mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-29 06:04:06 +00:00
feat(promql): run a root ranking over the evaluated per-series prefix
A `topk`/`bottomk` statement answers over the whole vector: which `k` series a group keeps at a grid point depends on every series present there, so a per-partition answer is that partition's best, not the query's. This adds one global node for exactly that root shape and leaves the parallel prefix alone. The prefix stays one `FusedSeries` per scan partition, so every partition still decodes and evaluates its own series. It now emits its evaluated chunks as rows of a private Arrow frame layout instead of the row table, carrying each chunk's complete labels, absolute grid positions, nulls and finality. Existing DataFusion operators gather and order those frames by producer and ordinal, and the new `VectorSelectExec` feeds them to one existing native runtime, which ranks only after the frames have all arrived. Nothing is gathered before it has been computed, and no raw input, wire format or region protocol is extended. Admission is a single logical check before any extension node exists, so a shape this node does not answer keeps the complete existing plan rather than failing at physical planning. It requires a root ranking over a tree that reads one series at a time, exactly one Float64 field, one raw input, and a table whose DDL leaves it one region: the frames are numbered by the region-local partition index, so more than one region cannot be told apart. The frame stream and the ranking release the schema and grid they read when they end or fail, so an ended stream a consumer keeps does not pin the statement's grid. The acceptance test runs a real standalone with four non-empty scan and fused partitions in one region, holds every fused partition until all four have computed a first batch, and compares the ranked answer with an independently computed top two of the unranked window and with the existing planner's answer. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -14,6 +14,7 @@
|
||||
|
||||
mod absent;
|
||||
mod empty_metric;
|
||||
mod evaluated_frame;
|
||||
mod fused_series;
|
||||
mod histogram_fold;
|
||||
mod instant_manipulate;
|
||||
@@ -25,6 +26,7 @@ mod series_divide;
|
||||
#[cfg(test)]
|
||||
mod test_util;
|
||||
mod union_distinct_on;
|
||||
mod vector_select;
|
||||
|
||||
pub use absent::{Absent, AbsentExec, AbsentStream};
|
||||
use common_query::native_histogram::{SUM_FIELD, native_histogram_value_type};
|
||||
@@ -49,6 +51,7 @@ pub use range_manipulate::{RangeManipulate, RangeManipulateExec, RangeManipulate
|
||||
pub use scalar_calculate::ScalarCalculate;
|
||||
pub use series_divide::{SeriesDivide, SeriesDivideExec, SeriesDivideStream};
|
||||
pub use union_distinct_on::{UnionDistinctOn, UnionDistinctOnExec, UnionDistinctOnStream};
|
||||
pub use vector_select::VectorSelect;
|
||||
|
||||
pub type Millisecond = <TimestampMillisecondType as ArrowPrimitiveType>::Native;
|
||||
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
// 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.
|
||||
|
||||
//! The private in-process frame between the parallel prefix and the global consumer.
|
||||
//!
|
||||
//! One [`EvaluatedChunk`] is one Arrow row of a fixed layout: the metric, its labels, the absolute
|
||||
//! grid positions the chunk carries and their values. The frame names no grid, so the consumer
|
||||
//! binds the [`SeriesSchema`] the chunks were evaluated against and the plan keeps that binding.
|
||||
//! An empty row is a real row: it is how a series closes without holding a value. DataFusion may
|
||||
//! rebatch, so [`read`] takes the row it wants and keeps nothing. [`Sequence`] checks the
|
||||
//! producer/ordinal ordering a single row cannot state.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::arrow::array::{
|
||||
Array, ArrayRef, BooleanArray, Float64Array, ListArray, StringArray, UInt64Array,
|
||||
};
|
||||
use datafusion::arrow::buffer::{OffsetBuffer, ScalarBuffer};
|
||||
use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::samples::{
|
||||
DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{GridSpan, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName};
|
||||
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
|
||||
/// The output stream the chunk belongs to.
|
||||
const PRODUCER: &str = "producer";
|
||||
/// The chunk's position in its producer's output.
|
||||
const FRAME_ORDINAL: &str = "frame_ordinal";
|
||||
/// The metric name; null when the series has none, empty when it is `""`.
|
||||
const METRIC_NAME: &str = "metric_name";
|
||||
/// The ordinary label names, parallel to [`LABEL_VALUES`].
|
||||
const LABEL_NAMES: &str = "label_names";
|
||||
/// The ordinary label values, parallel to [`LABEL_NAMES`].
|
||||
const LABEL_VALUES: &str = "label_values";
|
||||
/// The absolute grid positions of the chunk's rows.
|
||||
const POSITIONS: &str = "positions";
|
||||
/// The chunk's float values, parallel to [`POSITIONS`].
|
||||
const VALUES: &str = "values";
|
||||
/// Whether this chunk closes its series.
|
||||
const IS_LAST: &str = "is_last";
|
||||
/// Arrow's name for the child field of a list.
|
||||
const LIST_ITEM: &str = "item";
|
||||
|
||||
/// The fixed frame layout: only the metric name and the values may be null, and a label is absent
|
||||
/// by being absent from the parallel lists rather than by a null entry.
|
||||
pub(crate) fn schema() -> SchemaRef {
|
||||
let list = |name: &str, item: DataType, nullable: bool| {
|
||||
Field::new(
|
||||
name,
|
||||
DataType::List(Arc::new(Field::new(LIST_ITEM, item, nullable))),
|
||||
false,
|
||||
)
|
||||
};
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new(PRODUCER, DataType::UInt64, false),
|
||||
Field::new(FRAME_ORDINAL, DataType::UInt64, false),
|
||||
Field::new(METRIC_NAME, DataType::Utf8, true),
|
||||
list(LABEL_NAMES, DataType::Utf8, false),
|
||||
list(LABEL_VALUES, DataType::Utf8, false),
|
||||
list(POSITIONS, DataType::UInt64, false),
|
||||
list(VALUES, DataType::Float64, true),
|
||||
Field::new(IS_LAST, DataType::Boolean, false),
|
||||
]))
|
||||
}
|
||||
|
||||
/// Packs one evaluated chunk into a one-row batch of [`schema`].
|
||||
///
|
||||
/// `series_schema` must name exactly one field and one grid, and the chunk is validated against it
|
||||
/// through [`Series::try_new`] before the axis is reduced to positions. Samples must be float
|
||||
/// segments, so a histogram or mixed segment is refused even when it holds no row; chunked float
|
||||
/// segments are accepted. Nulls, NaN bits, sparse positions and an empty closing chunk are carried
|
||||
/// through unchanged.
|
||||
pub(crate) fn pack(
|
||||
chunk: &EvaluatedChunk,
|
||||
series_schema: &SeriesSchema,
|
||||
producer: u64,
|
||||
frame_ordinal: u64,
|
||||
) -> Result<RecordBatch> {
|
||||
if series_schema.fields.len() != 1 || series_schema.eval_grid.is_none() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"an evaluated frame requires one field and a grid".to_string(),
|
||||
));
|
||||
}
|
||||
let series = Series::try_new(
|
||||
series_schema,
|
||||
chunk.series.metric.clone(),
|
||||
chunk.series.time.clone(),
|
||||
chunk.series.fields.clone(),
|
||||
)
|
||||
.map_err(series_error)?;
|
||||
let samples =
|
||||
series.fields.as_slice().first().ok_or_else(|| {
|
||||
DataFusionError::Execution("evaluated chunk holds no field".to_string())
|
||||
})?;
|
||||
// Every segment is checked, so an empty histogram segment is refused just like a filled one.
|
||||
for segment in samples.segments() {
|
||||
if !matches!(segment.dense(), Some(DenseSamplesRef::Float(_))) {
|
||||
return Err(DataFusionError::NotImplemented(
|
||||
"an evaluated frame carries float samples only".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// `positions` walks the carried rows, so the holes between runs never become rows.
|
||||
let mut positions: Vec<u64> = Vec::with_capacity(samples.len());
|
||||
let mut values: Vec<Option<f64>> = Vec::with_capacity(samples.len());
|
||||
let mut cursor = samples.cursor();
|
||||
for (position, row) in series.time.positions() {
|
||||
positions.push(u64::try_from(position).map_err(|_| {
|
||||
DataFusionError::Execution("evaluated frame position does not fit UInt64".to_string())
|
||||
})?);
|
||||
match cursor.at(row) {
|
||||
Some(SampleRef::Float(value)) => values.push(Some(value)),
|
||||
Some(SampleRef::Missing) => values.push(None),
|
||||
Some(SampleRef::Histogram(_)) => {
|
||||
return Err(DataFusionError::NotImplemented(
|
||||
"an evaluated frame carries float samples only".to_string(),
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated chunk row {row} is missing from its field"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let names: Vec<&str> = series
|
||||
.metric
|
||||
.tags()
|
||||
.iter()
|
||||
.map(|tag| tag.name.as_ref())
|
||||
.collect();
|
||||
let labels: Vec<&str> = series
|
||||
.metric
|
||||
.tags()
|
||||
.iter()
|
||||
.map(|tag| tag.value.as_ref())
|
||||
.collect();
|
||||
let columns: Vec<ArrayRef> = vec![
|
||||
Arc::new(UInt64Array::from(vec![producer])),
|
||||
Arc::new(UInt64Array::from(vec![frame_ordinal])),
|
||||
Arc::new(StringArray::from(vec![series.metric.name()])),
|
||||
Arc::new(list(
|
||||
DataType::Utf8,
|
||||
false,
|
||||
Arc::new(StringArray::from(names)),
|
||||
)?),
|
||||
Arc::new(list(
|
||||
DataType::Utf8,
|
||||
false,
|
||||
Arc::new(StringArray::from(labels)),
|
||||
)?),
|
||||
Arc::new(list(
|
||||
DataType::UInt64,
|
||||
false,
|
||||
Arc::new(UInt64Array::from(positions)),
|
||||
)?),
|
||||
Arc::new(list(
|
||||
DataType::Float64,
|
||||
true,
|
||||
Arc::new(Float64Array::from(values)),
|
||||
)?),
|
||||
Arc::new(BooleanArray::from(vec![chunk.is_last])),
|
||||
];
|
||||
Ok(RecordBatch::try_new(schema(), columns)?)
|
||||
}
|
||||
|
||||
/// Reads the chunk held by `row` of `batch`.
|
||||
///
|
||||
/// `series_schema` is the binding that supplies the grid absolute positions refer to: it must name
|
||||
/// exactly one field and one grid. The batch must carry exactly [`schema`], every required column
|
||||
/// must be non-null at `row`, the label lists must be parallel and name one label set (`__name__`
|
||||
/// stays the metric name), positions must be strictly increasing and inside the grid, and one value
|
||||
/// must exist per position. The axis is rebuilt compactly, so no row is materialized for a hole.
|
||||
pub(crate) fn read(
|
||||
batch: &RecordBatch,
|
||||
row: usize,
|
||||
series_schema: &Arc<SeriesSchema>,
|
||||
) -> Result<(u64, u64, EvaluatedChunk)> {
|
||||
if batch.schema().as_ref() != schema().as_ref() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated frame schema mismatch".to_string(),
|
||||
));
|
||||
}
|
||||
if row >= batch.num_rows() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame row {row} is outside a batch of {} rows",
|
||||
batch.num_rows()
|
||||
)));
|
||||
}
|
||||
if series_schema.fields.len() != 1 {
|
||||
return Err(DataFusionError::Execution(
|
||||
"an evaluated frame requires one field".to_string(),
|
||||
));
|
||||
}
|
||||
let Some(grid) = series_schema.eval_grid.clone() else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"an evaluated frame requires a grid".to_string(),
|
||||
));
|
||||
};
|
||||
let columns = batch.columns();
|
||||
for (column, index) in [
|
||||
(PRODUCER, 0),
|
||||
(FRAME_ORDINAL, 1),
|
||||
(LABEL_NAMES, 3),
|
||||
(LABEL_VALUES, 4),
|
||||
(POSITIONS, 5),
|
||||
(VALUES, 6),
|
||||
(IS_LAST, 7),
|
||||
] {
|
||||
if columns[index].is_null(row) {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame requires a non-null {column} at row {row}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let producers = down::<UInt64Array>(&columns[0], PRODUCER)?;
|
||||
let ordinals = down::<UInt64Array>(&columns[1], FRAME_ORDINAL)?;
|
||||
let names = down::<StringArray>(&columns[2], METRIC_NAME)?;
|
||||
let label_names = down::<ListArray>(&columns[3], LABEL_NAMES)?;
|
||||
let label_values = down::<ListArray>(&columns[4], LABEL_VALUES)?;
|
||||
let position_list = down::<ListArray>(&columns[5], POSITIONS)?;
|
||||
let value_list = down::<ListArray>(&columns[6], VALUES)?;
|
||||
let lasts = down::<BooleanArray>(&columns[7], IS_LAST)?;
|
||||
|
||||
let name = (!names.is_null(row)).then(|| Arc::<str>::from(names.value(row)));
|
||||
let names = strings(label_names, row, LABEL_NAMES)?;
|
||||
let labels = strings(label_values, row, LABEL_VALUES)?;
|
||||
if names.len() != labels.len() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame has {} label names and {} label values",
|
||||
names.len(),
|
||||
labels.len()
|
||||
)));
|
||||
}
|
||||
let tags: Vec<Label> = names
|
||||
.into_iter()
|
||||
.zip(labels)
|
||||
.map(|(name, value)| Label { name, value })
|
||||
.collect();
|
||||
// The constructor sorts the labels and refuses duplicate names and a `__name__` tag.
|
||||
let metric = MetricName::try_new(name, tags).map_err(series_error)?;
|
||||
|
||||
let positions = positions(position_list, row, grid.spec().len)?;
|
||||
let value_array = value_list.value(row);
|
||||
let values = down::<Float64Array>(&value_array, VALUES)?;
|
||||
if positions.len() != values.len() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame has {} positions and {} values",
|
||||
positions.len(),
|
||||
values.len()
|
||||
)));
|
||||
}
|
||||
let axis = TimeAxis::from_grid_spans(grid, run_spans(&positions)).map_err(series_error)?;
|
||||
let fields = SeriesFields::try_from_vec(vec![Samples::from_float(values.clone())])
|
||||
.map_err(series_error)?;
|
||||
let series = Series::try_new(series_schema, metric, axis, fields).map_err(series_error)?;
|
||||
let is_last = lasts.value(row);
|
||||
let chunk = EvaluatedChunk::try_new(series, is_last)?;
|
||||
Ok((producers.value(row), ordinals.value(row), chunk))
|
||||
}
|
||||
|
||||
/// Builds a one-row list over `values`, refusing a row Arrow's `i32` offsets cannot address.
|
||||
fn list(item: DataType, nullable: bool, values: ArrayRef) -> Result<ListArray> {
|
||||
let len = i32::try_from(values.len()).map_err(|_| {
|
||||
DataFusionError::Execution("evaluated frame row is longer than Arrow addresses".to_string())
|
||||
})?;
|
||||
let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0, len]));
|
||||
let item = Arc::new(Field::new(LIST_ITEM, item, nullable));
|
||||
Ok(ListArray::try_new(item, offsets, values, None)?)
|
||||
}
|
||||
|
||||
/// Reads the non-null UTF-8 entries of one list row.
|
||||
fn strings(array: &ListArray, row: usize, column: &str) -> Result<Vec<Arc<str>>> {
|
||||
let row_values = array.value(row);
|
||||
let values = down::<StringArray>(&row_values, column)?;
|
||||
if values.null_count() != 0 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame requires non-null {column} entries at row {row}"
|
||||
)));
|
||||
}
|
||||
Ok((0..values.len())
|
||||
.map(|index| Arc::<str>::from(values.value(index)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Reads one list row of positions, checking strict order and grid bounds.
|
||||
fn positions(array: &ListArray, row: usize, grid_len: u64) -> Result<Vec<usize>> {
|
||||
let row_values = array.value(row);
|
||||
let values = down::<UInt64Array>(&row_values, POSITIONS)?;
|
||||
if values.null_count() != 0 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame requires non-null positions at row {row}"
|
||||
)));
|
||||
}
|
||||
let mut positions: Vec<usize> = Vec::with_capacity(values.len());
|
||||
for index in 0..values.len() {
|
||||
let position = values.value(index);
|
||||
if position >= grid_len {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame position {position} is outside a grid of {grid_len} points"
|
||||
)));
|
||||
}
|
||||
let position = usize::try_from(position).map_err(|_| {
|
||||
DataFusionError::Execution("evaluated frame position does not fit usize".to_string())
|
||||
})?;
|
||||
if positions.last().is_some_and(|last| *last >= position) {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame positions must be strictly increasing, {position} is not"
|
||||
)));
|
||||
}
|
||||
positions.push(position);
|
||||
}
|
||||
Ok(positions)
|
||||
}
|
||||
|
||||
/// The maximal runs of consecutive absolute positions, in order.
|
||||
fn run_spans(positions: &[usize]) -> Vec<GridSpan> {
|
||||
let mut spans: Vec<GridSpan> = Vec::new();
|
||||
for &position in positions {
|
||||
match spans.last_mut() {
|
||||
Some(span) if span.start() + span.len() == position => {
|
||||
*span = GridSpan::new(span.start(), span.len() + 1);
|
||||
}
|
||||
_ => spans.push(GridSpan::new(position, 1)),
|
||||
}
|
||||
}
|
||||
spans
|
||||
}
|
||||
|
||||
/// Downcasts one column to its declared Arrow type.
|
||||
fn down<'a, T: Array + 'static>(array: &'a ArrayRef, column: &str) -> Result<&'a T> {
|
||||
array.as_any().downcast_ref::<T>().ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"evaluated frame column {column} has an unexpected type"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reports a series-model rejection as the execution error the caller sees.
|
||||
fn series_error(error: datatypes::error::Error) -> DataFusionError {
|
||||
DataFusionError::External(Box::new(error))
|
||||
}
|
||||
|
||||
/// Orders the frames of one execution's output by producer and frame ordinal.
|
||||
///
|
||||
/// A producer's frames start at ordinal 0 and follow without gaps, whatever their finality, since
|
||||
/// one producer hands over many series and each closes once on its own frame. Switching producer
|
||||
/// requires the previous one to have closed, producers are numbered strictly upwards, and the
|
||||
/// execution ends on a closing frame. The state is three scalars: labels, positions, occurrence
|
||||
/// identity and per-producer history stay with the runtime that already owns them.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Sequence {
|
||||
previous_producer: Option<u64>,
|
||||
next_ordinal: u64,
|
||||
last_closed: bool,
|
||||
}
|
||||
|
||||
impl Sequence {
|
||||
/// Records the next frame, rejecting an ordinal out of order, a producer boundary before the
|
||||
/// previous producer closed, and a producer that goes backwards.
|
||||
pub(crate) fn check(&mut self, producer: u64, ordinal: u64, is_last: bool) -> Result<()> {
|
||||
let expected = match self.previous_producer {
|
||||
None => 0,
|
||||
Some(previous) if producer == previous => self.next_ordinal,
|
||||
Some(previous) => {
|
||||
if producer < previous {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame producer {producer} goes backwards from {previous}"
|
||||
)));
|
||||
}
|
||||
if !self.last_closed {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame of producer {producer} starts before producer {previous} \
|
||||
closed"
|
||||
)));
|
||||
}
|
||||
0
|
||||
}
|
||||
};
|
||||
if ordinal != expected {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame of producer {producer} has ordinal {ordinal}, expected {expected}"
|
||||
)));
|
||||
}
|
||||
let next = ordinal.checked_add(1).ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"evaluated frame ordinal {ordinal} of producer {producer} cannot be incremented"
|
||||
))
|
||||
})?;
|
||||
self.previous_producer = Some(producer);
|
||||
self.next_ordinal = next;
|
||||
self.last_closed = is_last;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that the sequence ended on a closing frame, if it began at all.
|
||||
pub(crate) fn finish(&self) -> Result<()> {
|
||||
match self.previous_producer {
|
||||
Some(producer) if !self.last_closed => Err(DataFusionError::Execution(format!(
|
||||
"evaluated frame producer {producer} ended without a closing frame"
|
||||
))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,670 @@
|
||||
// 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.
|
||||
|
||||
//! What the evaluated frame has to carry unchanged and what it has to refuse.
|
||||
//!
|
||||
//! The chunks here are what an evaluator hands over: absolute positions on a shared grid, with
|
||||
//! holes between the runs it decided. Pack and read are checked against each other for the shapes
|
||||
//! that matter (sparse runs, chunked floats, an empty close, absent and empty labels) and against
|
||||
//! malformed input on their own. The sequence checks are scalar, so they need no chunks.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::arrow::array::{
|
||||
ArrayRef, Float64Array, ListArray, StringArray, UInt32Array, UInt64Array,
|
||||
};
|
||||
use datafusion::arrow::buffer::ScalarBuffer;
|
||||
use datafusion::arrow::compute::concat_batches;
|
||||
use datafusion::arrow::datatypes::{DataType, Field, Schema};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::error::DataFusionError;
|
||||
use datatypes::series::histogram::HistogramBatchBuilder;
|
||||
use datatypes::series::samples::{
|
||||
FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName};
|
||||
|
||||
use super::{
|
||||
FRAME_ORDINAL, IS_LAST, LABEL_NAMES, LABEL_VALUES, POSITIONS, PRODUCER, Sequence, VALUES, list,
|
||||
pack, read, schema,
|
||||
};
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
|
||||
const VALUE: &str = "value";
|
||||
const GRID_START_MS: i64 = 300_000;
|
||||
const GRID_STEP_MS: i64 = 60_000;
|
||||
const GRID_LEN: u64 = 8;
|
||||
|
||||
fn grid(start_ms: i64, len: u64) -> Arc<EvalGrid> {
|
||||
Arc::new(EvalGrid::try_new(GridSpec::try_new(start_ms, GRID_STEP_MS, len).unwrap()).unwrap())
|
||||
}
|
||||
|
||||
fn one_field() -> Arc<[FieldSpec]> {
|
||||
Arc::from([FieldSpec { name: VALUE.into() }])
|
||||
}
|
||||
|
||||
fn schema_on(grid: Arc<EvalGrid>) -> SeriesSchema {
|
||||
SeriesSchema {
|
||||
fields: one_field(),
|
||||
eval_grid: Some(grid),
|
||||
}
|
||||
}
|
||||
|
||||
fn series_schema() -> SeriesSchema {
|
||||
schema_on(grid(GRID_START_MS, GRID_LEN))
|
||||
}
|
||||
|
||||
fn two_field_schema(grid: Arc<EvalGrid>) -> SeriesSchema {
|
||||
SeriesSchema {
|
||||
fields: Arc::from([
|
||||
FieldSpec { name: VALUE.into() },
|
||||
FieldSpec {
|
||||
name: "other".into(),
|
||||
},
|
||||
]),
|
||||
eval_grid: Some(grid),
|
||||
}
|
||||
}
|
||||
|
||||
fn bound(schema: &SeriesSchema) -> Arc<SeriesSchema> {
|
||||
Arc::new(schema.clone())
|
||||
}
|
||||
|
||||
fn metric(name: Option<&str>, tags: &[(&str, &str)]) -> MetricName {
|
||||
MetricName::try_new(
|
||||
name.map(Arc::<str>::from),
|
||||
tags.iter()
|
||||
.map(|(name, value)| Label {
|
||||
name: Arc::<str>::from(*name),
|
||||
value: Arc::<str>::from(*value),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn sample(value: Option<f64>) -> Samples {
|
||||
Samples::from_float(Float64Array::from(vec![value]))
|
||||
}
|
||||
|
||||
fn chunk_with(
|
||||
schema: &SeriesSchema,
|
||||
metric: MetricName,
|
||||
spans: Vec<GridSpan>,
|
||||
samples: Samples,
|
||||
is_last: bool,
|
||||
) -> EvaluatedChunk {
|
||||
let axis = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap();
|
||||
let series = Series::try_new(schema, metric, axis, SeriesFields::one(samples)).unwrap();
|
||||
EvaluatedChunk::try_new(series, is_last).unwrap()
|
||||
}
|
||||
|
||||
/// A chunk over `runs`, each `(start position, one value or null per row)`.
|
||||
fn chunk(
|
||||
schema: &SeriesSchema,
|
||||
metric: MetricName,
|
||||
runs: &[(usize, Vec<Option<f64>>)],
|
||||
is_last: bool,
|
||||
) -> EvaluatedChunk {
|
||||
let mut spans = Vec::new();
|
||||
let mut values = Vec::new();
|
||||
for (start, run) in runs {
|
||||
if run.is_empty() {
|
||||
continue;
|
||||
}
|
||||
spans.push(GridSpan::new(*start, run.len()));
|
||||
values.extend(run.iter().copied());
|
||||
}
|
||||
chunk_with(
|
||||
schema,
|
||||
metric,
|
||||
spans,
|
||||
Samples::from_float(Float64Array::from(values)),
|
||||
is_last,
|
||||
)
|
||||
}
|
||||
|
||||
fn two_field_evaluated(schema: &SeriesSchema) -> EvaluatedChunk {
|
||||
let axis =
|
||||
TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), vec![GridSpan::new(0, 1)])
|
||||
.unwrap();
|
||||
let fields = SeriesFields::try_from_vec(vec![sample(Some(1.0)), sample(Some(2.0))]).unwrap();
|
||||
let series = Series::try_new(schema, metric(Some("m"), &[]), axis, fields).unwrap();
|
||||
EvaluatedChunk::try_new(series, true).unwrap()
|
||||
}
|
||||
|
||||
fn positions_of(chunk: &EvaluatedChunk) -> Vec<usize> {
|
||||
chunk
|
||||
.series
|
||||
.time
|
||||
.positions()
|
||||
.map(|(position, _)| position)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The chunks' float values by bits, so a NaN payload is compared, not just `is_nan`.
|
||||
fn float_bits(chunk: &EvaluatedChunk) -> Vec<Option<u64>> {
|
||||
chunk.series.fields.as_slice()[0]
|
||||
.iter()
|
||||
.map(|sample| match sample {
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Float(value) => Some(value.to_bits()),
|
||||
SampleRef::Histogram(_) => panic!("the test chunk holds a histogram"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One frame of producer `producer` with a metric and a single point.
|
||||
fn packed(schema: &SeriesSchema, producer: u64, ordinal: u64, is_last: bool) -> RecordBatch {
|
||||
let chunk = chunk(
|
||||
schema,
|
||||
metric(Some("m"), &[("a", "1")]),
|
||||
&[(0, vec![Some(1.0)])],
|
||||
is_last,
|
||||
);
|
||||
pack(&chunk, schema, producer, ordinal).unwrap()
|
||||
}
|
||||
|
||||
fn one_row(item: DataType, nullable: bool, values: ArrayRef) -> ListArray {
|
||||
list(item, nullable, values).unwrap()
|
||||
}
|
||||
|
||||
fn replace(batch: &RecordBatch, column: &str, values: ArrayRef) -> RecordBatch {
|
||||
let index = batch.schema().index_of(column).unwrap();
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns[index] = values;
|
||||
RecordBatch::try_new(batch.schema(), columns).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_is_the_fixed_evaluated_frame_layout() {
|
||||
let column = |item: DataType, nullable: bool| {
|
||||
DataType::List(Arc::new(Field::new("item", item, nullable)))
|
||||
};
|
||||
let expected = Schema::new(vec![
|
||||
Field::new("producer", DataType::UInt64, false),
|
||||
Field::new("frame_ordinal", DataType::UInt64, false),
|
||||
Field::new("metric_name", DataType::Utf8, true),
|
||||
Field::new("label_names", column(DataType::Utf8, false), false),
|
||||
Field::new("label_values", column(DataType::Utf8, false), false),
|
||||
Field::new("positions", column(DataType::UInt64, false), false),
|
||||
Field::new("values", column(DataType::Float64, true), false),
|
||||
Field::new("is_last", DataType::Boolean, false),
|
||||
]);
|
||||
assert_eq!(schema().as_ref(), &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_preserves_sparse_positions_nulls_and_nan_bits() {
|
||||
let series_schema = series_schema();
|
||||
let metric = metric(None, &[("host", "a"), ("empty", "")]);
|
||||
let nan = f64::from_bits(0x7ff8_0000_0000_0001);
|
||||
let chunk = chunk(
|
||||
&series_schema,
|
||||
metric.clone(),
|
||||
&[(1, vec![Some(1.5), None]), (4, vec![Some(nan), Some(-0.0)])],
|
||||
true,
|
||||
);
|
||||
let batch = pack(&chunk, &series_schema, 7, 3).unwrap();
|
||||
assert_eq!(batch.num_rows(), 1);
|
||||
assert_eq!(batch.schema().as_ref(), schema().as_ref());
|
||||
|
||||
let (producer, ordinal, read) = read(&batch, 0, &bound(&series_schema)).unwrap();
|
||||
assert_eq!((producer, ordinal), (7, 3));
|
||||
assert!(read.is_last);
|
||||
assert_eq!(read.series.metric, metric);
|
||||
assert_eq!(positions_of(&read), vec![1, 2, 4, 5]);
|
||||
assert_eq!(
|
||||
float_bits(&read),
|
||||
vec![
|
||||
Some(1.5f64.to_bits()),
|
||||
None,
|
||||
Some(nan.to_bits()),
|
||||
Some((-0.0f64).to_bits()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_keeps_an_absent_metric_name_distinct_from_an_empty_one() {
|
||||
let series_schema = series_schema();
|
||||
for name in [None, Some("")] {
|
||||
let metric = metric(name, &[("a", "")]);
|
||||
let chunk = chunk(
|
||||
&series_schema,
|
||||
metric.clone(),
|
||||
&[(2, vec![Some(1.0)])],
|
||||
false,
|
||||
);
|
||||
let batch = pack(&chunk, &series_schema, 0, 1).unwrap();
|
||||
let (_, _, read) = read(&batch, 0, &bound(&series_schema)).unwrap();
|
||||
assert_eq!(read.series.metric, metric);
|
||||
assert_eq!(read.series.metric.name(), name);
|
||||
assert_eq!(read.series.metric.get("a"), Some(""));
|
||||
assert!(!read.is_last);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_closing_chunk_is_still_one_row() {
|
||||
let series_schema = series_schema();
|
||||
let metric = metric(Some("m"), &[("a", "1")]);
|
||||
let chunk = chunk(&series_schema, metric.clone(), &[], true);
|
||||
let batch = pack(&chunk, &series_schema, 2, 0).unwrap();
|
||||
assert_eq!(batch.num_rows(), 1);
|
||||
|
||||
let (producer, ordinal, read) = read(&batch, 0, &bound(&series_schema)).unwrap();
|
||||
assert_eq!((producer, ordinal), (2, 0));
|
||||
assert!(read.is_last);
|
||||
assert_eq!(read.series.metric, metric);
|
||||
assert!(read.series.time.is_empty());
|
||||
assert!(positions_of(&read).is_empty());
|
||||
assert!(float_bits(&read).is_empty());
|
||||
assert_eq!(
|
||||
read.series.time.grid().map(|grid| grid.spec()),
|
||||
Some(series_schema.eval_grid.as_ref().unwrap().spec())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunked_float_samples_round_trip() {
|
||||
let series_schema = series_schema();
|
||||
let nan = f64::from_bits(0x7ff8_0000_0000_0002);
|
||||
let samples = Samples::try_from_chunks(vec![
|
||||
Samples::from_float(Float64Array::from(vec![Some(1.0), None])),
|
||||
Samples::from_float(Float64Array::from(vec![Some(nan)])),
|
||||
])
|
||||
.unwrap();
|
||||
let chunk = chunk_with(
|
||||
&series_schema,
|
||||
metric(Some("m"), &[]),
|
||||
vec![GridSpan::new(2, 3)],
|
||||
samples,
|
||||
false,
|
||||
);
|
||||
let batch = pack(&chunk, &series_schema, 1, 0).unwrap();
|
||||
let (_, _, read) = read(&batch, 0, &bound(&series_schema)).unwrap();
|
||||
assert_eq!(positions_of(&read), vec![2, 3, 4]);
|
||||
assert_eq!(
|
||||
float_bits(&read),
|
||||
vec![Some(1.0f64.to_bits()), None, Some(nan.to_bits())]
|
||||
);
|
||||
assert!(!read.is_last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_accepts_a_rebatched_batch_at_any_row() {
|
||||
let series_schema = series_schema();
|
||||
let mut batches = Vec::new();
|
||||
for (ordinal, name) in ["a", "b", "c"].into_iter().enumerate() {
|
||||
let chunk = chunk(
|
||||
&series_schema,
|
||||
metric(Some(name), &[]),
|
||||
&[(ordinal, vec![Some(ordinal as f64)])],
|
||||
ordinal == 2,
|
||||
);
|
||||
batches.push(pack(&chunk, &series_schema, 0, ordinal as u64).unwrap());
|
||||
}
|
||||
let combined = concat_batches(&schema(), &batches).unwrap();
|
||||
assert_eq!(combined.num_rows(), 3);
|
||||
|
||||
for (row, name, is_last) in [(2usize, "c", true), (0, "a", false), (1, "b", false)] {
|
||||
let (producer, ordinal, read) = read(&combined, row, &bound(&series_schema)).unwrap();
|
||||
assert_eq!((producer, ordinal), (0, row as u64));
|
||||
assert_eq!(read.series.metric.name(), Some(name));
|
||||
assert_eq!(read.is_last, is_last);
|
||||
assert_eq!(float_bits(&read), vec![Some((row as f64).to_bits())]);
|
||||
}
|
||||
|
||||
// DataFusion may hand over a slice of a larger batch, not only whole batches.
|
||||
let sliced = combined.slice(1, 1);
|
||||
let (_, ordinal, read) = read(&sliced, 0, &bound(&series_schema)).unwrap();
|
||||
assert_eq!(ordinal, 1);
|
||||
assert_eq!(read.series.metric.name(), Some("b"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pack_refuses_a_chunk_the_bound_schema_does_not_describe() {
|
||||
let series_schema = series_schema();
|
||||
let two_fields = two_field_schema(series_schema.eval_grid.clone().unwrap());
|
||||
let two_field_chunk = two_field_evaluated(&two_fields);
|
||||
let no_grid = SeriesSchema {
|
||||
fields: one_field(),
|
||||
eval_grid: None,
|
||||
};
|
||||
let explicit = {
|
||||
let time = TimeAxis::try_new(ScalarBuffer::from(vec![0i64])).unwrap();
|
||||
let series = Series::try_new(
|
||||
&no_grid,
|
||||
metric(Some("m"), &[]),
|
||||
time,
|
||||
SeriesFields::one(sample(Some(1.0))),
|
||||
)
|
||||
.unwrap();
|
||||
// `try_new` refuses an explicit axis, so the invalid chunk is built literally: this is
|
||||
// the producer defect `pack` has to catch.
|
||||
EvaluatedChunk {
|
||||
series,
|
||||
is_last: true,
|
||||
}
|
||||
};
|
||||
let other_grid = schema_on(grid(GRID_START_MS - GRID_STEP_MS, GRID_LEN));
|
||||
let wrong_grid = chunk(
|
||||
&other_grid,
|
||||
metric(Some("m"), &[]),
|
||||
&[(0, vec![Some(1.0)])],
|
||||
true,
|
||||
);
|
||||
let cases = [
|
||||
("two-field schema", &two_fields, &two_field_chunk),
|
||||
("two-field chunk", &series_schema, &two_field_chunk),
|
||||
("schema without a grid", &no_grid, &explicit),
|
||||
("chunk without a grid", &series_schema, &explicit),
|
||||
("chunk on another grid", &series_schema, &wrong_grid),
|
||||
];
|
||||
for (case, bound_schema, chunk) in cases {
|
||||
assert!(
|
||||
pack(chunk, bound_schema, 0, 0).is_err(),
|
||||
"{case} was packed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pack_refuses_histogram_and_mixed_samples_even_when_empty() {
|
||||
let series_schema = series_schema();
|
||||
let histogram = Samples::try_from_histogram(
|
||||
UInt32Array::from(Vec::<u32>::new()),
|
||||
HistogramBatchBuilder::new().finish().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mixed = Samples::try_from_mixed(
|
||||
Float64Array::from(Vec::<f64>::new()),
|
||||
HistogramSamples::try_new(
|
||||
UInt32Array::from(Vec::<u32>::new()),
|
||||
HistogramBatchBuilder::new().finish().unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
for (case, samples) in [("histogram", histogram), ("mixed", mixed)] {
|
||||
let chunk = chunk_with(
|
||||
&series_schema,
|
||||
metric(Some("h"), &[]),
|
||||
Vec::new(),
|
||||
samples,
|
||||
true,
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
pack(&chunk, &series_schema, 0, 0),
|
||||
Err(DataFusionError::NotImplemented(_))
|
||||
),
|
||||
"{case} samples were packed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_refuses_null_required_columns() {
|
||||
let series_schema = series_schema();
|
||||
let batch = packed(&series_schema, 0, 0, false);
|
||||
for column in [
|
||||
PRODUCER,
|
||||
FRAME_ORDINAL,
|
||||
LABEL_NAMES,
|
||||
LABEL_VALUES,
|
||||
POSITIONS,
|
||||
VALUES,
|
||||
IS_LAST,
|
||||
] {
|
||||
let index = batch.schema().index_of(column).unwrap();
|
||||
let field = batch.schema().field(index).clone();
|
||||
let nulls = datafusion::arrow::array::new_null_array(field.data_type(), 1);
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns[index] = nulls;
|
||||
assert!(
|
||||
RecordBatch::try_new(batch.schema(), columns.clone()).is_err(),
|
||||
"Arrow accepted a null {column}"
|
||||
);
|
||||
|
||||
// The same nulls under a schema that claims the column nullable: Arrow builds it, and
|
||||
// only the fixed-layout check stands between it and the reader.
|
||||
let mut fields = batch.schema().fields().to_vec();
|
||||
fields[index] = Arc::new(field.with_nullable(true));
|
||||
let foreign = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
|
||||
let error = read(&foreign, 0, &bound(&series_schema)).unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("schema mismatch"),
|
||||
"a null {column} reported {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_refuses_positions_that_are_not_strictly_ordered_or_in_bounds() {
|
||||
let series_schema = series_schema();
|
||||
let batch = packed(&series_schema, 0, 0, false);
|
||||
let cases = [
|
||||
("duplicate", vec![1u64, 1]),
|
||||
("backwards", vec![2, 1]),
|
||||
("out of bounds", vec![GRID_LEN]),
|
||||
("length mismatch", vec![0, 1]),
|
||||
];
|
||||
for (case, positions) in cases {
|
||||
let malformed = replace(
|
||||
&batch,
|
||||
POSITIONS,
|
||||
Arc::new(one_row(
|
||||
DataType::UInt64,
|
||||
false,
|
||||
Arc::new(UInt64Array::from(positions)),
|
||||
)),
|
||||
);
|
||||
assert!(
|
||||
read(&malformed, 0, &bound(&series_schema)).is_err(),
|
||||
"positions {case} were accepted"
|
||||
);
|
||||
}
|
||||
|
||||
let malformed = replace(
|
||||
&batch,
|
||||
VALUES,
|
||||
Arc::new(one_row(
|
||||
DataType::Float64,
|
||||
true,
|
||||
Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0)])),
|
||||
)),
|
||||
);
|
||||
assert!(read(&malformed, 0, &bound(&series_schema)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_refuses_label_lists_that_are_not_one_label_set() {
|
||||
let series_schema = series_schema();
|
||||
let batch = packed(&series_schema, 0, 0, false);
|
||||
let cases = [
|
||||
(
|
||||
"duplicate names",
|
||||
vec!["a", "a"],
|
||||
vec!["1", "2"],
|
||||
"duplicate label name",
|
||||
),
|
||||
(
|
||||
"unequal lengths",
|
||||
vec!["a", "b"],
|
||||
vec!["1"],
|
||||
"label names and",
|
||||
),
|
||||
("name as a tag", vec!["__name__"], vec!["x"], "__name__"),
|
||||
];
|
||||
for (case, names, values, expected) in cases {
|
||||
let pair = |values: Vec<&str>| {
|
||||
Arc::new(one_row(
|
||||
DataType::Utf8,
|
||||
false,
|
||||
Arc::new(StringArray::from(values)),
|
||||
))
|
||||
};
|
||||
let malformed = replace(&batch, LABEL_NAMES, pair(names));
|
||||
let malformed = replace(&malformed, LABEL_VALUES, pair(values));
|
||||
let error = read(&malformed, 0, &bound(&series_schema)).unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains(expected),
|
||||
"{case} reported {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_refuses_a_batch_that_is_not_the_fixed_layout() {
|
||||
let series_schema = series_schema();
|
||||
let batch = packed(&series_schema, 0, 0, false);
|
||||
|
||||
assert!(read(&batch, 1, &bound(&series_schema)).is_err());
|
||||
|
||||
let fields: Vec<Field> = batch
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let nullable = field.is_nullable() || field.name() == PRODUCER;
|
||||
Field::new(field.name().as_str(), field.data_type().clone(), nullable)
|
||||
})
|
||||
.collect();
|
||||
let foreign =
|
||||
RecordBatch::try_new(Arc::new(Schema::new(fields)), batch.columns().to_vec()).unwrap();
|
||||
assert!(read(&foreign, 0, &bound(&series_schema)).is_err());
|
||||
|
||||
let short = RecordBatch::try_new(
|
||||
Arc::new(Schema::new(batch.schema().fields()[..7].to_vec())),
|
||||
batch.columns()[..7].to_vec(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(read(&short, 0, &bound(&series_schema)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_refuses_a_binding_it_cannot_address() {
|
||||
let series_schema = series_schema();
|
||||
let batch = packed(&series_schema, 0, 0, false);
|
||||
let two_fields = two_field_schema(series_schema.eval_grid.clone().unwrap());
|
||||
assert!(read(&batch, 0, &bound(&two_fields)).is_err());
|
||||
let no_grid = SeriesSchema {
|
||||
fields: one_field(),
|
||||
eval_grid: None,
|
||||
};
|
||||
assert!(read(&batch, 0, &bound(&no_grid)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_accepts_frames_in_producer_order() {
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.finish().unwrap();
|
||||
sequence.check(0, 0, false).unwrap();
|
||||
sequence.check(0, 1, false).unwrap();
|
||||
sequence.check(0, 2, true).unwrap();
|
||||
// A later producer number may skip values; only a decrease is backwards.
|
||||
sequence.check(2, 0, false).unwrap();
|
||||
sequence.check(2, 1, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_duplicate_gapped_and_first_nonzero_ordinals() {
|
||||
let mut sequence = Sequence::default();
|
||||
assert!(sequence.check(0, 1, false).is_err());
|
||||
sequence.check(0, 0, false).unwrap();
|
||||
assert!(sequence.check(0, 0, false).is_err());
|
||||
assert!(sequence.check(0, 2, false).is_err());
|
||||
// The rejected frames left the sequence where it was.
|
||||
sequence.check(0, 1, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_accepts_many_closed_series_from_one_producer() {
|
||||
// One producer hands over many series, so a closing frame ends a series and not the producer:
|
||||
// the next frame of that producer is still expected, as the pattern Main accepts shows.
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(0, 0, true).unwrap();
|
||||
sequence.check(0, 1, true).unwrap();
|
||||
sequence.check(0, 2, false).unwrap();
|
||||
sequence.check(0, 3, true).unwrap();
|
||||
sequence.check(1, 0, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_a_new_producer_before_the_previous_closed() {
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(0, 0, false).unwrap();
|
||||
assert!(sequence.check(1, 0, true).is_err());
|
||||
sequence.check(0, 1, true).unwrap();
|
||||
sequence.check(1, 0, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
|
||||
// A closed frame only closes the series it carried, so it does not end its producer either.
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(0, 0, true).unwrap();
|
||||
sequence.check(0, 1, false).unwrap();
|
||||
assert!(sequence.check(1, 0, true).is_err());
|
||||
sequence.check(0, 2, true).unwrap();
|
||||
sequence.check(1, 0, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_a_backwards_producer() {
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(2, 0, true).unwrap();
|
||||
assert!(sequence.check(1, 0, true).is_err());
|
||||
assert!(sequence.check(2, 0, true).is_err());
|
||||
// The rejected frames left the sequence where it was.
|
||||
sequence.check(2, 1, true).unwrap();
|
||||
sequence.check(3, 0, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_a_new_producer_with_a_nonzero_ordinal() {
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(0, 0, true).unwrap();
|
||||
assert!(sequence.check(1, 3, true).is_err());
|
||||
sequence.check(1, 0, true).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_finish_requires_the_last_frame_to_close() {
|
||||
let mut sequence = Sequence::default();
|
||||
sequence.check(0, 0, false).unwrap();
|
||||
assert!(sequence.finish().is_err());
|
||||
sequence.check(0, 1, true).unwrap();
|
||||
sequence.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_rejects_an_ordinal_that_cannot_be_incremented() {
|
||||
// No real stream reaches this state, but the checked increment is what keeps the state from
|
||||
// wrapping; the fields are set directly so the guard itself is exercised.
|
||||
let mut sequence = Sequence {
|
||||
previous_producer: Some(0),
|
||||
next_ordinal: u64::MAX,
|
||||
last_closed: false,
|
||||
};
|
||||
assert!(sequence.check(0, u64::MAX, true).is_err());
|
||||
assert_eq!(sequence.next_ordinal, u64::MAX);
|
||||
assert!(!sequence.last_closed);
|
||||
}
|
||||
@@ -31,7 +31,9 @@
|
||||
//! chunk, carrying the series' encoded key, its finality, its timestamps and its fields, plus the
|
||||
//! complete labels when the frame is explicit — with each series' rows contiguous and its
|
||||
//! timestamps ascending, which is what the caller's [`SeriesOrdering`] names. The output is one
|
||||
//! batch per evaluated chunk, with the statement's grid timestamps in the declared time column.
|
||||
//! batch per evaluated chunk, with the statement's grid timestamps in the declared time column; a
|
||||
//! node built in frame mode ([`FusedSeries::try_new_evaluated`]) emits the same chunks as rows of
|
||||
//! [`super::evaluated_frame`]'s layout instead.
|
||||
//! Everything the tree cannot do is rejected when the execution plan is built, not when the first
|
||||
//! batch arrives: a tree the native runtime does not execute, a frame whose schema the tree's input
|
||||
//! was not compiled against, or an output schema the conversion cannot classify.
|
||||
@@ -52,8 +54,8 @@ use datafusion::arrow::array::{
|
||||
use datafusion::arrow::buffer::ScalarBuffer;
|
||||
use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::common::DFSchemaRef;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::common::{DFSchemaRef, ToDFSchema};
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::context::TaskContext;
|
||||
use datafusion::execution::memory_pool::{
|
||||
@@ -69,7 +71,9 @@ use datafusion::physical_plan::{
|
||||
};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::raw::RawSeriesChunk;
|
||||
use datatypes::series::samples::{DenseSamplesRef, SampleRef, Samples, Series, SeriesSchema};
|
||||
use datatypes::series::samples::{
|
||||
DenseSamplesRef, FieldSpec, SampleRef, Samples, Series, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::EvalGrid;
|
||||
use futures::Stream;
|
||||
use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream};
|
||||
@@ -78,10 +82,12 @@ use crate::evaluated::EvaluatedChunk;
|
||||
use crate::grid_series::{LabelSet, label_set};
|
||||
use crate::native::execute::InputId;
|
||||
use crate::native::execute::{NativeExecutionState, NativeExecutor};
|
||||
use crate::native::plan::{NativeExpr, NativeNode, NativeTree};
|
||||
use crate::native::plan::{NativeExpr, NativeNode, NativeTree, reads_across_series};
|
||||
use crate::native::runs::{Run, absorb};
|
||||
use crate::source::materialize_raw_labels;
|
||||
|
||||
use super::evaluated_frame::{pack, schema as frame_schema};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -233,6 +239,13 @@ pub struct FusedSeries {
|
||||
input: LogicalPlan,
|
||||
/// The columns this node produces.
|
||||
output_schema: DFSchemaRef,
|
||||
/// Whether this node emits evaluated frames instead of the field, tag and time row table.
|
||||
///
|
||||
/// A frame node packs every evaluated chunk into one row of [`super::evaluated_frame`]'s
|
||||
/// layout, which carries the chunk's own labels, absolute grid positions and finality, and its
|
||||
/// `output_schema` is that layout. The modes are different outputs of one computation, so the
|
||||
/// flag is part of the identity.
|
||||
output_frames: bool,
|
||||
}
|
||||
|
||||
impl FusedSeries {
|
||||
@@ -256,6 +269,40 @@ impl FusedSeries {
|
||||
binding,
|
||||
input,
|
||||
output_schema,
|
||||
output_frames: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates the node in frame mode: every evaluated chunk leaves as one row of
|
||||
/// [`super::evaluated_frame`]'s layout, so a consumer above rebuilds the tree's own chunks.
|
||||
///
|
||||
/// The output schema is that layout, so the tree needs two facts the row table does not: its
|
||||
/// output has exactly one field on the statement's grid, and it reads one series at a time,
|
||||
/// because a frame names the series whose chunk it holds and nothing about its vector.
|
||||
pub(crate) fn try_new_evaluated(
|
||||
promql: Arc<str>,
|
||||
tree: NativeTree,
|
||||
binding: FusedSeriesBinding,
|
||||
input: LogicalPlan,
|
||||
) -> DataFusionResult<Self> {
|
||||
validate_binding(&tree, &binding)?;
|
||||
if reads_across_series(tree.root()) {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeries cannot emit a tree that reads across series as evaluated frames: a \
|
||||
frame carries one series' chunk"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
// The chunk a frame holds is packed against the tree's own output schema.
|
||||
let _ = evaluated_series_schema(&tree)?;
|
||||
let output_schema = frame_schema().to_dfschema_ref()?;
|
||||
Ok(Self {
|
||||
promql,
|
||||
tree,
|
||||
binding,
|
||||
input,
|
||||
output_schema,
|
||||
output_frames: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -282,6 +329,9 @@ impl FusedSeries {
|
||||
/// the frame passes both on. Building the node rejects a tree the runtime cannot execute, a
|
||||
/// frame schema the tree's input was not compiled against, and a schema the conversion cannot
|
||||
/// classify, so a plan that is built is a plan that runs.
|
||||
///
|
||||
/// A frame-mode node builds a frame-mode execution: the mode is not a property of the input or
|
||||
/// of the tree, so it travels with the node.
|
||||
pub fn to_execution_plan(
|
||||
&self,
|
||||
exec_input: Arc<dyn ExecutionPlan>,
|
||||
@@ -289,7 +339,7 @@ impl FusedSeries {
|
||||
ordering: SeriesOrdering,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
let output_schema: SchemaRef = self.output_schema.inner().clone();
|
||||
Ok(Arc::new(FusedSeriesExec::try_new(
|
||||
Ok(Arc::new(FusedSeriesExec::build(
|
||||
Arc::clone(&self.promql),
|
||||
exec_input,
|
||||
label_source,
|
||||
@@ -298,6 +348,7 @@ impl FusedSeries {
|
||||
output_schema,
|
||||
self.binding.time_index.clone(),
|
||||
self.binding.tags.clone(),
|
||||
self.output_frames,
|
||||
)?))
|
||||
}
|
||||
}
|
||||
@@ -322,6 +373,9 @@ impl UserDefinedLogicalNodeCore for FusedSeries {
|
||||
}
|
||||
|
||||
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
|
||||
if self.output_frames {
|
||||
return write!(f, "FusedSeries: evaluated frames for {}", self.promql);
|
||||
}
|
||||
write!(f, "FusedSeries: {}", self.promql)
|
||||
}
|
||||
|
||||
@@ -343,6 +397,7 @@ impl UserDefinedLogicalNodeCore for FusedSeries {
|
||||
binding: self.binding.clone(),
|
||||
input,
|
||||
output_schema: Arc::clone(&self.output_schema),
|
||||
output_frames: self.output_frames,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -358,6 +413,7 @@ impl PartialEq for FusedSeries {
|
||||
&& self.binding == other.binding
|
||||
&& self.input == other.input
|
||||
&& self.output_schema == other.output_schema
|
||||
&& self.output_frames == other.output_frames
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,6 +425,7 @@ impl Hash for FusedSeries {
|
||||
self.binding.hash(state);
|
||||
self.input.hash(state);
|
||||
self.output_schema.hash(state);
|
||||
self.output_frames.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +447,10 @@ impl PartialOrd for FusedSeries {
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
match self.output_frames.cmp(&other.output_frames) {
|
||||
Ordering::Equal => {}
|
||||
ord => return Some(ord),
|
||||
}
|
||||
if self.output_schema == other.output_schema {
|
||||
Some(Ordering::Equal)
|
||||
} else {
|
||||
@@ -615,9 +676,34 @@ fn validate_binding(
|
||||
}
|
||||
}
|
||||
|
||||
/// The series schema a tree's own output is evaluated on, which an evaluated frame is packed
|
||||
/// against: exactly one field, on the grid the tree evaluated on, whose `Arc` is kept as it is.
|
||||
fn evaluated_series_schema(tree: &NativeTree) -> DataFusionResult<Arc<SeriesSchema>> {
|
||||
let output = tree
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
.filter(|output| output.eval_grid.is_some())
|
||||
.ok_or_else(|| {
|
||||
DataFusionError::Plan(
|
||||
"FusedSeries cannot emit a tree whose output is not samples on a grid as \
|
||||
evaluated frames"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
if output.fields.len() != 1 {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"FusedSeries cannot emit a tree of {} output fields as evaluated frames, which carry \
|
||||
one field",
|
||||
output.fields.len()
|
||||
)));
|
||||
}
|
||||
Ok(Arc::clone(output))
|
||||
}
|
||||
|
||||
/// Where one output column of [`FusedSeriesExec`] comes from.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum OutputColumn {
|
||||
pub(crate) enum OutputColumn {
|
||||
/// The evaluation grid timestamps of the current chunk.
|
||||
Time,
|
||||
/// Series field by index in the bound series schema.
|
||||
@@ -627,9 +713,12 @@ enum OutputColumn {
|
||||
}
|
||||
|
||||
/// Classifies every output column, rejecting anything the conversion cannot produce.
|
||||
fn classify_output(
|
||||
///
|
||||
/// `fields` are the fields of the schema the chunks were evaluated against: those, and not the
|
||||
/// whole schema, are what a reader of such a schema has to hand.
|
||||
pub(crate) fn classify_output(
|
||||
output_schema: &SchemaRef,
|
||||
series_schema: &SeriesSchema,
|
||||
fields: &[FieldSpec],
|
||||
tags: &[String],
|
||||
time_column: &str,
|
||||
) -> DataFusionResult<Vec<OutputColumn>> {
|
||||
@@ -644,11 +733,7 @@ fn classify_output(
|
||||
"tag column {tag:?} of FusedSeriesExec cannot be the time column"
|
||||
)));
|
||||
}
|
||||
if series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| field.name.as_ref() == tag)
|
||||
{
|
||||
if fields.iter().any(|field| field.name.as_ref() == tag) {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"tag column {tag:?} of FusedSeriesExec clashes with a series field"
|
||||
)));
|
||||
@@ -656,7 +741,7 @@ fn classify_output(
|
||||
}
|
||||
|
||||
let mut time_seen = false;
|
||||
let mut field_seen = vec![false; series_schema.fields.len()];
|
||||
let mut field_seen = vec![false; 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() {
|
||||
@@ -684,11 +769,7 @@ fn classify_output(
|
||||
classification.push(OutputColumn::Time);
|
||||
continue;
|
||||
}
|
||||
if let Some(index) = series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.position(|field| field.name.as_ref() == name)
|
||||
{
|
||||
if let Some(index) = 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"
|
||||
@@ -746,7 +827,7 @@ fn classify_output(
|
||||
if !seen {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"missing field column {:?} in FusedSeriesExec output schema",
|
||||
series_schema.fields[index].name
|
||||
fields[index].name
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -776,8 +857,14 @@ pub struct FusedSeriesExec {
|
||||
ordering: SeriesOrdering,
|
||||
/// Which of the tree's inputs every raw chunk a partition reads enters at.
|
||||
input_id: InputId,
|
||||
/// Where each output column comes from.
|
||||
/// Where each output column comes from, or empty in frame mode, whose output is the layout.
|
||||
classification: Arc<[OutputColumn]>,
|
||||
/// The series schema each evaluated chunk is packed against, and `None` when this node emits
|
||||
/// the row table instead.
|
||||
///
|
||||
/// It is the tree's own output schema, read off the tree at construction, so a frame cannot be
|
||||
/// labelled with a schema the tree that produced it does not have.
|
||||
evaluated_output: Option<Arc<SeriesSchema>>,
|
||||
/// The output column holding the grid timestamps, kept so this node can be rebuilt over a new
|
||||
/// child without losing which column its time came from.
|
||||
time_column: String,
|
||||
@@ -823,14 +910,64 @@ impl FusedSeriesExec {
|
||||
output_schema: SchemaRef,
|
||||
time_column: String,
|
||||
tags: Vec<String>,
|
||||
) -> DataFusionResult<Self> {
|
||||
Self::build(
|
||||
promql,
|
||||
input,
|
||||
label_source,
|
||||
ordering,
|
||||
tree,
|
||||
output_schema,
|
||||
time_column,
|
||||
tags,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates the node in either mode: `output_frames` says whether every evaluated chunk leaves
|
||||
/// as one row of [`super::evaluated_frame`]'s layout rather than as rows of the declared table.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build(
|
||||
promql: Arc<str>,
|
||||
input: Arc<dyn ExecutionPlan>,
|
||||
label_source: RawLabelSource,
|
||||
ordering: SeriesOrdering,
|
||||
tree: Arc<NativeTree>,
|
||||
output_schema: SchemaRef,
|
||||
time_column: String,
|
||||
tags: Vec<String>,
|
||||
output_frames: bool,
|
||||
) -> DataFusionResult<Self> {
|
||||
let tree_input = tree_input(&tree)?;
|
||||
// Building a state is what proves the runtime executes this tree: a node kind it does not
|
||||
// run yet is refused here, so a plan that is built is a plan that starts. The throwaway
|
||||
// state is dropped at once, returning its (unbounded) reservations.
|
||||
let _ = NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()))?;
|
||||
let classification =
|
||||
classify_output(&output_schema, &tree_input.schema, &tags, &time_column)?;
|
||||
let evaluated_output = if output_frames {
|
||||
Some(evaluated_series_schema(&tree)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A frame's columns are its own layout, so a frame node classifies nothing and checks that
|
||||
// it was given that layout instead.
|
||||
let classification: Arc<[OutputColumn]> = if evaluated_output.is_some() {
|
||||
if output_schema.as_ref() != frame_schema().as_ref() {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeriesExec emits evaluated frames but its output schema is not the frame \
|
||||
layout"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
Arc::from(Vec::new())
|
||||
} else {
|
||||
classify_output(
|
||||
&output_schema,
|
||||
&tree_input.schema.fields,
|
||||
&tags,
|
||||
&time_column,
|
||||
)?
|
||||
.into()
|
||||
};
|
||||
// Read here rather than below, because whether the split below can happen decides whether
|
||||
// the tree shape is one this node may run at all.
|
||||
let input_properties = input.properties();
|
||||
@@ -892,7 +1029,8 @@ impl FusedSeriesExec {
|
||||
label_source,
|
||||
ordering,
|
||||
input_id: tree_input.input_id,
|
||||
classification: classification.into(),
|
||||
classification,
|
||||
evaluated_output,
|
||||
time_column,
|
||||
tags: tags.into(),
|
||||
input,
|
||||
@@ -973,8 +1111,8 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
))
|
||||
})?;
|
||||
// Rebuilt rather than patched: the new child's schema is what the frame is validated
|
||||
// against, so a child that changed shape is refused instead of decoded with a stale layout.
|
||||
Ok(Arc::new(Self::try_new(
|
||||
// against. The mode comes along, so a frame node stays one; label sets and roots are fresh.
|
||||
Ok(Arc::new(Self::build(
|
||||
Arc::clone(&self.promql),
|
||||
child,
|
||||
self.label_source.clone(),
|
||||
@@ -983,6 +1121,7 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
self.output_schema.clone(),
|
||||
self.time_column.clone(),
|
||||
self.tags.to_vec(),
|
||||
self.evaluated_output.is_some(),
|
||||
)?))
|
||||
}
|
||||
|
||||
@@ -999,6 +1138,12 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.attach(&context.runtime_env().memory_pool);
|
||||
// A producer is one execution of the tree: the partition this stream runs.
|
||||
let producer = u64::try_from(partition).map_err(|_| {
|
||||
DataFusionError::Execution(format!(
|
||||
"FusedSeriesExec partition {partition} does not fit an evaluated frame's producer"
|
||||
))
|
||||
})?;
|
||||
let input = self.input.execute(partition, Arc::clone(&context))?;
|
||||
// Batches become raw series chunks through the shared frame decoder, which is the inverse of
|
||||
// what the producer packed: one chunk per frame row, each series closed exactly once by the
|
||||
@@ -1022,6 +1167,9 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
executor: Some(NativeExecutor::new(state)),
|
||||
input_id: self.input_id,
|
||||
classification: Arc::clone(&self.classification),
|
||||
evaluated_output: self.evaluated_output.clone(),
|
||||
producer,
|
||||
next_ordinal: 0,
|
||||
tags: Arc::clone(&self.tags),
|
||||
output_schema: self.output_schema.clone(),
|
||||
labels: Arc::clone(&self.labels),
|
||||
@@ -1038,8 +1186,9 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
/// Converts one evaluated chunk into one output batch.
|
||||
///
|
||||
/// The time column is the absolute grid positions the chunk carries, missing samples are nulls and
|
||||
/// ordinary NaN stays a value.
|
||||
fn series_to_record_batch(
|
||||
/// ordinary NaN stays a value. `classification` is what [`classify_output`] answered for
|
||||
/// `output_schema`.
|
||||
pub(crate) fn series_to_record_batch(
|
||||
classification: &[OutputColumn],
|
||||
tags: &[String],
|
||||
output_schema: &SchemaRef,
|
||||
@@ -1172,7 +1321,7 @@ fn render_labels(labels: &LabelSet) -> String {
|
||||
/// later partitions are checked against stayed: everything the map held after the first partition
|
||||
/// was unaccounted for.
|
||||
#[derive(Default)]
|
||||
struct LabelSets {
|
||||
pub(crate) struct LabelSets {
|
||||
/// The grid positions each final label set already occupies, one run list per field of the
|
||||
/// series schema. Each list is sorted, disjoint and has the runs that touch joined, which is
|
||||
/// what lets a claim look a position up instead of walking the history.
|
||||
@@ -1187,7 +1336,7 @@ impl LabelSets {
|
||||
///
|
||||
/// Later executions keep the first reservation: it already pays for what `seen` holds, and
|
||||
/// moving it to another pool would drop the bytes other partitions are still growing.
|
||||
fn attach(&mut self, pool: &Arc<dyn MemoryPool>) {
|
||||
pub(crate) fn attach(&mut self, pool: &Arc<dyn MemoryPool>) {
|
||||
if self.reservation.is_none() {
|
||||
self.reservation =
|
||||
Some(MemoryConsumer::new("FusedSeriesExec label sets").register(pool));
|
||||
@@ -1201,7 +1350,7 @@ impl LabelSets {
|
||||
/// legal, and so are series that fill the same points field by field: Prometheus merges both
|
||||
/// 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(&mut self, series: &Series) -> DataFusionResult<()> {
|
||||
pub(crate) fn claim(&mut self, series: &Series) -> DataFusionResult<()> {
|
||||
let runs = occupied_runs(series)?;
|
||||
// A chunk holding no value occupies nothing, so there is no collision to remember and no
|
||||
// entry to write. Such a chunk is not rare: a selection over a series that staleness or the
|
||||
@@ -1383,6 +1532,10 @@ fn colliding_field(stored: &[Vec<Run>], runs: &[Vec<Run>]) -> Option<usize> {
|
||||
}
|
||||
|
||||
/// The batches one execution of [`FusedSeriesExec`] yields.
|
||||
///
|
||||
/// An ordinary stream yields the row table; a frame-mode stream yields one row of
|
||||
/// [`super::evaluated_frame`]'s layout per chunk, numbered by this partition as its producer and by
|
||||
/// its position in this whole stream as its ordinal.
|
||||
pub struct FusedSeriesStream {
|
||||
/// The input frames, read as raw series chunks, or `None` once the stream ended in an error.
|
||||
///
|
||||
@@ -1394,8 +1547,19 @@ pub struct FusedSeriesStream {
|
||||
executor: Option<NativeExecutor>,
|
||||
/// The position of the tree's input node, which is where every chunk read enters.
|
||||
input_id: InputId,
|
||||
/// Where each output column comes from.
|
||||
/// Where each output column comes from, or empty in frame mode.
|
||||
classification: Arc<[OutputColumn]>,
|
||||
/// The series schema each chunk is packed against, `None` for the row table and once this
|
||||
/// stream has ended.
|
||||
///
|
||||
/// It is the tree's own output schema, so holding it past the last chunk would keep the grid it
|
||||
/// names - and the timestamps that grid materializes - alive in an ended stream a consumer
|
||||
/// keeps, for rows that can no longer be produced.
|
||||
evaluated_output: Option<Arc<SeriesSchema>>,
|
||||
/// The producer every frame of this stream names: the partition this execution runs.
|
||||
producer: u64,
|
||||
/// The ordinal the next frame carries, counted across the whole stream rather than per series.
|
||||
next_ordinal: u64,
|
||||
/// The tag column names, indexed by `OutputColumn::Tag`.
|
||||
tags: Arc<[String]>,
|
||||
/// The schema of every batch this stream yields.
|
||||
@@ -1455,8 +1619,12 @@ impl FusedSeriesStream {
|
||||
};
|
||||
match executor.next_chunk() {
|
||||
Ok(Some(chunk)) => Ok(Some(chunk)),
|
||||
// Nothing more will be settled - not an input EOF, which still flushes through
|
||||
// `Ok(Some)` above - so the schema the rows were packed against is released with the
|
||||
// execution, rather than staying alive in an ended stream a consumer keeps.
|
||||
Ok(None) => {
|
||||
self.executor = None;
|
||||
self.evaluated_output = None;
|
||||
Ok(None)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
@@ -1472,6 +1640,9 @@ impl FusedSeriesStream {
|
||||
self.done = true;
|
||||
self.executor = None;
|
||||
self.input = None;
|
||||
// Nothing can be packed any more, so the schema the rows were packed against - and the grid
|
||||
// its positions were read on - goes with the run that produced them.
|
||||
self.evaluated_output = None;
|
||||
// The label-set map and its charge are the plan's, so a stream stopping early gives back
|
||||
// nothing: the entries another partition is still checking against have to stay charged, and
|
||||
// are released when the plan itself is dropped.
|
||||
@@ -1483,17 +1654,34 @@ impl FusedSeriesStream {
|
||||
fn convert(&mut self, chunks: Vec<EvaluatedChunk>) -> DataFusionResult<()> {
|
||||
for chunk in &chunks {
|
||||
// The label set is claimed before its batch is queued, so a collision surfaces at the
|
||||
// chunk that reached it and nothing this plan would refuse is handed out after it.
|
||||
// chunk that reached it and nothing this plan would refuse is handed out after it. A
|
||||
// frame leaves with the same claim as a row: the tree decides which series closes.
|
||||
self.labels
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.claim(&chunk.series)?;
|
||||
let batch = series_to_record_batch(
|
||||
&self.classification,
|
||||
&self.tags,
|
||||
&self.output_schema,
|
||||
chunk,
|
||||
)?;
|
||||
let batch = match self.evaluated_output.as_ref() {
|
||||
// Packing validates the chunk against the tree's schema and carries its labels,
|
||||
// positions, nulls and finality. The ordinal is advanced only once the row exists,
|
||||
// so a packing error cannot leave a gap another frame would not fill.
|
||||
Some(schema) => {
|
||||
let (ordinal, producer) = (self.next_ordinal, self.producer);
|
||||
let batch = pack(chunk, schema, producer, ordinal)?;
|
||||
self.next_ordinal = ordinal.checked_add(1).ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"FusedSeriesExec evaluated frame {ordinal} of producer {producer} \
|
||||
cannot be incremented"
|
||||
))
|
||||
})?;
|
||||
batch
|
||||
}
|
||||
None => series_to_record_batch(
|
||||
&self.classification,
|
||||
&self.tags,
|
||||
&self.output_schema,
|
||||
chunk,
|
||||
)?,
|
||||
};
|
||||
self.ready.push_back(batch);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -29,12 +29,10 @@
|
||||
//! second per second, so the value it has to produce is exactly 1 (or 2) at every grid point and
|
||||
//! any position or finalization mistake shows up as a wrong, missing or duplicated row.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::task::Context;
|
||||
|
||||
use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray};
|
||||
use datafusion::arrow::buffer::{Buffer, ScalarBuffer};
|
||||
@@ -42,32 +40,25 @@ use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::common::ToDFSchema;
|
||||
use datafusion::common::config::ConfigOptions;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::datasource::memory::MemorySourceConfig;
|
||||
use datafusion::datasource::source::DataSourceExec;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::context::TaskContext;
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
|
||||
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
|
||||
use datafusion::logical_expr::{EmptyRelation, LogicalPlan, UserDefinedLogicalNodeCore};
|
||||
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
|
||||
use datafusion::physical_optimizer::PhysicalOptimizerRule;
|
||||
use datafusion::physical_optimizer::ensure_requirements::EnsureRequirements;
|
||||
use datafusion::physical_plan::execution_plan::{
|
||||
Boundedness, ChildrenPropertiesMode, EmissionType, ReplaceChildrenOptions,
|
||||
};
|
||||
use datafusion::physical_plan::execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions};
|
||||
use datafusion::physical_plan::metrics::{MetricValue, MetricsSet};
|
||||
use datafusion::physical_plan::{
|
||||
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, Partitioning, PlanProperties,
|
||||
RecordBatchStream, SendableRecordBatchStream, collect, displayable,
|
||||
};
|
||||
use datafusion::physical_plan::{Distribution, ExecutionPlan, collect, displayable};
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datatypes::series::frame::{RawLabelMode, pack_raw_series_chunk, raw_series_frame_schema};
|
||||
use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
|
||||
use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema};
|
||||
use datatypes::series::samples::{
|
||||
FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName, SeriesOrdering};
|
||||
use futures::{Stream, StreamExt, TryStreamExt};
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use store_api::region_engine::RawLabelSource;
|
||||
|
||||
use super::{
|
||||
@@ -75,6 +66,10 @@ use super::{
|
||||
occupied_runs, series_to_record_batch,
|
||||
};
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
use crate::extension_plan::evaluated_frame::{
|
||||
read as read_frame, schema as evaluated_frame_schema,
|
||||
};
|
||||
use crate::extension_plan::test_util::{StagedStream, staged, task_context};
|
||||
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
|
||||
use crate::native::plan::{
|
||||
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundWindow, Grouping,
|
||||
@@ -448,186 +443,6 @@ fn memory_exec_partitioned_with(
|
||||
fn memory_exec_partitioned(partitions: Vec<Vec<RecordBatch>>) -> Arc<dyn ExecutionPlan> {
|
||||
memory_exec_partitioned_with(frame_schema(), partitions)
|
||||
}
|
||||
|
||||
/// A task context whose memory pool is `pool`, so what the node charges can be read afterwards.
|
||||
fn task_context(pool: &Arc<GreedyMemoryPool>) -> Arc<TaskContext> {
|
||||
let runtime = RuntimeEnvBuilder::new()
|
||||
.with_memory_pool(Arc::clone(pool) as Arc<dyn MemoryPool>)
|
||||
.build()
|
||||
.expect("the runtime environment builds");
|
||||
Arc::new(TaskContext::default().with_runtime(Arc::new(runtime)))
|
||||
}
|
||||
|
||||
/// A physical input whose one partition's stream `make` builds.
|
||||
fn staged(
|
||||
schema: SchemaRef,
|
||||
make: impl Fn() -> SendableRecordBatchStream + Send + Sync + 'static,
|
||||
) -> Arc<dyn ExecutionPlan> {
|
||||
Arc::new(StagedPlan {
|
||||
properties: Arc::new(PlanProperties::new(
|
||||
EquivalenceProperties::new(schema),
|
||||
Partitioning::UnknownPartitioning(1),
|
||||
EmissionType::Incremental,
|
||||
Boundedness::Bounded,
|
||||
)),
|
||||
make: Box::new(make),
|
||||
})
|
||||
}
|
||||
|
||||
/// A physical input, so a test can stage what a memory source cannot: a pending poll, an error
|
||||
/// after some rows, and a stream whose drop it can see.
|
||||
struct StagedPlan {
|
||||
make: Box<dyn Fn() -> SendableRecordBatchStream + Send + Sync>,
|
||||
properties: Arc<PlanProperties>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for StagedPlan {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("StagedPlan").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayAs for StagedPlan {
|
||||
fn fmt_as(&self, _t: DisplayFormatType, _f: &mut Formatter) -> fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionPlan for StagedPlan {
|
||||
fn name(&self) -> &str {
|
||||
"StagedPlan"
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
&self.properties
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn apply_expressions(
|
||||
&self,
|
||||
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
|
||||
) -> DataFusionResult<TreeNodeRecursion> {
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
}
|
||||
|
||||
fn with_new_children(
|
||||
self: Arc<Self>,
|
||||
_children: Vec<Arc<dyn ExecutionPlan>>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&self,
|
||||
partition: usize,
|
||||
_context: Arc<TaskContext>,
|
||||
) -> DataFusionResult<SendableRecordBatchStream> {
|
||||
// A scan answers the partitions it declares and no others, which is what makes an index
|
||||
// past this plan's count an error the node above has to pass on.
|
||||
if partition >= self.properties.partitioning.partition_count() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"StagedPlan has no partition {partition}"
|
||||
)));
|
||||
}
|
||||
Ok((self.make)())
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream a [`StagedPlan`] hands over: `batches`, then an optional error, with a pending poll
|
||||
/// and a drop a test can observe.
|
||||
struct StagedStream {
|
||||
schema: SchemaRef,
|
||||
batches: VecDeque<RecordBatch>,
|
||||
handed: usize,
|
||||
/// Hand this many batches, then answer [`Poll::Pending`] once.
|
||||
pending_after: Option<usize>,
|
||||
/// The error to report once the batches are exhausted.
|
||||
error: Option<&'static str>,
|
||||
/// Set when this stream is dropped, so a test can see the input being released.
|
||||
dropped: Option<Arc<AtomicBool>>,
|
||||
/// Counts the batches this stream has handed over, so a test can see how far one poll read.
|
||||
handed_out: Option<Arc<AtomicUsize>>,
|
||||
}
|
||||
|
||||
impl StagedStream {
|
||||
fn new(schema: SchemaRef, batches: Vec<RecordBatch>) -> Self {
|
||||
Self {
|
||||
schema,
|
||||
batches: batches.into(),
|
||||
handed: 0,
|
||||
pending_after: None,
|
||||
error: None,
|
||||
dropped: None,
|
||||
handed_out: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_after(mut self, batches: usize) -> Self {
|
||||
self.pending_after = Some(batches);
|
||||
self
|
||||
}
|
||||
|
||||
fn error(mut self, message: &'static str) -> Self {
|
||||
self.error = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
fn dropped(mut self, flag: &Arc<AtomicBool>) -> Self {
|
||||
self.dropped = Some(Arc::clone(flag));
|
||||
self
|
||||
}
|
||||
|
||||
fn counted(mut self, counter: &Arc<AtomicUsize>) -> Self {
|
||||
self.handed_out = Some(Arc::clone(counter));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for StagedStream {
|
||||
type Item = DataFusionResult<RecordBatch>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = &mut *self;
|
||||
if this.pending_after == Some(this.handed) {
|
||||
this.pending_after = None;
|
||||
cx.waker().wake_by_ref();
|
||||
return Poll::Pending;
|
||||
}
|
||||
match this.batches.pop_front() {
|
||||
Some(batch) => {
|
||||
this.handed += 1;
|
||||
if let Some(counter) = &this.handed_out {
|
||||
counter.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
Poll::Ready(Some(Ok(batch)))
|
||||
}
|
||||
None => match this.error.take() {
|
||||
Some(message) => {
|
||||
Poll::Ready(Some(Err(DataFusionError::Execution(message.to_string()))))
|
||||
}
|
||||
None => Poll::Ready(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordBatchStream for StagedStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StagedStream {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dropped) = &self.dropped {
|
||||
dropped.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fused(tree: NativeTree) -> FusedSeries {
|
||||
let binding = binding(&tree);
|
||||
FusedSeries::try_new(
|
||||
@@ -1320,7 +1135,7 @@ async fn cancelling_after_partial_input_clears_current_bytes_and_keeps_peak() {
|
||||
.expect("the runtime executes a rate tree");
|
||||
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
|
||||
let mut stream = exec
|
||||
.execute(0, task_context(&pool))
|
||||
.execute(0, task_context(Arc::clone(&pool) as Arc<dyn MemoryPool>))
|
||||
.expect("the node executes");
|
||||
|
||||
// One unclosed series chunk is accepted; the source then parks before another arrives, so the
|
||||
@@ -2156,7 +1971,7 @@ async fn a_label_set_stays_charged_after_its_first_stream_ends() {
|
||||
"this test needs one series in each of two partitions"
|
||||
);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
|
||||
let context = task_context(&pool);
|
||||
let context = task_context(Arc::clone(&pool) as Arc<dyn MemoryPool>);
|
||||
|
||||
// The first partition claims the label set, answers it and ends.
|
||||
let mut stream = exec
|
||||
@@ -3174,3 +2989,568 @@ fn a_chunk_reaching_back_still_merges() {
|
||||
"a chunk starting before the last stored run was appended rather than merged"
|
||||
);
|
||||
}
|
||||
|
||||
/// The series schema the `rate(x[5m])` tree's own output is evaluated on, which a frame is packed
|
||||
/// and read against.
|
||||
fn rate_output() -> Arc<SeriesSchema> {
|
||||
rate_tree()
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
.expect("a rate tree produces samples")
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The frame-mode node of `tree`: its output is the frame layout, so it is built from the binding
|
||||
/// and the input alone.
|
||||
fn evaluated_node(tree: NativeTree) -> FusedSeries {
|
||||
let binding = binding(&tree);
|
||||
FusedSeries::try_new_evaluated(Arc::from(PROMQL), tree, binding, input_plan(frame_schema()))
|
||||
.expect("the binding matches the tree")
|
||||
}
|
||||
|
||||
/// Every frame `batches` hold, read back with the tree's own evaluated output schema.
|
||||
///
|
||||
/// A batch may hold several rows and a row is one chunk, so every row is read: that is what makes a
|
||||
/// producer's frames comparable to the rows the ordinary node yields.
|
||||
fn read_frames(batches: &[RecordBatch]) -> Vec<(u64, u64, EvaluatedChunk)> {
|
||||
let schema = rate_output();
|
||||
let mut frames = Vec::new();
|
||||
for batch in batches {
|
||||
for row in 0..batch.num_rows() {
|
||||
frames.push(read_frame(batch, row, &schema).expect("the node packs the frame layout"));
|
||||
}
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
/// The rows the chunks of `frames` hold, in the shape the ordinary path yields: timestamp, value,
|
||||
/// host and metric name.
|
||||
fn frame_rows(frames: &[(u64, u64, EvaluatedChunk)]) -> Vec<Row> {
|
||||
let grid = grid_timestamps();
|
||||
let mut rows = Vec::new();
|
||||
for (_, _, chunk) in frames {
|
||||
// The tree has one output field, and a series' field list is never empty.
|
||||
let samples = &chunk.series.fields.as_slice()[0];
|
||||
let host = chunk.series.metric.get(HOST).map(str::to_string);
|
||||
let name = chunk.series.metric.get(NAME).map(str::to_string);
|
||||
let mut samples = samples.iter();
|
||||
for (position, _) in chunk.series.time.positions() {
|
||||
let value = match samples.next().expect("one sample per carried row") {
|
||||
SampleRef::Float(value) => Some(value),
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Histogram(_) => panic!("rate produces float samples"),
|
||||
};
|
||||
rows.push((grid[position], value, host.clone(), name.clone()));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The producer and ordinal of every frame, which is what a consumer orders frames by.
|
||||
fn frame_numbers(frames: &[(u64, u64, EvaluatedChunk)]) -> Vec<(u64, u64)> {
|
||||
frames
|
||||
.iter()
|
||||
.map(|(producer, ordinal, _)| (*producer, *ordinal))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Three partitions each frame the series it read, numbered as one producer per partition.
|
||||
///
|
||||
/// A frame names the producer whose output it belongs to and its position in that producer's
|
||||
/// output, and a producer is one execution of the tree: the partition. Three partitions therefore
|
||||
/// report three producers, each starting at ordinal 0, and each frame carries the labels and grid
|
||||
/// positions of the series that partition read.
|
||||
#[tokio::test]
|
||||
async fn three_partitions_frame_their_own_series() {
|
||||
let partitions = [1.0, 2.0, 3.0]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, scale)| {
|
||||
vec![frame(&series_chunk(
|
||||
&format!("web-{index}"),
|
||||
&series_samples(scale),
|
||||
true,
|
||||
))]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let exec = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec_partitioned(partitions),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
assert_eq!(evaluated_frame_schema(), exec.schema());
|
||||
|
||||
let batches = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("each partition runs its own tree");
|
||||
// Partitions settle in whatever order they finish, and a frame says which producer it belongs
|
||||
// to, so the frames are ordered by what they say rather than by how they arrived.
|
||||
let mut frames = read_frames(&batches);
|
||||
frames.sort_by_key(|(producer, ordinal, _)| (*producer, *ordinal));
|
||||
assert_eq!(
|
||||
3,
|
||||
frames.len(),
|
||||
"one evaluated chunk per partition: {frames:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
vec![(0, 0), (1, 0), (2, 0)],
|
||||
frame_numbers(&frames),
|
||||
"one producer per partition, each starting at ordinal 0"
|
||||
);
|
||||
assert!(
|
||||
frames.iter().all(|(_, _, chunk)| chunk.is_last),
|
||||
"each frame holds the chunk that closes its one series"
|
||||
);
|
||||
for (index, (_, _, chunk)) in frames.iter().enumerate() {
|
||||
let host = format!("web-{index}");
|
||||
assert_eq!(Some(host.as_str()), chunk.series.metric.get(HOST));
|
||||
assert_eq!(
|
||||
None,
|
||||
chunk.series.metric.get(NAME),
|
||||
"rate drops the metric name, and the frame carries the labels the tree produced"
|
||||
);
|
||||
assert_eq!(GRID_LEN as usize, chunk.series.time.len());
|
||||
}
|
||||
|
||||
let rows = frame_rows(&frames);
|
||||
for (index, scale) in [1.0, 2.0, 3.0].into_iter().enumerate() {
|
||||
let host = format!("web-{index}");
|
||||
let series = rows
|
||||
.iter()
|
||||
.filter(|row| row.2.as_deref() == Some(host.as_str()))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
assert_series_rates(&series, &[(scale, host.as_str())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// One series split over three input chunks followed by a whole second series is framed chunk by
|
||||
/// chunk, and its frames hold exactly the rows the version that arrived whole does.
|
||||
///
|
||||
/// The ordinal counts the stream rather than the series: a closing frame ends a series, not a
|
||||
/// producer, so the second series continues the numbering the first closed on.
|
||||
#[tokio::test]
|
||||
async fn a_series_split_over_chunks_keeps_its_rows_when_framed() {
|
||||
// The same two series twice: whole, then with the first one split over three chunks. Both
|
||||
// series share the one partition, so the second arrives after the first one closed.
|
||||
let whole = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec(frames(&[
|
||||
series_chunk("web-1", &series_samples(1.0), true),
|
||||
series_chunk("web-2", &series_samples(2.0), true),
|
||||
])),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let whole = read_frames(
|
||||
&collect(whole, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the node runs"),
|
||||
);
|
||||
let split = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec(
|
||||
one_series_frames()
|
||||
.into_iter()
|
||||
.chain(frames(&[series_chunk("web-2", &series_samples(2.0), true)]))
|
||||
.collect(),
|
||||
),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let split = read_frames(
|
||||
&collect(split, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the node runs"),
|
||||
);
|
||||
|
||||
// Same rows from both sources: a frame carries the chunk's own absolute positions, so a chunk
|
||||
// boundary is not a row boundary.
|
||||
assert_eq!(frame_rows(&whole), frame_rows(&split));
|
||||
let rows = frame_rows(&split);
|
||||
let two = 2 * GRID_LEN as usize;
|
||||
assert_eq!(
|
||||
grid_timestamps()
|
||||
.into_iter()
|
||||
.chain(grid_timestamps())
|
||||
.collect::<Vec<_>>(),
|
||||
rows.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"the frames cover the whole grid for both series, in order"
|
||||
);
|
||||
assert_eq!(
|
||||
[
|
||||
vec![Some(1.0); GRID_LEN as usize],
|
||||
vec![Some(2.0); GRID_LEN as usize]
|
||||
]
|
||||
.concat(),
|
||||
rows.iter().map(|row| row.1).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(
|
||||
rows.iter().enumerate().all(|(index, row)| {
|
||||
let host = if index < GRID_LEN as usize {
|
||||
"web-1"
|
||||
} else {
|
||||
"web-2"
|
||||
};
|
||||
row.2.as_deref() == Some(host) && row.3.is_none()
|
||||
}),
|
||||
"every row carries the labels of the series it belongs to: {rows:?}"
|
||||
);
|
||||
assert_eq!(two, rows.len());
|
||||
|
||||
// One producer, ordinals from 0 without gaps across both series: the first series' close ends
|
||||
// the series, not the producer, so the second series continues the numbering.
|
||||
let numbers = frame_numbers(&split);
|
||||
assert!(
|
||||
numbers.len() > 1,
|
||||
"the chunks settled separately: {numbers:?}"
|
||||
);
|
||||
let expected = (0..numbers.len() as u64)
|
||||
.map(|ordinal| (0, ordinal))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(expected, numbers);
|
||||
let closes = split
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, _, chunk))| chunk.is_last)
|
||||
.map(|(index, _)| index)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
2,
|
||||
closes.len(),
|
||||
"each series closes exactly once, on one frame: {closes:?}"
|
||||
);
|
||||
let next = split
|
||||
.get(closes[0] + 1)
|
||||
.expect("the second series is framed after the first one closed");
|
||||
assert_eq!(
|
||||
(0, closes[0] as u64 + 1),
|
||||
(next.0, next.1),
|
||||
"the ordinal continues across the first series' close"
|
||||
);
|
||||
assert_eq!(
|
||||
Some("web-2"),
|
||||
next.2.series.metric.get(HOST),
|
||||
"the frame after the close belongs to the second series"
|
||||
);
|
||||
assert!(
|
||||
split.last().expect("the series settle").2.is_last,
|
||||
"the second series' closing frame is the stream's last"
|
||||
);
|
||||
}
|
||||
|
||||
/// A closing chunk that holds no row is still a frame: the series' labels and its finality travel
|
||||
/// in a row with no position and no value.
|
||||
#[tokio::test]
|
||||
async fn an_empty_closing_chunk_is_still_a_frame() {
|
||||
// One sample at 0s, while every grid point's window is left-open: no window holds a sample, so
|
||||
// `rate` decides no position and the series closes on an empty chunk.
|
||||
let exec = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec(frames(&[series_chunk(
|
||||
"web-1",
|
||||
&series_samples(1.0)[..1],
|
||||
true,
|
||||
)])),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let batches = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the node runs");
|
||||
assert_eq!(
|
||||
1,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"the empty chunk is one frame row"
|
||||
);
|
||||
let frames = read_frames(&batches);
|
||||
assert_eq!(vec![(0, 0)], frame_numbers(&frames));
|
||||
let (_, _, chunk) = frames.first().expect("the series closes on a frame");
|
||||
assert!(chunk.is_last, "the row is the chunk that closes the series");
|
||||
assert_eq!(0, chunk.series.time.len(), "no position was decided");
|
||||
assert_eq!(
|
||||
Some("web-1"),
|
||||
chunk.series.metric.get(HOST),
|
||||
"the closing row still names the series it closes"
|
||||
);
|
||||
}
|
||||
|
||||
/// The frame path claims each label set before it packs anything, exactly as the row path does: two
|
||||
/// partitions whose series land on one label set are still refused, and the refusal is the claim's
|
||||
/// rather than something a consumer above would have to notice.
|
||||
#[tokio::test]
|
||||
async fn a_duplicate_label_set_is_refused_before_a_frame_is_packed() {
|
||||
let series = frame(&series_chunk("web-1", &series_samples(1.0), true));
|
||||
let exec = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec_partitioned(vec![vec![series.clone()], vec![series]]),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let error = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect_err("the second partition lands on the label set the first one claimed");
|
||||
let message = error_chain(&error);
|
||||
assert!(
|
||||
message.contains("vector cannot contain metrics with the same labelset"),
|
||||
"refused for another reason: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The output mode is part of the node's identity, and `EXPLAIN` says which one it is.
|
||||
#[test]
|
||||
fn the_output_mode_is_part_of_the_nodes_identity() {
|
||||
let tree = rate_tree();
|
||||
let frames = evaluated_node(tree.clone());
|
||||
// The same output schema, but built as the ordinary node: only the mode can tell them apart.
|
||||
let ordinary = FusedSeries::try_new(
|
||||
Arc::from(PROMQL),
|
||||
tree.clone(),
|
||||
binding(&tree),
|
||||
input_plan(frame_schema()),
|
||||
evaluated_frame_schema().to_dfschema_ref().unwrap(),
|
||||
)
|
||||
.expect("the binding matches the tree");
|
||||
assert_eq!(ordinary.schema(), frames.schema());
|
||||
assert_ne!(ordinary, frames);
|
||||
assert_ne!(
|
||||
Some(std::cmp::Ordering::Equal),
|
||||
ordinary.partial_cmp(&frames)
|
||||
);
|
||||
assert_eq!(
|
||||
"FusedSeries: rate(x[5m])",
|
||||
Explain(&ordinary).to_string(),
|
||||
"the ordinary line stays what it was"
|
||||
);
|
||||
assert_eq!(
|
||||
"FusedSeries: evaluated frames for rate(x[5m])",
|
||||
Explain(&frames).to_string()
|
||||
);
|
||||
}
|
||||
|
||||
/// A rebuilt frame node is a frame node again, with fresh label sets: the same series is packed a
|
||||
/// second time, numbered from ordinal 0.
|
||||
#[tokio::test]
|
||||
async fn a_rebuilt_frame_node_stays_a_frame_node() {
|
||||
let exec = plan_of(
|
||||
evaluated_node(rate_tree()),
|
||||
memory_exec(one_series_frames()),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let first = read_frames(
|
||||
&collect(Arc::clone(&exec), SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the node runs"),
|
||||
);
|
||||
assert_eq!(evaluated_frame_schema(), exec.schema());
|
||||
|
||||
let rebuilt = Arc::clone(&exec)
|
||||
.replace_children(
|
||||
vec![memory_exec(one_series_frames())],
|
||||
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
|
||||
)
|
||||
.expect("the node rebuilds over another input");
|
||||
assert_eq!(
|
||||
evaluated_frame_schema(),
|
||||
rebuilt.schema(),
|
||||
"the rebuilt node kept the frame layout"
|
||||
);
|
||||
let before = rebuilt
|
||||
.metrics()
|
||||
.expect("a plan that has not run reports a set");
|
||||
assert_eq!(0, before.iter().count(), "the rebuild inherited a run");
|
||||
|
||||
let again = read_frames(
|
||||
&collect(Arc::clone(&rebuilt), SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the rebuilt node runs"),
|
||||
);
|
||||
assert_eq!(frame_rows(&first), frame_rows(&again));
|
||||
assert_eq!(
|
||||
frame_numbers(&first),
|
||||
frame_numbers(&again),
|
||||
"the rebuilt plan's label sets were empty, so the same series is framed again"
|
||||
);
|
||||
assert_eq!(
|
||||
1,
|
||||
count(
|
||||
&rebuilt.metrics().expect("the node reports its execution"),
|
||||
"native.root.completed_series"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// A tree a frame cannot hold is refused when the node is built: a frame carries one series' chunk
|
||||
/// of one field, so neither a tree that answers across series nor one of two output fields fits.
|
||||
#[test]
|
||||
fn a_tree_a_frame_cannot_hold_is_refused() {
|
||||
let across = aggregate_tree();
|
||||
let error = FusedSeries::try_new_evaluated(
|
||||
Arc::from(PROMQL),
|
||||
across.clone(),
|
||||
binding_of(&across, raw_schema(), vec![HOST.to_string()]),
|
||||
input_plan(frame_schema()),
|
||||
)
|
||||
.expect_err("an aggregate reads the whole vector at a grid point");
|
||||
assert!(
|
||||
error.to_string().contains("reads across series"),
|
||||
"refused for another reason: {error}"
|
||||
);
|
||||
|
||||
let two_fields = rate_tree_of(two_field_schema());
|
||||
let error = FusedSeries::try_new_evaluated(
|
||||
Arc::from(PROMQL),
|
||||
two_fields.clone(),
|
||||
binding_of(&two_fields, two_field_schema(), vec![HOST.to_string()]),
|
||||
input_plan(frame_schema()),
|
||||
)
|
||||
.expect_err("a frame carries one value per position");
|
||||
assert!(
|
||||
error.to_string().contains("output fields"),
|
||||
"refused for another reason: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The evaluated schema and the grid a frame-mode stream packs against, watched weakly.
|
||||
///
|
||||
/// Only the `Weak`s leave this helper. A strong handle held here would keep alive exactly what the
|
||||
/// tests below measure, and the test's own handles are dropped before it looks.
|
||||
fn evaluated_weak(tree: &NativeTree) -> (Weak<SeriesSchema>, Weak<EvalGrid>) {
|
||||
let output = tree
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
.expect("a rate tree's output is samples");
|
||||
let grid = output
|
||||
.eval_grid
|
||||
.clone()
|
||||
.expect("a rate tree's output is evaluated on a grid");
|
||||
(Arc::downgrade(output), Arc::downgrade(&grid))
|
||||
}
|
||||
|
||||
/// A frame-mode stream releases what its rows were packed against once it ends.
|
||||
///
|
||||
/// The chunks are packed against the tree's own output schema, so a stream that kept that handle
|
||||
/// past its last chunk would keep the schema, the grid it names and the grid's materialized
|
||||
/// timestamps alive in a consumer that keeps an ended stream. The plan is dropped before the stream
|
||||
/// runs here, so after it ends the only handle left would be the stream's own.
|
||||
#[tokio::test]
|
||||
async fn an_ended_frame_stream_releases_the_evaluated_schema() {
|
||||
let tree = rate_tree();
|
||||
let output = tree
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
.expect("a rate tree's output is samples")
|
||||
.clone();
|
||||
let (schema, grid) = evaluated_weak(&tree);
|
||||
let exec = plan_of(evaluated_node(tree), memory_exec(one_series_frames()))
|
||||
.expect("the runtime executes a rate tree");
|
||||
let mut stream = exec
|
||||
.execute(0, SessionContext::default().task_ctx())
|
||||
.expect("the node executes");
|
||||
// The plan holds the tree it runs and the schema it packs against, and the input it hands over
|
||||
// holds raw frames: neither may be what keeps the evaluated schema alive after this point.
|
||||
drop(exec);
|
||||
|
||||
// Read every frame with the test's own handle while it still exists: the rows, the closing one
|
||||
// included, are handed out before anything is released.
|
||||
let mut frames = Vec::new();
|
||||
while let Some(batch) = stream.next().await {
|
||||
let batch = batch.expect("the node runs");
|
||||
for row in 0..batch.num_rows() {
|
||||
frames.push(read_frame(&batch, row, &output).expect("every row is a frame"));
|
||||
}
|
||||
}
|
||||
let rows = frame_rows(&frames);
|
||||
assert_eq!(
|
||||
grid_timestamps(),
|
||||
rows.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"the whole series is answered before the release"
|
||||
);
|
||||
assert!(
|
||||
frames.last().expect("the series settles").2.is_last,
|
||||
"the closing frame is the last one packed"
|
||||
);
|
||||
// A decoded chunk names the grid it was read on, so the rows go before the schema is measured.
|
||||
drop(rows);
|
||||
drop(frames);
|
||||
drop(output);
|
||||
|
||||
assert!(
|
||||
schema.upgrade().is_none(),
|
||||
"the ended stream still holds the evaluated schema"
|
||||
);
|
||||
assert!(
|
||||
grid.upgrade().is_none(),
|
||||
"the ended stream still holds the grid the schema names"
|
||||
);
|
||||
// An ended stream answers nothing, and asks nothing of what it released.
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
/// The same release happens when the stream ends in an error rather than at its input's end: a
|
||||
/// stopped run cannot pack another row, so it holds on to nothing it would pack one against.
|
||||
#[tokio::test]
|
||||
async fn a_failed_frame_stream_releases_the_evaluated_schema() {
|
||||
let tree = rate_tree();
|
||||
let output = tree
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
.expect("a rate tree's output is samples")
|
||||
.clone();
|
||||
let (schema, grid) = evaluated_weak(&tree);
|
||||
let frames = frame_schema();
|
||||
let exec = plan_of(
|
||||
evaluated_node(tree),
|
||||
staged(frames.clone(), move || {
|
||||
Box::pin(
|
||||
StagedStream::new(frames.clone(), one_series_frames()).error("a source defect"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.expect("the runtime executes a rate tree");
|
||||
let mut stream = exec
|
||||
.execute(0, SessionContext::default().task_ctx())
|
||||
.expect("the node executes");
|
||||
drop(exec);
|
||||
|
||||
let mut packed = Vec::new();
|
||||
let error = loop {
|
||||
match stream.next().await {
|
||||
Some(Ok(batch)) => packed.push(batch),
|
||||
Some(Err(error)) => break error,
|
||||
None => panic!("the source's error was not reported"),
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
error.to_string().contains("a source defect"),
|
||||
"reported for another reason: {error}"
|
||||
);
|
||||
// The source's own chunks are read and packed before it fails, so the error costs no rows the
|
||||
// source had already handed up; the failure itself releases the schema those rows were packed
|
||||
// against.
|
||||
assert!(
|
||||
!packed.is_empty(),
|
||||
"the chunks the source handed up are packed before it fails"
|
||||
);
|
||||
let mut positions = 0;
|
||||
for frame in &packed {
|
||||
let (_, _, chunk) = read_frame(frame, 0, &output)
|
||||
.expect("a packed frame reads back against the tree's schema");
|
||||
positions += chunk.series.time.len();
|
||||
}
|
||||
assert_eq!(
|
||||
GRID_LEN as usize, positions,
|
||||
"every row the source handed up, the closing one included, is packed before it fails"
|
||||
);
|
||||
|
||||
drop(output);
|
||||
assert!(
|
||||
schema.upgrade().is_none(),
|
||||
"the failed stream still holds the evaluated schema"
|
||||
);
|
||||
assert!(
|
||||
grid.upgrade().is_none(),
|
||||
"the failed stream still holds the grid the schema names"
|
||||
);
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ use table::table::scan::RegionScanExec;
|
||||
|
||||
use crate::extension_plan::{
|
||||
Absent, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate, RangeManipulate,
|
||||
ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn,
|
||||
ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn, VectorSelect,
|
||||
};
|
||||
|
||||
pub struct PromExtensionPlanner;
|
||||
@@ -72,6 +72,8 @@ impl ExtensionPlanner for PromExtensionPlanner {
|
||||
physical_inputs,
|
||||
session.config_options().execution.target_partitions,
|
||||
)
|
||||
} else if let Some(node) = node.as_any().downcast_ref::<VectorSelect>() {
|
||||
plan_vector_select(node, physical_inputs)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -165,3 +167,23 @@ fn plan_fused_series(
|
||||
.to_execution_plan(series_scan, label_source, ordering)
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// Builds the physical node of a [`VectorSelect`] over the one input it reads.
|
||||
///
|
||||
/// The node gathers what its input's partitions hand up and answers across the whole vector, so it
|
||||
/// takes exactly one input; the ranking itself is the node's own work. A plan with another number
|
||||
/// of inputs is a node the query planner did not build, so it is reported instead of being planned
|
||||
/// from whichever input happened to come first.
|
||||
fn plan_vector_select(
|
||||
select: &VectorSelect,
|
||||
physical_inputs: &[Arc<dyn ExecutionPlan>],
|
||||
) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
|
||||
let [input] = physical_inputs else {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"the VectorSelect node takes exactly one input, but {} were planned",
|
||||
physical_inputs.len()
|
||||
)));
|
||||
};
|
||||
|
||||
select.to_execution_plan(Arc::clone(input)).map(Some)
|
||||
}
|
||||
|
||||
@@ -14,19 +14,36 @@
|
||||
|
||||
//! Utils for testing extension plan
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt::{self, Formatter};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_query::native_histogram::{NativeHistogram, Span, UNKNOWN_COUNTER_RESET_HINT};
|
||||
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
|
||||
use common_recordbatch::DfRecordBatch as RecordBatch;
|
||||
use datafusion::arrow::array::Float64Array;
|
||||
use datafusion::arrow::datatypes::{
|
||||
ArrowPrimitiveType, DataType, Field, Schema, TimestampMillisecondType,
|
||||
ArrowPrimitiveType, DataType, Field, Schema, SchemaRef, TimestampMillisecondType,
|
||||
};
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::datasource::memory::MemorySourceConfig;
|
||||
use datafusion::datasource::source::DataSourceExec;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::TaskContext;
|
||||
use datafusion::execution::memory_pool::MemoryPool;
|
||||
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
|
||||
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
|
||||
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
|
||||
use datafusion::physical_plan::{
|
||||
DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties, RecordBatchStream,
|
||||
SendableRecordBatchStream,
|
||||
};
|
||||
use datatypes::arrow::array::TimestampMillisecondArray;
|
||||
use datatypes::arrow_array::StringArray;
|
||||
use futures::Stream;
|
||||
|
||||
pub(crate) const TIME_INDEX_COLUMN: &str = "timestamp";
|
||||
|
||||
@@ -95,3 +112,196 @@ pub(crate) fn prepare_test_data_with_stale_marker() -> DataSourceExec {
|
||||
MemorySourceConfig::try_new(&[vec![data]], schema, None).unwrap(),
|
||||
))
|
||||
}
|
||||
|
||||
/// A task context whose memory pool is `pool`.
|
||||
pub(crate) fn task_context(pool: Arc<dyn MemoryPool>) -> Arc<TaskContext> {
|
||||
let runtime = RuntimeEnvBuilder::new()
|
||||
.with_memory_pool(pool)
|
||||
.build()
|
||||
.expect("the runtime environment builds");
|
||||
Arc::new(TaskContext::default().with_runtime(Arc::new(runtime)))
|
||||
}
|
||||
|
||||
/// A physical input whose one partition's stream `make` builds.
|
||||
pub(crate) fn staged(
|
||||
schema: SchemaRef,
|
||||
make: impl Fn() -> SendableRecordBatchStream + Send + Sync + 'static,
|
||||
) -> Arc<dyn ExecutionPlan> {
|
||||
Arc::new(StagedPlan {
|
||||
properties: Arc::new(PlanProperties::new(
|
||||
EquivalenceProperties::new(schema),
|
||||
Partitioning::UnknownPartitioning(1),
|
||||
EmissionType::Incremental,
|
||||
Boundedness::Bounded,
|
||||
)),
|
||||
make: Box::new(make),
|
||||
})
|
||||
}
|
||||
|
||||
/// A physical input, so a test can stage what a memory source cannot: a pending poll, an error
|
||||
/// after some rows, and a stream whose drop it can see.
|
||||
struct StagedPlan {
|
||||
make: Box<dyn Fn() -> SendableRecordBatchStream + Send + Sync>,
|
||||
properties: Arc<PlanProperties>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for StagedPlan {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("StagedPlan").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayAs for StagedPlan {
|
||||
fn fmt_as(&self, _t: DisplayFormatType, _f: &mut Formatter) -> fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionPlan for StagedPlan {
|
||||
fn name(&self) -> &str {
|
||||
"StagedPlan"
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
&self.properties
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn apply_expressions(
|
||||
&self,
|
||||
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
|
||||
) -> DataFusionResult<TreeNodeRecursion> {
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
}
|
||||
|
||||
fn with_new_children(
|
||||
self: Arc<Self>,
|
||||
_children: Vec<Arc<dyn ExecutionPlan>>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&self,
|
||||
partition: usize,
|
||||
_context: Arc<TaskContext>,
|
||||
) -> DataFusionResult<SendableRecordBatchStream> {
|
||||
// A scan answers the partitions it declares and no others, which is what makes an index
|
||||
// past this plan's count an error the node above has to pass on.
|
||||
if partition >= self.properties.partitioning.partition_count() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"StagedPlan has no partition {partition}"
|
||||
)));
|
||||
}
|
||||
Ok((self.make)())
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream a [`StagedPlan`] hands over: `batches`, then an optional error, with a pending poll,
|
||||
/// a drop and a failure a test can observe.
|
||||
pub(crate) struct StagedStream {
|
||||
schema: SchemaRef,
|
||||
batches: VecDeque<RecordBatch>,
|
||||
handed: usize,
|
||||
/// Hand this many batches, then answer [`Poll::Pending`] once.
|
||||
pending_after: Option<usize>,
|
||||
/// The error to report once the batches are exhausted.
|
||||
error: Option<&'static str>,
|
||||
/// Set when this stream is dropped, so a test can see the input being released.
|
||||
dropped: Option<Arc<AtomicBool>>,
|
||||
/// Counts the batches this stream has handed over, so a test can see how far one poll read.
|
||||
counted: Option<Arc<AtomicUsize>>,
|
||||
/// Set when this stream reports its error, so a test can see it was read to its failure.
|
||||
failed: Option<Arc<AtomicBool>>,
|
||||
}
|
||||
|
||||
impl StagedStream {
|
||||
pub(crate) fn new(schema: SchemaRef, batches: Vec<RecordBatch>) -> Self {
|
||||
Self {
|
||||
schema,
|
||||
batches: batches.into(),
|
||||
handed: 0,
|
||||
pending_after: None,
|
||||
error: None,
|
||||
dropped: None,
|
||||
counted: None,
|
||||
failed: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pending_after(mut self, batches: usize) -> Self {
|
||||
self.pending_after = Some(batches);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn error(mut self, message: &'static str) -> Self {
|
||||
self.error = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets `flag` when this stream is dropped, so a test can see the input being released.
|
||||
pub(crate) fn dropped(mut self, flag: &Arc<AtomicBool>) -> Self {
|
||||
self.dropped = Some(Arc::clone(flag));
|
||||
self
|
||||
}
|
||||
|
||||
/// Counts each batch handed over into `counter`, so a test can see how far one poll read.
|
||||
pub(crate) fn counted(mut self, counter: &Arc<AtomicUsize>) -> Self {
|
||||
self.counted = Some(Arc::clone(counter));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets `flag` when this stream reports its error, so a test can see it was read to its failure.
|
||||
pub(crate) fn failed(mut self, flag: &Arc<AtomicBool>) -> Self {
|
||||
self.failed = Some(Arc::clone(flag));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for StagedStream {
|
||||
type Item = DataFusionResult<RecordBatch>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = &mut *self;
|
||||
if this.pending_after == Some(this.handed) {
|
||||
this.pending_after = None;
|
||||
cx.waker().wake_by_ref();
|
||||
return Poll::Pending;
|
||||
}
|
||||
match this.batches.pop_front() {
|
||||
Some(batch) => {
|
||||
this.handed += 1;
|
||||
if let Some(counter) = &this.counted {
|
||||
counter.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
Poll::Ready(Some(Ok(batch)))
|
||||
}
|
||||
None => match this.error.take() {
|
||||
Some(message) => {
|
||||
if let Some(failed) = &this.failed {
|
||||
failed.store(true, Ordering::SeqCst);
|
||||
}
|
||||
Poll::Ready(Some(Err(DataFusionError::Execution(message.to_string()))))
|
||||
}
|
||||
None => Poll::Ready(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordBatchStream for StagedStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StagedStream {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dropped) = &self.dropped {
|
||||
dropped.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,808 @@
|
||||
// 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 global `topk`/`bottomk` over the evaluated frames another node produced.
|
||||
//!
|
||||
//! Which `k` series a group keeps at a grid point depends on every series present there, so the
|
||||
//! selection is one answer for the whole vector: a per-partition `topk` would answer with that
|
||||
//! partition's best, not the query's. This node therefore reads its input as one global stream in
|
||||
//! producer-then-ordinal order, which makes each series' chunks contiguous again.
|
||||
//!
|
||||
//! The tree is cut directly at the root, not searched for: the child of the root `Vector` node is
|
||||
//! the prefix, run over the raw input and emitted as frames, and the same root node is the suffix,
|
||||
//! with its child replaced by one bound input. Any other shape is
|
||||
//! [`DataFusionError::NotImplemented`], reported before this node exists, so a caller can fall back
|
||||
//! to the existing PromQL planner.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt::{self, Formatter};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use datafusion::arrow::compute::SortOptions;
|
||||
use datafusion::arrow::datatypes::{Schema, SchemaRef};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::common::DFSchemaRef;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::TaskContext;
|
||||
use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation, UnboundedMemoryPool};
|
||||
use datafusion::logical_expr::{Expr, Extension, LogicalPlan, UserDefinedLogicalNodeCore};
|
||||
use datafusion::physical_expr::{
|
||||
EquivalenceProperties, LexOrdering, LexRequirement, OrderingRequirements, PhysicalExpr,
|
||||
PhysicalSortExpr,
|
||||
};
|
||||
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
|
||||
use datafusion::physical_plan::execution_plan::EmissionType;
|
||||
use datafusion::physical_plan::expressions::Column;
|
||||
use datafusion::physical_plan::metrics::MetricsSet;
|
||||
use datafusion::physical_plan::sorts::sort::SortExec;
|
||||
use datafusion::physical_plan::{
|
||||
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements,
|
||||
Partitioning, PlanProperties, RecordBatchStream, SendableRecordBatchStream,
|
||||
};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::SeriesSchema;
|
||||
use futures::Stream;
|
||||
|
||||
use crate::extension_plan::evaluated_frame::{self, Sequence};
|
||||
use crate::extension_plan::fused_series::{
|
||||
FusedSeries, FusedSeriesBinding, LabelSets, OutputColumn, classify_output,
|
||||
series_to_record_batch,
|
||||
};
|
||||
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor, RuntimeTreeHandle};
|
||||
use crate::native::plan::{
|
||||
BoundInput, BoundVectorOp, NativeExpr, NativeNode, NativeTree, reads_across_series,
|
||||
};
|
||||
|
||||
/// How many input steps one poll runs before it wakes itself.
|
||||
///
|
||||
/// A frame row settles nothing before the input ends, so without a budget an input of many frames
|
||||
/// would be read to its end inside one poll. The figure is the fused node's, which reads the same
|
||||
/// stream the same way.
|
||||
const POLL_BUDGET: usize = 64;
|
||||
|
||||
/// The only ordering placed below the selection: ascending, nulls last.
|
||||
const ASCENDING: SortOptions = SortOptions {
|
||||
descending: false,
|
||||
nulls_first: false,
|
||||
};
|
||||
|
||||
/// The logical plan of one global vector selection over evaluated frames.
|
||||
#[derive(Debug)]
|
||||
pub struct VectorSelect {
|
||||
/// The PromQL text this node was compiled from.
|
||||
promql: Arc<str>,
|
||||
/// The frames, produced by the prefix.
|
||||
input: LogicalPlan,
|
||||
/// The root selection alone, over one bound input.
|
||||
suffix: Arc<NativeTree>,
|
||||
/// The evaluated series schema the frames are packed against.
|
||||
series_schema: Arc<SeriesSchema>,
|
||||
/// The output column holding the grid timestamps.
|
||||
time_column: String,
|
||||
/// The logical tag names the output carries.
|
||||
tags: Vec<String>,
|
||||
/// The columns this node produces.
|
||||
output_schema: DFSchemaRef,
|
||||
}
|
||||
|
||||
impl VectorSelect {
|
||||
/// The name this node is shown under.
|
||||
pub const fn name() -> &'static str {
|
||||
"VectorSelect"
|
||||
}
|
||||
|
||||
/// Creates the node for `full_tree`, whose frames come from `raw_input`.
|
||||
///
|
||||
/// The prefix is the root's child tree run over the raw input and emitted as frames; the suffix
|
||||
/// is the root itself with its child replaced by one input. A tree this node is not the answer
|
||||
/// for is [`DataFusionError::NotImplemented`], which is what lets a caller fall back before any
|
||||
/// extension node is created.
|
||||
pub fn try_new(
|
||||
promql: Arc<str>,
|
||||
full_tree: NativeTree,
|
||||
binding: FusedSeriesBinding,
|
||||
raw_input: LogicalPlan,
|
||||
output_schema: DFSchemaRef,
|
||||
) -> DataFusionResult<Self> {
|
||||
let (op, child) = match &full_tree.root().expr {
|
||||
NativeExpr::Vector { op, input } => (op.clone(), input),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"a tree whose root is not an operation over the whole input vector",
|
||||
));
|
||||
}
|
||||
};
|
||||
if !matches!(op, BoundVectorOp::TopK { .. }) {
|
||||
return Err(unsupported("a vector operation other than topk or bottomk"));
|
||||
}
|
||||
// A frame names one series' chunk and says nothing about the vector it belongs to, so a
|
||||
// child that reads across series cannot be framed.
|
||||
if reads_across_series(child) {
|
||||
return Err(unsupported(
|
||||
"a topk over an expression that reads across series",
|
||||
));
|
||||
}
|
||||
let Some(child_schema) = child.output.samples() else {
|
||||
return Err(unsupported(
|
||||
"a topk over an expression that is not a vector",
|
||||
));
|
||||
};
|
||||
if child_schema.fields.len() != 1 {
|
||||
return Err(unsupported(
|
||||
"a topk over a vector of more than one field, which a frame cannot carry",
|
||||
));
|
||||
}
|
||||
// The frames name absolute positions on the statement's grid, which is the grid the time
|
||||
// column stamps, so the two have to agree.
|
||||
let Some(child_grid) = child_schema.eval_grid.as_ref() else {
|
||||
return Err(unsupported(
|
||||
"a topk over an expression that is not evaluated",
|
||||
));
|
||||
};
|
||||
if child_grid.spec() != binding.grid.spec() {
|
||||
return Err(unsupported(
|
||||
"a topk whose input is evaluated on another grid than the statement's",
|
||||
));
|
||||
}
|
||||
|
||||
let time_column = binding.time_index.clone();
|
||||
let tags = binding.tags.clone();
|
||||
let prefix = FusedSeries::try_new_evaluated(
|
||||
Arc::clone(&promql),
|
||||
NativeTree::try_new(child.as_ref().clone())?,
|
||||
binding,
|
||||
raw_input,
|
||||
)?;
|
||||
// The frames arrive ordered by producer and then ordinal, so each series' chunks are
|
||||
// contiguous and no series interleaves with another.
|
||||
let suffix = Arc::new(NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Vector {
|
||||
input: Box::new(NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
output: child.output.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
output: child.output.clone(),
|
||||
}),
|
||||
op,
|
||||
},
|
||||
output: full_tree.root().output.clone(),
|
||||
})?);
|
||||
Ok(Self {
|
||||
promql,
|
||||
input: LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(prefix),
|
||||
}),
|
||||
suffix,
|
||||
series_schema: Arc::clone(child_schema),
|
||||
time_column,
|
||||
tags,
|
||||
output_schema,
|
||||
})
|
||||
}
|
||||
|
||||
/// The physical node that runs `exec_input` as this node's input.
|
||||
///
|
||||
/// The selection is one answer for the whole vector, so the frames are brought into one
|
||||
/// partition and ordered by producer and ordinal first. Both steps are ordinary DataFusion
|
||||
/// nodes, and the ordering this node requires is exactly the sort below it.
|
||||
pub fn to_execution_plan(
|
||||
&self,
|
||||
exec_input: Arc<dyn ExecutionPlan>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
let global = match exec_input.properties().partitioning.partition_count() {
|
||||
0 => {
|
||||
return Err(DataFusionError::Plan(
|
||||
"VectorSelect has an input with no partitions".to_string(),
|
||||
));
|
||||
}
|
||||
1 => exec_input,
|
||||
_ => Arc::new(CoalescePartitionsExec::new(exec_input)),
|
||||
};
|
||||
let sort = SortExec::new(frame_ordering(global.schema().as_ref())?, global);
|
||||
Ok(Arc::new(VectorSelectExec::try_new(
|
||||
Arc::clone(&self.promql),
|
||||
Arc::new(sort),
|
||||
Arc::clone(&self.suffix),
|
||||
Arc::clone(&self.series_schema),
|
||||
self.output_schema.inner().clone(),
|
||||
self.time_column.clone(),
|
||||
self.tags.clone(),
|
||||
)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl UserDefinedLogicalNodeCore for VectorSelect {
|
||||
fn name(&self) -> &str {
|
||||
Self::name()
|
||||
}
|
||||
|
||||
fn inputs(&self) -> Vec<&LogicalPlan> {
|
||||
vec![&self.input]
|
||||
}
|
||||
|
||||
fn schema(&self) -> &DFSchemaRef {
|
||||
&self.output_schema
|
||||
}
|
||||
|
||||
fn expressions(&self) -> Vec<Expr> {
|
||||
// The selection's operands are bound inside its tree.
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f, "VectorSelect: {}", self.promql)
|
||||
}
|
||||
|
||||
fn with_exprs_and_inputs(
|
||||
&self,
|
||||
_exprs: Vec<Expr>,
|
||||
mut inputs: Vec<LogicalPlan>,
|
||||
) -> DataFusionResult<Self> {
|
||||
if inputs.len() != 1 {
|
||||
return Err(DataFusionError::Internal(
|
||||
"VectorSelect should have exactly one input".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
promql: Arc::clone(&self.promql),
|
||||
input: inputs.pop().unwrap(),
|
||||
suffix: Arc::clone(&self.suffix),
|
||||
series_schema: Arc::clone(&self.series_schema),
|
||||
time_column: self.time_column.clone(),
|
||||
tags: self.tags.clone(),
|
||||
output_schema: Arc::clone(&self.output_schema),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for VectorSelect {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
// `NativeTree` carries no structural equality, so its rendering stands in for it.
|
||||
self.promql == other.promql
|
||||
&& self.suffix.to_string() == other.suffix.to_string()
|
||||
&& self.input == other.input
|
||||
&& self.time_column == other.time_column
|
||||
&& self.tags == other.tags
|
||||
&& self.output_schema == other.output_schema
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for VectorSelect {}
|
||||
|
||||
impl Hash for VectorSelect {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.promql.hash(state);
|
||||
self.input.hash(state);
|
||||
self.time_column.hash(state);
|
||||
self.tags.hash(state);
|
||||
self.output_schema.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for VectorSelect {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
match self.promql.partial_cmp(&other.promql) {
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
match self
|
||||
.suffix
|
||||
.to_string()
|
||||
.partial_cmp(&other.suffix.to_string())
|
||||
{
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
match self.input.partial_cmp(&other.input) {
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
match self.time_column.partial_cmp(&other.time_column) {
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
match self.tags.partial_cmp(&other.tags) {
|
||||
Some(Ordering::Equal) => {}
|
||||
ord => return ord,
|
||||
}
|
||||
if self.output_schema == other.output_schema {
|
||||
Some(Ordering::Equal)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal for a statement this node does not answer.
|
||||
fn unsupported(what: &str) -> DataFusionError {
|
||||
DataFusionError::NotImplemented(format!("VectorSelect does not handle {what}"))
|
||||
}
|
||||
|
||||
/// The ordering the frames are read in: producer ascending, then frame ordinal ascending.
|
||||
///
|
||||
/// Both columns are taken from `schema`, so the sort can only name columns the frame reader accepts.
|
||||
fn frame_ordering(schema: &Schema) -> DataFusionResult<LexOrdering> {
|
||||
let column = |index: usize| -> DataFusionResult<Arc<dyn PhysicalExpr>> {
|
||||
let field = schema.fields().get(index).ok_or_else(|| {
|
||||
DataFusionError::Plan(format!(
|
||||
"an evaluated frame has {} columns, so it has no column {index}",
|
||||
schema.fields().len()
|
||||
))
|
||||
})?;
|
||||
Ok(Arc::new(Column::new(field.name(), index)))
|
||||
};
|
||||
LexOrdering::new([
|
||||
PhysicalSortExpr::new(column(0)?, ASCENDING),
|
||||
PhysicalSortExpr::new(column(1)?, ASCENDING),
|
||||
])
|
||||
.ok_or_else(|| DataFusionError::Plan("the ordering of an evaluated frame is empty".to_string()))
|
||||
}
|
||||
|
||||
/// The physical node that runs one selection over the whole input vector.
|
||||
pub struct VectorSelectExec {
|
||||
/// The PromQL text this suffix was compiled from, which is what the plan line shows.
|
||||
promql: Arc<str>,
|
||||
/// The ordered frames, in one partition.
|
||||
input: Arc<dyn ExecutionPlan>,
|
||||
/// The root selection alone.
|
||||
suffix: Arc<NativeTree>,
|
||||
/// The evaluated series schema every frame is read against.
|
||||
series_schema: Arc<SeriesSchema>,
|
||||
/// Where each output column comes from.
|
||||
classification: Arc<[OutputColumn]>,
|
||||
/// The tag column names, indexed by [`OutputColumn::Tag`].
|
||||
tags: Arc<[String]>,
|
||||
/// The output column holding the grid timestamps, kept so the node can be rebuilt.
|
||||
time_column: String,
|
||||
/// The columns this node produces.
|
||||
output_schema: SchemaRef,
|
||||
/// The ordering the frames arrive in, which is also what this node requires.
|
||||
ordering: LexOrdering,
|
||||
/// The label sets the final series claim, shared by every execution of this plan.
|
||||
labels: Arc<Mutex<LabelSets>>,
|
||||
/// Runtime roots from executions of the suffix, retained for fresh metrics exports.
|
||||
runtimes: Mutex<Vec<(usize, RuntimeTreeHandle)>>,
|
||||
/// This node's partitioning, emission and boundedness.
|
||||
properties: Arc<PlanProperties>,
|
||||
}
|
||||
|
||||
impl VectorSelectExec {
|
||||
/// Creates the node, rejecting an input it cannot read and an output it cannot convert.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn try_new(
|
||||
promql: Arc<str>,
|
||||
input: Arc<dyn ExecutionPlan>,
|
||||
suffix: Arc<NativeTree>,
|
||||
series_schema: Arc<SeriesSchema>,
|
||||
output_schema: SchemaRef,
|
||||
time_column: String,
|
||||
tags: Vec<String>,
|
||||
) -> DataFusionResult<Self> {
|
||||
if input.schema().as_ref() != evaluated_frame::schema().as_ref() {
|
||||
return Err(DataFusionError::Plan(
|
||||
"VectorSelectExec reads evaluated frames, but its input is not that layout"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
let partition_count = input.properties().partitioning.partition_count();
|
||||
if partition_count != 1 {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"VectorSelectExec reads one global input, but its input has {partition_count} \
|
||||
partitions"
|
||||
)));
|
||||
}
|
||||
let ordering = frame_ordering(input.schema().as_ref())?;
|
||||
// Building a throwaway state proves the runtime executes this tree.
|
||||
let _ = NativeExecutionState::try_new(&suffix, Arc::new(UnboundedMemoryPool::default()))?;
|
||||
let classification =
|
||||
classify_output(&output_schema, &series_schema.fields, &tags, &time_column)?;
|
||||
// One partition and a final result: nothing is answered before the input ended.
|
||||
let properties = Arc::new(PlanProperties::new(
|
||||
EquivalenceProperties::new(output_schema.clone()),
|
||||
Partitioning::UnknownPartitioning(1),
|
||||
EmissionType::Final,
|
||||
input.properties().boundedness,
|
||||
));
|
||||
Ok(Self {
|
||||
promql,
|
||||
input,
|
||||
suffix,
|
||||
series_schema,
|
||||
classification: classification.into(),
|
||||
tags: tags.into(),
|
||||
time_column,
|
||||
output_schema,
|
||||
ordering,
|
||||
labels: Arc::new(Mutex::new(LabelSets::default())),
|
||||
runtimes: Mutex::new(Vec::new()),
|
||||
properties,
|
||||
})
|
||||
}
|
||||
|
||||
/// The name this node is shown under.
|
||||
pub const fn name() -> &'static str {
|
||||
"VectorSelectExec"
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for VectorSelectExec {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("VectorSelectExec").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayAs for VectorSelectExec {
|
||||
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f, "VectorSelectExec: {}\n{}", self.promql, self.suffix)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionPlan for VectorSelectExec {
|
||||
fn name(&self) -> &str {
|
||||
Self::name()
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
&self.properties
|
||||
}
|
||||
|
||||
/// A global selection is one answer for the whole vector. A hash requirement would force a hash
|
||||
/// exchange as soon as the child has more than one partition, and that exchange reorders the
|
||||
/// frames the sort below just ordered.
|
||||
fn input_distribution_requirements(&self) -> InputDistributionRequirements {
|
||||
InputDistributionRequirements::new(vec![Distribution::SinglePartition])
|
||||
}
|
||||
|
||||
/// The frames have to arrive in exactly the order the sort below produces; stating it in the
|
||||
/// sort's own terms is what keeps `EnforceSorting` from removing it.
|
||||
///
|
||||
/// The requirement is the stored ordering rather than a second construction of it: this method
|
||||
/// cannot report an error, and rebuilding the columns here would need one.
|
||||
fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
|
||||
vec![Some(OrderingRequirements::new(LexRequirement::from(
|
||||
self.ordering.clone(),
|
||||
)))]
|
||||
}
|
||||
|
||||
/// Splitting the input cannot help: the selection ranks the whole vector.
|
||||
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
|
||||
vec![false]
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
|
||||
vec![&self.input]
|
||||
}
|
||||
|
||||
fn apply_expressions(
|
||||
&self,
|
||||
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
|
||||
) -> DataFusionResult<TreeNodeRecursion> {
|
||||
// The selection's operands are bound inside its tree.
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
}
|
||||
|
||||
fn with_new_children(
|
||||
self: Arc<Self>,
|
||||
children: Vec<Arc<dyn ExecutionPlan>>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
let [child] = <[Arc<dyn ExecutionPlan>; 1]>::try_from(children).map_err(|children| {
|
||||
DataFusionError::Plan(format!(
|
||||
"VectorSelectExec requires exactly one child, got {}",
|
||||
children.len()
|
||||
))
|
||||
})?;
|
||||
// Rebuilt rather than patched: the new child's schema and partitioning are what the frame
|
||||
// reader and the global ordering rely on.
|
||||
Ok(Arc::new(Self::try_new(
|
||||
Arc::clone(&self.promql),
|
||||
child,
|
||||
Arc::clone(&self.suffix),
|
||||
Arc::clone(&self.series_schema),
|
||||
self.output_schema.clone(),
|
||||
self.time_column.clone(),
|
||||
self.tags.to_vec(),
|
||||
)?))
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&self,
|
||||
partition: usize,
|
||||
context: Arc<TaskContext>,
|
||||
) -> DataFusionResult<SendableRecordBatchStream> {
|
||||
// The label-set state is the plan's, so its charge is attached once and released with the
|
||||
// plan rather than with a stream.
|
||||
self.labels
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.attach(&context.runtime_env().memory_pool);
|
||||
let input = self.input.execute(partition, Arc::clone(&context))?;
|
||||
let state = NativeExecutionState::try_new(
|
||||
&self.suffix,
|
||||
Arc::clone(&context.runtime_env().memory_pool),
|
||||
)?;
|
||||
// The runtime root outlives the stream: it is what this plan reports metrics from.
|
||||
let runtime = state.runtime_tree();
|
||||
self.runtimes
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push((partition, runtime));
|
||||
// One frame batch is held at a time, so this reservation follows that batch.
|
||||
let frames = MemoryConsumer::new("VectorSelectExec frames")
|
||||
.register(&context.runtime_env().memory_pool);
|
||||
Ok(Box::pin(VectorSelectStream {
|
||||
input: Some(input),
|
||||
batch: None,
|
||||
row: 0,
|
||||
sequence: Sequence::default(),
|
||||
executor: Some(NativeExecutor::new(state)),
|
||||
input_id: InputId::new(0),
|
||||
series_schema: Some(Arc::clone(&self.series_schema)),
|
||||
classification: Arc::clone(&self.classification),
|
||||
tags: Arc::clone(&self.tags),
|
||||
output_schema: self.output_schema.clone(),
|
||||
labels: Arc::clone(&self.labels),
|
||||
frames,
|
||||
draining: false,
|
||||
done: false,
|
||||
}))
|
||||
}
|
||||
|
||||
fn metrics(&self) -> Option<MetricsSet> {
|
||||
let runtimes = self.runtimes.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut metrics = MetricsSet::new();
|
||||
for (partition, runtime) in runtimes.iter() {
|
||||
let runtime = runtime.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for metric in runtime.export_metrics(*partition).iter() {
|
||||
metrics.push(Arc::clone(metric));
|
||||
}
|
||||
}
|
||||
Some(metrics)
|
||||
}
|
||||
}
|
||||
|
||||
/// The batches one execution of [`VectorSelectExec`] yields.
|
||||
struct VectorSelectStream {
|
||||
/// The ordered frames, or `None` once the input ended or failed.
|
||||
input: Option<SendableRecordBatchStream>,
|
||||
/// The frame batch in hand, of which `row` is next.
|
||||
batch: Option<RecordBatch>,
|
||||
/// The first row of `batch` not handed over yet.
|
||||
row: usize,
|
||||
/// The producer and ordinal order the frames have to arrive in.
|
||||
sequence: Sequence,
|
||||
/// The execution of this node's suffix, or `None` once its answer is complete.
|
||||
executor: Option<NativeExecutor>,
|
||||
/// The position the suffix's input node is fed at.
|
||||
input_id: InputId,
|
||||
/// The evaluated series schema every frame is read against, or `None` once this stream is done.
|
||||
///
|
||||
/// It is the only thing here that can hold the statement's grid alive - the plan's copy is not
|
||||
/// reachable through this stream once the stream is gone - so it is given up when the stream
|
||||
/// reaches its end or fails, after the execution that read it has been dropped, rather than
|
||||
/// with the stream itself.
|
||||
series_schema: Option<Arc<SeriesSchema>>,
|
||||
/// Where each output column comes from.
|
||||
classification: Arc<[OutputColumn]>,
|
||||
/// The tag column names, indexed by [`OutputColumn::Tag`].
|
||||
tags: Arc<[String]>,
|
||||
/// The schema of every batch this stream yields.
|
||||
output_schema: SchemaRef,
|
||||
/// The label-set occupancy shared with the other executions of this plan.
|
||||
labels: Arc<Mutex<LabelSets>>,
|
||||
/// What the frame batch in hand keeps charged on the task's memory pool.
|
||||
frames: MemoryReservation,
|
||||
/// Whether the input ended, so what is left is the selection's own answer.
|
||||
draining: bool,
|
||||
/// Whether this stream ended.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl VectorSelectStream {
|
||||
/// Takes the frame batch, charging the pool for the batch as a whole.
|
||||
fn hold(&mut self, batch: RecordBatch) -> DataFusionResult<()> {
|
||||
self.frames.try_resize(batch.get_array_memory_size())?;
|
||||
self.batch = Some(batch);
|
||||
self.row = 0;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gives the frame batch back, returning what it held to the pool.
|
||||
fn release_batch(&mut self) {
|
||||
self.batch = None;
|
||||
self.row = 0;
|
||||
let _ = self.frames.try_resize(0);
|
||||
}
|
||||
|
||||
/// Reads row `row` of the held batch and hands its chunk to the suffix.
|
||||
///
|
||||
/// The sequence is checked before the chunk is pushed, so a producer that starts before the
|
||||
/// previous one closed, or an ordinal out of order, is refused rather than read as a
|
||||
/// continuation. Nothing may come back before the input ends: a chunk here would be an answer
|
||||
/// computed from part of the vector.
|
||||
fn feed(&mut self, row: usize) -> DataFusionResult<()> {
|
||||
let Some(batch) = self.batch.as_ref() else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"VectorSelectExec read a row no batch holds".to_string(),
|
||||
));
|
||||
};
|
||||
let Some(schema) = self.series_schema.as_ref() else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"VectorSelectExec read a frame after it gave up its series schema".to_string(),
|
||||
));
|
||||
};
|
||||
let (producer, ordinal, chunk) = evaluated_frame::read(batch, row, schema)?;
|
||||
self.sequence.check(producer, ordinal, chunk.is_last)?;
|
||||
let Some(executor) = self.executor.as_mut() else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"VectorSelectExec read a frame after its execution closed".to_string(),
|
||||
));
|
||||
};
|
||||
executor.push_evaluated(self.input_id, chunk)?;
|
||||
if executor.next_chunk()?.is_some() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"the native selection produced a chunk before its input ended, so it answered from \
|
||||
part of the vector"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends the frame input and every series in it, so the selection settles.
|
||||
///
|
||||
/// The sequence ends first: an unclosed producer is a frame-stream defect, which ending the
|
||||
/// runtime would report only as a series left open.
|
||||
fn finish_input(&mut self) -> DataFusionResult<()> {
|
||||
self.sequence.finish()?;
|
||||
match self.executor.as_mut() {
|
||||
Some(executor) => executor.end_of_input(),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pulls one series the selection kept and converts it, or `None` when there is no more.
|
||||
///
|
||||
/// One chunk per call is what keeps this a stream, and `None` is also when the execution closes
|
||||
/// and returns its reservations, so it is dropped here rather than held until the stream is.
|
||||
fn pull_one(&mut self) -> DataFusionResult<Option<RecordBatch>> {
|
||||
let chunk = match self.executor.as_mut() {
|
||||
Some(executor) => executor.next_chunk()?,
|
||||
None => return Ok(None),
|
||||
};
|
||||
let Some(chunk) = chunk else {
|
||||
self.executor = None;
|
||||
return Ok(None);
|
||||
};
|
||||
// The frames below claimed what they held before the selection chose among them; the
|
||||
// answer is claimed here as well, so two kept series on one label set are still refused.
|
||||
self.labels
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.claim(&chunk.series)?;
|
||||
let batch = series_to_record_batch(
|
||||
&self.classification,
|
||||
&self.tags,
|
||||
&self.output_schema,
|
||||
&chunk,
|
||||
)?;
|
||||
Ok(Some(batch))
|
||||
}
|
||||
|
||||
/// Ends the stream in an error, releasing the execution, the held frame and the input at once.
|
||||
///
|
||||
/// The label-set map is the plan's, so what it holds stays charged until the plan itself goes.
|
||||
fn fail(&mut self) {
|
||||
self.done = true;
|
||||
self.executor = None;
|
||||
self.input = None;
|
||||
self.series_schema = None;
|
||||
self.release_batch();
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordBatchStream for VectorSelectStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.output_schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for VectorSelectStream {
|
||||
type Item = DataFusionResult<RecordBatch>;
|
||||
|
||||
fn poll_next(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<DataFusionResult<RecordBatch>>> {
|
||||
let this = &mut *self;
|
||||
for _ in 0..POLL_BUDGET {
|
||||
if this.done {
|
||||
// The grid the schema names is the last thing this stream could hold after it
|
||||
// ended, so it is given up here as well as on an error.
|
||||
this.series_schema = None;
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
// The input ended, so what is left is the selection's answer, one series per pull.
|
||||
if this.draining {
|
||||
match this.pull_one() {
|
||||
Ok(Some(batch)) => return Poll::Ready(Some(Ok(batch))),
|
||||
Ok(None) => {
|
||||
this.done = true;
|
||||
this.series_schema = None;
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
this.fail();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The held batch is read a row at a time and released with its last row, so one poll
|
||||
// never pays for two batches.
|
||||
if this.batch.is_some() {
|
||||
let rows = this.batch.as_ref().map_or(0, RecordBatch::num_rows);
|
||||
if this.row < rows {
|
||||
let row = this.row;
|
||||
this.row += 1;
|
||||
if let Err(error) = this.feed(row) {
|
||||
this.fail();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
this.release_batch();
|
||||
continue;
|
||||
}
|
||||
let Some(input) = this.input.as_mut() else {
|
||||
this.done = true;
|
||||
this.series_schema = None;
|
||||
continue;
|
||||
};
|
||||
// `as_mut` is what turns the pinned box into the pinned stream a poll takes.
|
||||
let polled = input.as_mut().poll_next(cx);
|
||||
match polled {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(None) => {
|
||||
this.input = None;
|
||||
if let Err(error) = this.finish_input() {
|
||||
this.fail();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
this.draining = true;
|
||||
}
|
||||
Poll::Ready(Some(Err(error))) => {
|
||||
// A failed input leaves a selection computed from part of the vector, so no
|
||||
// answer may be handed out.
|
||||
this.fail();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
Poll::Ready(Some(Ok(batch))) => {
|
||||
if let Err(error) = this.hold(batch) {
|
||||
this.fail();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -37,7 +37,7 @@ use datafusion_optimizer::push_down_filter::PushDownFilter;
|
||||
use datafusion_optimizer::rewrite_set_comparison::RewriteSetComparison;
|
||||
use datafusion_optimizer::scalar_subquery_to_join::ScalarSubqueryToJoin;
|
||||
use datafusion_optimizer::simplify_expressions::SimplifyExpressions;
|
||||
use promql::extension_plan::{FusedSeries, SeriesDivide};
|
||||
use promql::extension_plan::{FusedSeries, SeriesDivide, VectorSelect};
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
use table::metadata::TableType;
|
||||
use table::table::adapter::DfTableProviderAdapter;
|
||||
@@ -114,7 +114,8 @@ pub struct DistPlannerAnalyzer {
|
||||
///
|
||||
/// A region input normally has to be encoded to Substrait before it can leave the frontend, and
|
||||
/// [`PlanRewriter::should_expand`] cuts the plan at the first node that does not encode. In
|
||||
/// process, a root `FusedSeries` plan travels as a `LogicalPlan` instead and skips that gate;
|
||||
/// process, a native root plan - a root `FusedSeries`, or a root `VectorSelect` over the
|
||||
/// per-series prefix it ranks - travels as a `LogicalPlan` instead and skips that gate;
|
||||
/// other plans retain the ordinary encoding checks.
|
||||
///
|
||||
/// Whoever builds the query engine sets this, once, from the transport it wired. It is neither a
|
||||
@@ -446,9 +447,9 @@ struct PlanRewriter {
|
||||
/// Used by [`PlanRewriter::should_expand`] to skip the per-node encoding check.
|
||||
///
|
||||
/// Used for the ordinary standalone fast path when the root plan is encodable. It is not
|
||||
/// needed when the root itself is the in-process `FusedSeries` exception.
|
||||
/// needed when the root itself is the in-process native exception.
|
||||
whole_plan_encodable: bool,
|
||||
/// In-process transport skips the encodability gate only when the rewritten root itself is FusedSeries.
|
||||
/// In-process transport skips the encodability gate only when the rewritten root is a native plan.
|
||||
skip_encodability_gate: bool,
|
||||
/// Current level in the tree
|
||||
level: usize,
|
||||
@@ -505,8 +506,31 @@ struct PlanRewriter {
|
||||
new_child_plan: Option<LogicalPlan>,
|
||||
}
|
||||
|
||||
fn is_fused_series_plan(plan: &LogicalPlan) -> bool {
|
||||
matches!(plan, LogicalPlan::Extension(extension) if extension.node.as_any().is::<FusedSeries>())
|
||||
/// Whether `plan` is a native root: the shape an in-process engine hands to a region as a
|
||||
/// `LogicalPlan` as it was planned.
|
||||
///
|
||||
/// A root `FusedSeries` is such a plan. So is a root `VectorSelect` that ranks a per-series prefix,
|
||||
/// i.e. one whose one input is the `FusedSeries` over the scan it reads: the ranking stays on the
|
||||
/// frontend and that prefix is what a region builds.
|
||||
///
|
||||
/// The check is by exact shape and not by name, so a wrapper around either node, or one whose
|
||||
/// child is not the one a region builds it from, keeps the ordinary encoding checks.
|
||||
fn is_in_process_native_plan(plan: &LogicalPlan) -> bool {
|
||||
let LogicalPlan::Extension(extension) = plan else {
|
||||
return false;
|
||||
};
|
||||
if extension.node.as_any().is::<FusedSeries>() {
|
||||
return true;
|
||||
}
|
||||
if !extension.node.as_any().is::<VectorSelect>() {
|
||||
return false;
|
||||
}
|
||||
matches!(
|
||||
extension.node.inputs().as_slice(),
|
||||
[LogicalPlan::Extension(prefix)]
|
||||
if prefix.node.as_any().is::<FusedSeries>()
|
||||
&& matches!(prefix.node.inputs().as_slice(), [LogicalPlan::TableScan(_)])
|
||||
)
|
||||
}
|
||||
|
||||
impl PlanRewriter {
|
||||
@@ -518,7 +542,7 @@ impl PlanRewriter {
|
||||
_ => plan,
|
||||
};
|
||||
let skip_encodability_gate =
|
||||
in_process_region_transport && is_fused_series_plan(native_root);
|
||||
in_process_region_transport && is_in_process_native_plan(native_root);
|
||||
Self {
|
||||
// Preserve the ordinary whole-plan fast path unless this is the in-process root
|
||||
// exception: no node in that tree needs an encoding check.
|
||||
@@ -559,7 +583,7 @@ impl PlanRewriter {
|
||||
// When the root does not encode, the plan holds at least one node that has to stay
|
||||
// on the frontend and only the per-node check locates it.
|
||||
//
|
||||
// For the in-process root `FusedSeries` exception, encodability says nothing about where
|
||||
// For the in-process native root exception, encodability says nothing about where
|
||||
// a node may run, and asking it would cut the plan at the first node with no serializer
|
||||
// branch before `check_plan` could decide. Skipping it only removes a reason to expand: every
|
||||
// check below still runs, and a node they call `NonCommutative`/`Unimplemented`/
|
||||
|
||||
@@ -22,6 +22,7 @@ use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
|
||||
use promql::extension_plan::{
|
||||
EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize,
|
||||
VectorSelect,
|
||||
};
|
||||
use promql::native::plan::reads_across_series;
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
|
||||
@@ -279,6 +280,11 @@ impl Categorizer {
|
||||
// placement is a proof of concept over one region.
|
||||
Commutativity::Commutative
|
||||
}
|
||||
// A ranking answers over the whole vector: it keeps `k` of all the series at a grid
|
||||
// point, so it needs every series at once and one region holds only part of them.
|
||||
// `Unsupported` would expand it just the same, but this node is refused on purpose
|
||||
// rather than because its name is unknown.
|
||||
name if name == VectorSelect::name() => Commutativity::NonCommutative,
|
||||
name if name == SeriesNormalize::name()
|
||||
|| name == InstantManipulate::name()
|
||||
|| name == RangeManipulate::name() =>
|
||||
@@ -532,6 +538,67 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
/// A `VectorSelect` ranking the frames of `raw_input`, bound to the tree the compiler builds for
|
||||
/// `topk(2, some_metric)`.
|
||||
///
|
||||
/// A statement root that ranks instead of folding is planned as this node, which builds the
|
||||
/// per-series prefix it reads over `raw_input`: the root a `topk` statement is planned to is the
|
||||
/// ranking over that prefix over its scan.
|
||||
fn vector_select_plan(raw_input: LogicalPlan) -> LogicalPlan {
|
||||
let mut stmt = native_statement();
|
||||
stmt.expr = parser::parse("topk(2, some_metric)").unwrap();
|
||||
let series_schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
eval_grid: None,
|
||||
});
|
||||
let tree = compile(
|
||||
&stmt,
|
||||
Arc::clone(&series_schema),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
.unwrap();
|
||||
let binding = FusedSeriesBinding {
|
||||
series_schema,
|
||||
grid: statement_grid(&stmt).unwrap(),
|
||||
metric_name: Some(Arc::from("some_metric")),
|
||||
time_index: "ts".to_string(),
|
||||
tags: Vec::new(),
|
||||
};
|
||||
// A ranking answers with its input's own series, so the node's output is the per-series one.
|
||||
let output_schema: DFSchemaRef = Arc::new(
|
||||
DFSchema::new_with_metadata(
|
||||
vec![
|
||||
(
|
||||
None,
|
||||
Arc::new(Field::new("v0", ArrowDataType::Float64, true)),
|
||||
),
|
||||
(
|
||||
None,
|
||||
Arc::new(Field::new(
|
||||
"ts",
|
||||
ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
|
||||
false,
|
||||
)),
|
||||
),
|
||||
],
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(
|
||||
VectorSelect::try_new(
|
||||
Arc::from("topk(2, some_metric)"),
|
||||
tree,
|
||||
binding,
|
||||
raw_input,
|
||||
output_schema,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// The region's own view of the metric's table: a scan whose provider is the region provider.
|
||||
fn table_scan_plan() -> LogicalPlan {
|
||||
let provider = mock_table_provider(RegionId::new(1, 1));
|
||||
@@ -554,6 +621,25 @@ mod tests {
|
||||
plan.inputs().into_iter().any(holds_fused_series)
|
||||
}
|
||||
|
||||
fn holds_vector_select(plan: &LogicalPlan) -> bool {
|
||||
if let LogicalPlan::Extension(extension) = plan
|
||||
&& extension.node.as_any().is::<VectorSelect>()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
plan.inputs().into_iter().any(holds_vector_select)
|
||||
}
|
||||
|
||||
/// The first `FusedSeries` node in `plan`, as the plan node it is.
|
||||
fn first_fused_series(plan: &LogicalPlan) -> Option<&LogicalPlan> {
|
||||
if let LogicalPlan::Extension(extension) = plan
|
||||
&& extension.node.as_any().is::<FusedSeries>()
|
||||
{
|
||||
return Some(plan);
|
||||
}
|
||||
plan.inputs().into_iter().find_map(first_fused_series)
|
||||
}
|
||||
|
||||
/// An extension node with no `ExtensionSerializer` branch: neither one under its own name nor
|
||||
/// one it shares, since the serializer lists names and not shapes. It stands in for the nodes
|
||||
/// that cannot reach a region as bytes for their own reasons, which the encoding gate must keep
|
||||
@@ -804,6 +890,182 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The categorizer refuses the ranking itself: it answers over the whole vector, not per series.
|
||||
#[test]
|
||||
fn vector_select_is_not_commutative_and_its_prefix_still_is() {
|
||||
let plan = vector_select_plan(table_scan_plan());
|
||||
|
||||
// The prefix under the ranking is still one series at a time.
|
||||
let inputs = plan.inputs();
|
||||
let [prefix] = inputs.as_slice() else {
|
||||
panic!("expected the ranking to have one input: {plan}");
|
||||
};
|
||||
assert!(matches!(
|
||||
Categorizer::check_plan(*prefix, None).unwrap(),
|
||||
Commutativity::Commutative
|
||||
));
|
||||
assert!(matches!(
|
||||
Categorizer::check_plan(&plan, None).unwrap(),
|
||||
Commutativity::NonCommutative
|
||||
));
|
||||
}
|
||||
|
||||
/// The ranking stays on the frontend and the prefix under it is what a region builds: the
|
||||
/// region read is the prefix over its own scan, and no part of the ranking is inside it.
|
||||
#[test]
|
||||
fn vector_select_root_keeps_the_ranking_above_the_region_read() {
|
||||
let analyzed = analyze(
|
||||
DistPlannerAnalyzer::new(true),
|
||||
vector_select_plan(table_scan_plan()),
|
||||
);
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
&analyzed,
|
||||
LogicalPlan::Extension(extension) if extension.node.as_any().is::<VectorSelect>()
|
||||
),
|
||||
"the ranking left the frontend although regions are reached in process: {analyzed}"
|
||||
);
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_vector_select),
|
||||
"the analyzer placed the ranking although it answers over the whole vector: {analyzed}"
|
||||
);
|
||||
|
||||
let merge_scan = first_merge_scan(&analyzed)
|
||||
.unwrap_or_else(|| panic!("expected the prefix to be a region read in: {analyzed}"));
|
||||
let prefix = first_fused_series(merge_scan.input()).unwrap_or_else(|| {
|
||||
panic!("expected the region read to be the per-series prefix in: {analyzed}")
|
||||
});
|
||||
let inputs = prefix.inputs();
|
||||
assert_eq!(
|
||||
1,
|
||||
inputs.len(),
|
||||
"expected the prefix to read exactly one input in: {analyzed}"
|
||||
);
|
||||
assert!(
|
||||
matches!(inputs.as_slice(), [LogicalPlan::TableScan(_)]),
|
||||
"expected the prefix to read the series scan itself in: {analyzed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Over the wire the plan is still cut where it stops encoding, which is below both native
|
||||
/// nodes: the region receives the bare scan and nothing of either node.
|
||||
#[test]
|
||||
fn vector_select_root_over_the_wire_places_neither_native_node() {
|
||||
let plan = vector_select_plan(table_scan_plan());
|
||||
// Neither node has a serializer branch, so the plan cannot leave the frontend as bytes.
|
||||
assert!(
|
||||
DFLogicalSubstraitConvertor
|
||||
.encode(&plan, DefaultSerializer)
|
||||
.is_err(),
|
||||
"the native nodes encode now, so the encoding gate decides nothing"
|
||||
);
|
||||
|
||||
let analyzed = analyze(DistPlannerAnalyzer::new(false), plan);
|
||||
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_fused_series),
|
||||
"the analyzer placed the prefix although its plan has to encode: {analyzed}"
|
||||
);
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_vector_select),
|
||||
"the analyzer placed the ranking although its plan has to encode: {analyzed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `EXPLAIN ANALYZE` wraps the rewritten root, and the exception is decided on the plan inside
|
||||
/// it: the same placement, made once.
|
||||
#[test]
|
||||
fn analyze_root_over_a_vector_select_places_the_prefix_the_same_way() {
|
||||
let plan = LogicalPlanBuilder::from(vector_select_plan(table_scan_plan()))
|
||||
.explain(false, true)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(plan, LogicalPlan::Analyze(_)),
|
||||
"expected an analyze root: {plan}"
|
||||
);
|
||||
|
||||
let analyzed = analyze(DistPlannerAnalyzer::new(true), plan);
|
||||
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_vector_select),
|
||||
"the analyzer placed the ranking although it answers over the whole vector: {analyzed}"
|
||||
);
|
||||
let merge_scan = first_merge_scan(&analyzed)
|
||||
.unwrap_or_else(|| panic!("expected the prefix to be a region read in: {analyzed}"));
|
||||
let prefix = first_fused_series(merge_scan.input()).unwrap_or_else(|| {
|
||||
panic!("expected the region read to be the per-series prefix in: {analyzed}")
|
||||
});
|
||||
assert!(
|
||||
matches!(prefix.inputs().as_slice(), [LogicalPlan::TableScan(_)]),
|
||||
"expected the prefix to read the series scan itself in: {analyzed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The exception is the root's own shape, not a search for a native node below it: a plan that
|
||||
/// wraps the prefix in something else keeps the ordinary per-node encoding checks, so the prefix
|
||||
/// stays on the frontend.
|
||||
#[test]
|
||||
fn a_wrapper_around_the_prefix_keeps_the_encoding_gate() {
|
||||
let plan = unserializable_plan(fused_series_plan(table_scan_plan()));
|
||||
assert!(
|
||||
DFLogicalSubstraitConvertor
|
||||
.encode(&plan, DefaultSerializer)
|
||||
.is_err(),
|
||||
"the wrapper and the prefix both have to stay unencodable for this to prove anything"
|
||||
);
|
||||
|
||||
let analyzed = analyze(DistPlannerAnalyzer::new(true), plan);
|
||||
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_fused_series),
|
||||
"the analyzer placed the prefix although its root is not the node itself: {analyzed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A ranking is a native root only over the prefix it builds, and the check reads the node's
|
||||
/// actual child: a ranking over anything else keeps the encoding gate, so the prefix below it
|
||||
/// stays on the frontend even though its own shape would be placeable.
|
||||
#[test]
|
||||
fn a_ranking_over_something_else_keeps_the_encoding_gate() {
|
||||
let ranking = vector_select_plan(table_scan_plan());
|
||||
let inputs = ranking.inputs();
|
||||
let [prefix] = inputs.as_slice() else {
|
||||
panic!("expected the ranking to have one input: {ranking}");
|
||||
};
|
||||
let prefix = *prefix;
|
||||
// The prefix with one projection in between: the same nodes, no longer the shape a region
|
||||
// builds as it was planned.
|
||||
let projected = LogicalPlanBuilder::from(prefix.clone())
|
||||
.project(
|
||||
prefix
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| datafusion_expr::col(field.name()))
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let plan = ranking.with_new_exprs(vec![], vec![projected]).unwrap();
|
||||
assert!(
|
||||
DFLogicalSubstraitConvertor
|
||||
.encode(&plan, DefaultSerializer)
|
||||
.is_err(),
|
||||
"the prefix has to stay unencodable for this to prove anything"
|
||||
);
|
||||
|
||||
let analyzed = analyze(DistPlannerAnalyzer::new(true), plan);
|
||||
|
||||
assert!(
|
||||
!any_remote_input_holds(&analyzed, holds_fused_series),
|
||||
"the analyzer placed the prefix although the ranking does not read it directly: {analyzed}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Skipping the encoding gate removes one reason to expand and adds none: a node that does not
|
||||
/// encode for its own reasons, and that the categorizer refuses, still draws the boundary at
|
||||
/// itself when regions are reached in process.
|
||||
|
||||
@@ -35,11 +35,11 @@ use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as
|
||||
use datafusion::common::{DFSchema, DFSchemaRef};
|
||||
use datafusion::error::DataFusionError;
|
||||
use datafusion::logical_expr::{Extension, LogicalPlan, TableScanBuilder};
|
||||
use datafusion_expr::Expr;
|
||||
use datafusion_expr::{Expr, UserDefinedLogicalNode};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding};
|
||||
use promql::native::plan::reads_across_series;
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, VectorSelect};
|
||||
use promql::native::plan::{BoundVectorOp, NativeExpr, NativeNode, reads_across_series};
|
||||
use promql_parser::parser::value::ValueType;
|
||||
use promql_parser::parser::{
|
||||
EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, VectorSelector,
|
||||
@@ -92,6 +92,9 @@ const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::KeyThenTime;
|
||||
impl PromPlanner {
|
||||
/// Plans `prom_expr` as one [`FusedSeries`] node, or returns `None` to keep the existing plan.
|
||||
///
|
||||
/// A statement whose root is a ranking over a tree that reads one series at a time is planned as
|
||||
/// a [`VectorSelect`] over such a prefix instead; see the whole-vector guard below.
|
||||
///
|
||||
/// The route is offered a whole expression because the compiler folds a range function and the
|
||||
/// math functions over it into one tree: offering a sub-expression instead would compile a tree
|
||||
/// that computes something the reader did not write. Everything else about the node comes from
|
||||
@@ -104,7 +107,8 @@ impl PromPlanner {
|
||||
/// happens are a shape the compiler refuses (`DataFusionError::NotImplemented`, which names
|
||||
/// what it found) and a query this route cannot bind faithfully — more than one selector, a
|
||||
/// label matcher the bare scan below the node would not apply, an `__field__` matcher that
|
||||
/// narrows the field set, a missing table, a native histogram field, or an unusable grid.
|
||||
/// narrows the field set, a missing table, a native histogram field, an unusable grid, or a
|
||||
/// whole-vector root that is not a ranking over a per-series prefix of one `Float64` field.
|
||||
pub(super) async fn try_plan_native_fused(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
@@ -303,7 +307,26 @@ impl PromPlanner {
|
||||
// one executor per scan partition. Declining here is the only place that still works: once
|
||||
// the `FusedSeries` node exists the logical plan is fixed, and the categorizer merely
|
||||
// declining to push it down would leave a node the physical layer must build anyway.
|
||||
if reads_across_series(tree.root()) {
|
||||
//
|
||||
// The one shape whose whole-vector part is only the outermost node — a ranking over a
|
||||
// tree that reads one series at a time — is still offered: each partition evaluates that
|
||||
// prefix on its own series, and the ranking over the gathered series needs the whole
|
||||
// vector. It is admitted only when the resolved input supplies exactly one `Float64`
|
||||
// field, because what a partition hands up names one value per grid position. Everything
|
||||
// else is declined here, before any node of this route exists, so the fallback is the plan
|
||||
// the existing planner would have built without any part of this one.
|
||||
//
|
||||
// The frames are numbered by the producer's local partition index, and every region starts
|
||||
// that numbering at zero, so a ranked statement is admitted only for a table whose DDL
|
||||
// leaves it one region: no partition expression. A partitioned table is declined even when
|
||||
// it happens to hold one region today, because the region list is not part of logical
|
||||
// planning; the per-series route above is unaffected.
|
||||
let ranked = reads_across_series(tree.root());
|
||||
if ranked
|
||||
&& (!ranks_a_per_series_prefix(tree.root())
|
||||
|| !single_float_field(input.schema(), &fields)
|
||||
|| !table_meta.partition_key_indices.is_empty())
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -318,18 +341,35 @@ impl PromPlanner {
|
||||
tags: tags.clone(),
|
||||
};
|
||||
let output_schema = fused_output_schema(&fields, &tags, &time_index)?;
|
||||
let node = FusedSeries::try_new(
|
||||
Arc::from(prom_expr.to_string()),
|
||||
tree,
|
||||
binding,
|
||||
input,
|
||||
output_schema,
|
||||
)
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
let node: Arc<dyn UserDefinedLogicalNode> = if ranked {
|
||||
// A ranking over a per-series prefix: the prefix leaves each partition as evaluated
|
||||
// frames, and the node above them ranks across the gathered series. A shape the node
|
||||
// refuses is this route declining it, exactly as the compiler's `NotImplemented` is.
|
||||
match VectorSelect::try_new(
|
||||
Arc::from(prom_expr.to_string()),
|
||||
tree,
|
||||
binding,
|
||||
input,
|
||||
output_schema,
|
||||
) {
|
||||
Ok(node) => Arc::new(node),
|
||||
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
}
|
||||
} else {
|
||||
Arc::new(
|
||||
FusedSeries::try_new(
|
||||
Arc::from(prom_expr.to_string()),
|
||||
tree,
|
||||
binding,
|
||||
input,
|
||||
output_schema,
|
||||
)
|
||||
.context(DataFusionPlanningSnafu)?,
|
||||
)
|
||||
};
|
||||
|
||||
Ok(Some(LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(node),
|
||||
})))
|
||||
Ok(Some(LogicalPlan::Extension(Extension { node })))
|
||||
}
|
||||
|
||||
/// The statement being planned, rebuilt from the evaluation numbers the planner holds.
|
||||
@@ -397,9 +437,9 @@ fn fused_output_schema(
|
||||
|
||||
/// The one selector `expr` folds, if it names exactly one.
|
||||
///
|
||||
/// The walk follows the grammar the native compiler accepts — a call, a range selector, a selector
|
||||
/// and parentheses — and stops at every other shape, because a shape the compiler cannot compile
|
||||
/// needs no selector resolved. Two distinct selectors are not one input, and a tree built over the
|
||||
/// The walk follows the grammar the native compiler accepts — a call, an aggregate, a range
|
||||
/// selector, a selector and parentheses — and stops at every other shape, because a shape the
|
||||
/// compiler cannot compile needs no selector resolved. Two distinct selectors are not one input, and a tree built over the
|
||||
/// wrong one of them would evaluate a window the query did not write.
|
||||
fn selector_range_millis(expr: &PromExpr) -> Option<i64> {
|
||||
match expr {
|
||||
@@ -410,10 +450,45 @@ fn selector_range_millis(expr: &PromExpr) -> Option<i64> {
|
||||
.args
|
||||
.iter()
|
||||
.find_map(|arg| selector_range_millis(arg)),
|
||||
// A ranking's range is the range of the vector it ranks: `topk(2, rate(x[5m]))` reads the
|
||||
// same five minutes `rate(x[5m])` does, and the scan has to cover it. The parameter is a
|
||||
// constant in every shape that reaches here, and one that carried a selector is not one
|
||||
// input to begin with.
|
||||
PromExpr::Aggregate(aggregate) => selector_range_millis(&aggregate.expr),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` is one ranking over a tree that reads one series at a time.
|
||||
///
|
||||
/// `topk` and `bottomk` are the whole-vector operations that answer with their input's own series
|
||||
/// and values, so they are the only ones that can sit above a per-series prefix. `limitk` and
|
||||
/// `limit_ratio` pick whole series by an input order or a label hash, a `sort` answers with an
|
||||
/// order only an instant result shows, `absent` reads no input at all and `count_values` writes a
|
||||
/// label — those remain whole-vector evaluations the existing planner performs.
|
||||
fn ranks_a_per_series_prefix(node: &NativeNode) -> bool {
|
||||
match &node.expr {
|
||||
NativeExpr::Vector {
|
||||
input,
|
||||
op: BoundVectorOp::TopK { .. },
|
||||
} => !reads_across_series(input),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the resolved input supplies exactly one field and that field is `Float64`.
|
||||
///
|
||||
/// Counting is not enough: the consumer above the prefix carries one float value per grid
|
||||
/// position, so a second field has nowhere to go, and a field of another type is a value the
|
||||
/// frame cannot carry. The type is read off the resolved input the scan was built from, by the
|
||||
/// field names the selector context resolved, rather than assumed from the logical column.
|
||||
fn single_float_field(schema: &DFSchemaRef, fields: &[String]) -> bool {
|
||||
let [only] = fields else {
|
||||
return false;
|
||||
};
|
||||
PromPlanner::field_column_type(schema, only) == Some(&ArrowDataType::Float64)
|
||||
}
|
||||
|
||||
/// Whether `engine` can serve raw series frames to the fused-series node.
|
||||
///
|
||||
/// A whitelist avoids probing a region from logical planning; declining only costs the native route.
|
||||
@@ -475,6 +550,15 @@ fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>)
|
||||
collect_selectors(arg, out);
|
||||
}
|
||||
}
|
||||
// An aggregate names its vector in its second argument, and the parameter a ranking takes
|
||||
// is an expression too: `topk(scalar(x), y)` reads two inputs, so it is counted here
|
||||
// rather than mistaken for one.
|
||||
PromExpr::Aggregate(aggregate) => {
|
||||
if let Some(param) = &aggregate.param {
|
||||
collect_selectors(param, out);
|
||||
}
|
||||
collect_selectors(&aggregate.expr, out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,8 @@ use datafusion::execution::context::SessionContext;
|
||||
use datafusion::logical_expr::{Extension, UserDefinedLogicalNodeCore, col};
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use promql::extension_plan::{FusedSeries, HistogramFold};
|
||||
use promql::extension_plan::{FusedSeries, HistogramFold, VectorSelect};
|
||||
use promql::native::plan::reads_across_series;
|
||||
use promql_parser::label::Labels;
|
||||
use promql_parser::parser;
|
||||
use session::context::QueryContext;
|
||||
@@ -1772,6 +1773,13 @@ fn find_metric_physical_scan(plan: &LogicalPlan) -> Option<datafusion::logical_e
|
||||
.and_then(|fused| match fused.inputs().first() {
|
||||
Some(LogicalPlan::TableScan(scan)) => Some(scan.clone()),
|
||||
_ => None,
|
||||
})
|
||||
// An extension node that is not the per-series one - a `VectorSelect` over one - has
|
||||
// the scan one level further down.
|
||||
.or_else(|| {
|
||||
plan.inputs()
|
||||
.into_iter()
|
||||
.find_map(find_metric_physical_scan)
|
||||
}),
|
||||
_ => plan
|
||||
.inputs()
|
||||
@@ -1780,6 +1788,64 @@ fn find_metric_physical_scan(plan: &LogicalPlan) -> Option<datafusion::logical_e
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-field table on the engine the native route accepts, with both fields `Float64`.
|
||||
async fn two_float_field_provider() -> DfTableSourceProvider {
|
||||
build_test_table_provider_with_options(
|
||||
&[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())],
|
||||
1,
|
||||
2,
|
||||
vec![],
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
ConcreteDataType::float64_datatype(),
|
||||
NATIVE_ENGINE,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Plans `query` and reports the error the planner answered with.
|
||||
///
|
||||
/// A shape the existing planner refuses is one this route has to refuse the same way, so the test
|
||||
/// comparing them reads the answer rather than the plan.
|
||||
async fn build_native_fused_plan_error(
|
||||
query: &str,
|
||||
native_fused: bool,
|
||||
table_provider: DfTableSourceProvider,
|
||||
) -> String {
|
||||
let eval_stmt = build_eval_stmt(query);
|
||||
PromPlanner::stmt_to_plan_with_annotations(
|
||||
table_provider,
|
||||
&eval_stmt,
|
||||
&build_query_engine_state(),
|
||||
None,
|
||||
native_fused,
|
||||
)
|
||||
.await
|
||||
.expect_err("the existing planner refuses a ranking over a multi-value input")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// The scan filters the native route built, as text, so a test can read the bounds it planned.
|
||||
fn native_scan_filters(plan: &LogicalPlan) -> String {
|
||||
let scan = find_metric_physical_scan(plan).expect("the native route keeps the physical scan");
|
||||
|
||||
scan.filters
|
||||
.iter()
|
||||
.map(|filter| format!("{filter:?}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" AND ")
|
||||
}
|
||||
|
||||
fn find_vector_select(plan: &LogicalPlan) -> Option<&VectorSelect> {
|
||||
if let LogicalPlan::Extension(Extension { node }) = plan
|
||||
&& let Some(select) = node.as_any().downcast_ref::<VectorSelect>()
|
||||
{
|
||||
return Some(select);
|
||||
}
|
||||
|
||||
plan.inputs().into_iter().find_map(find_vector_select)
|
||||
}
|
||||
|
||||
fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> {
|
||||
if let LogicalPlan::Extension(Extension { node }) = plan
|
||||
&& let Some(fused) = node.as_any().downcast_ref::<FusedSeries>()
|
||||
@@ -1913,6 +1979,41 @@ async fn native_fused_tag_partitioned_table_still_plans_fused_series() {
|
||||
assert!(plan.display_indent().to_string().contains("FusedSeries"));
|
||||
}
|
||||
|
||||
/// A partitioned table keeps the existing plan for a ranking: the frames are numbered by the
|
||||
/// region-local partition index, so more than one region cannot be told apart. The per-series route
|
||||
/// over the same table is untouched, and the fallback is the whole existing plan.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_declines_a_partitioned_table() {
|
||||
let native = build_native_fused_plan_with_provider(
|
||||
"topk(2, rate(some_metric[5m]))",
|
||||
true,
|
||||
native_engine_provider(vec![0]).await,
|
||||
)
|
||||
.await;
|
||||
let legacy = build_native_fused_plan_with_provider(
|
||||
"topk(2, rate(some_metric[5m]))",
|
||||
false,
|
||||
native_engine_provider(vec![0]).await,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
find_vector_select(&native).is_none(),
|
||||
"{}",
|
||||
native.display_indent()
|
||||
);
|
||||
assert!(
|
||||
find_fused_series(&native).is_none(),
|
||||
"{}",
|
||||
native.display_indent()
|
||||
);
|
||||
assert_eq!(
|
||||
native.display_indent().to_string(),
|
||||
legacy.display_indent().to_string(),
|
||||
"a partitioned table must keep the whole existing plan"
|
||||
);
|
||||
}
|
||||
|
||||
/// Metric logical scans retain their table-id restriction on the direct fused scan input.
|
||||
#[tokio::test]
|
||||
async fn native_fused_metric_engine_table_is_accepted() {
|
||||
@@ -2155,15 +2256,30 @@ async fn native_fused_non_numeric_field_falls_back() {
|
||||
}
|
||||
|
||||
/// A whole-vector operation is not a per-series tree, so it stays on the existing plan.
|
||||
///
|
||||
/// A ranking is the only whole-vector root with a per-series prefix under it, and it needs a
|
||||
/// prefix that reads one series at a time: a `topk` over a fold reads across series at both nodes,
|
||||
/// so no part of it is placed region-side.
|
||||
#[tokio::test]
|
||||
async fn native_fused_whole_vector_operation_falls_back() {
|
||||
for query in ["sort(some_metric)", "absent(some_metric)"] {
|
||||
for query in [
|
||||
"sort(some_metric)",
|
||||
"count_values(\"v\", some_metric)",
|
||||
"limitk(2, some_metric)",
|
||||
"limit_ratio(0.5, some_metric)",
|
||||
"topk(2, sum(rate(some_metric[5m])))",
|
||||
"absent(some_metric)",
|
||||
] {
|
||||
let native = build_native_fused_plan(query, true).await;
|
||||
let without_flag = build_native_fused_plan(query, false).await;
|
||||
assert!(
|
||||
find_fused_series(&native).is_none(),
|
||||
"`{query}` reads the whole vector and must not be placed region-side"
|
||||
);
|
||||
assert!(
|
||||
find_vector_select(&native).is_none(),
|
||||
"`{query}` is not a ranking over a per-series prefix"
|
||||
);
|
||||
assert_eq!(
|
||||
native.display_indent().to_string(),
|
||||
without_flag.display_indent().to_string(),
|
||||
@@ -2231,6 +2347,209 @@ async fn native_fused_anchored_rate_scan_uses_anchor_bounds() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The statement root is one ranking over a per-series prefix.
|
||||
///
|
||||
/// The ranking reads the whole vector at a grid point, so it cannot run inside one scan partition;
|
||||
/// the prefix under it answers one series from one series' rows, so it still can. The plan therefore
|
||||
/// splits exactly there: the root becomes a [`VectorSelect`] and the prefix below it a frame-mode
|
||||
/// `FusedSeries`.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_plans_a_vector_select_over_the_prefix() {
|
||||
let plan = build_native_fused_plan("topk(2, rate(some_metric[5m]))", true).await;
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
&plan,
|
||||
LogicalPlan::Extension(Extension { node }) if node.as_any().is::<VectorSelect>()
|
||||
),
|
||||
"{}",
|
||||
plan.display_indent()
|
||||
);
|
||||
let select = find_vector_select(&plan).expect("the root is planned as a VectorSelect");
|
||||
assert_eq!(1, select.inputs().len());
|
||||
// What the ranking reads is the prefix alone: no part of it reads across series.
|
||||
let prefix = find_fused_series(&plan).expect("the ranking reads a per-series prefix");
|
||||
assert!(
|
||||
!reads_across_series(prefix.tree().root()),
|
||||
"{}",
|
||||
prefix.tree()
|
||||
);
|
||||
// A ranking keeps the input's own fields, so the node's output is the per-series one.
|
||||
assert_eq!(
|
||||
vec!["timestamp", "field_0", "tag_0"],
|
||||
plan.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| field.name().as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// `bottomk` is the other ranking that answers with its input's own series, over a prefix that ends
|
||||
/// in a point-wise map.
|
||||
#[tokio::test]
|
||||
async fn native_fused_bottomk_plans_a_vector_select_over_the_prefix() {
|
||||
let plan = build_native_fused_plan("bottomk(3, abs(rate(some_metric[5m])))", true).await;
|
||||
|
||||
assert!(
|
||||
find_vector_select(&plan).is_some(),
|
||||
"{}",
|
||||
plan.display_indent()
|
||||
);
|
||||
let prefix = find_fused_series(&plan).expect("the ranking reads a per-series prefix");
|
||||
assert!(
|
||||
!reads_across_series(prefix.tree().root()),
|
||||
"{}",
|
||||
prefix.tree()
|
||||
);
|
||||
}
|
||||
|
||||
/// A written grouping is bound inside the ranking, so it neither declines the route nor moves to the
|
||||
/// prefix. The text shown for the node is the statement a reader wrote.
|
||||
#[tokio::test]
|
||||
async fn native_fused_grouped_topk_keeps_the_statement() {
|
||||
let plan = build_native_fused_plan("topk(2, rate(some_metric[5m])) by (tag_0)", true).await;
|
||||
|
||||
assert!(
|
||||
find_vector_select(&plan).is_some(),
|
||||
"{}",
|
||||
plan.display_indent()
|
||||
);
|
||||
let prefix = find_fused_series(&plan).expect("the ranking reads a per-series prefix");
|
||||
assert!(
|
||||
!reads_across_series(prefix.tree().root()),
|
||||
"{}",
|
||||
prefix.tree()
|
||||
);
|
||||
// The node shows the statement as the parser re-renders it, grouping clause included once.
|
||||
let display = plan.display_indent().to_string();
|
||||
assert!(
|
||||
display.contains("VectorSelect: topk by (tag_0) (2, rate(some_metric[5m]))"),
|
||||
"{display}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The flag off: a whole statement keeps the existing plan, whose ranking the existing planner
|
||||
/// performs.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_flag_off_keeps_the_existing_plan() {
|
||||
let plan = build_native_fused_plan("topk(2, rate(some_metric[5m]))", false).await;
|
||||
|
||||
let display = plan.display_indent().to_string();
|
||||
assert!(!display.contains("FusedSeries"), "{display}");
|
||||
assert!(!display.contains("VectorSelect"), "{display}");
|
||||
assert!(display.contains("PromRangeManipulate"), "{display}");
|
||||
}
|
||||
|
||||
/// A ranking carries one value per grid position, so a second field has nowhere to go.
|
||||
///
|
||||
/// The existing planner refuses a ranking over a multi-value input, so falling back means reporting
|
||||
/// the same refusal rather than producing a plan of its own. The per-series route keeps its own
|
||||
/// multi-field support.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_declines_a_second_field() {
|
||||
let native = build_native_fused_plan_error(
|
||||
"topk(2, some_metric)",
|
||||
true,
|
||||
two_float_field_provider().await,
|
||||
)
|
||||
.await;
|
||||
let legacy = build_native_fused_plan_error(
|
||||
"topk(2, some_metric)",
|
||||
false,
|
||||
two_float_field_provider().await,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
native.contains("multi-value input"),
|
||||
"the ranking must keep the refusal the existing planner reports: {native}"
|
||||
);
|
||||
assert_eq!(
|
||||
native, legacy,
|
||||
"a second field must keep the existing planner's answer"
|
||||
);
|
||||
|
||||
let per_series = build_native_fused_plan_with_provider(
|
||||
"rate(some_metric[5m])",
|
||||
true,
|
||||
two_float_field_provider().await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
find_fused_series(&per_series).is_some(),
|
||||
"{}",
|
||||
per_series.display_indent()
|
||||
);
|
||||
}
|
||||
|
||||
/// A field the ranking's frame cannot carry keeps the existing plan even though the raw scan could
|
||||
/// serve it: `Float32` is numeric, and one value per grid position is a `Float64`.
|
||||
///
|
||||
/// A field the scan cannot serve at all - a string, a boolean, a decimal - is refused earlier, by
|
||||
/// the raw-series gate above this one, and `native_fused_non_numeric_field_falls_back` covers it.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_declines_a_non_float64_field() {
|
||||
let field_type = ConcreteDataType::float32_datatype();
|
||||
let native = build_native_fused_plan_with_provider(
|
||||
"topk(2, some_metric)",
|
||||
true,
|
||||
build_test_table_provider_with_field_type(field_type.clone()).await,
|
||||
)
|
||||
.await;
|
||||
let legacy = build_native_fused_plan_with_provider(
|
||||
"topk(2, some_metric)",
|
||||
false,
|
||||
build_test_table_provider_with_field_type(field_type.clone()).await,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
find_fused_series(&native).is_none(),
|
||||
"{field_type} must not reach the native route"
|
||||
);
|
||||
assert!(find_vector_select(&native).is_none(), "{field_type}");
|
||||
assert_eq!(
|
||||
native.display_indent().to_string(),
|
||||
legacy.display_indent().to_string(),
|
||||
"{field_type} must keep the existing plan"
|
||||
);
|
||||
}
|
||||
|
||||
/// The ranking's scan is bounded to the range its own expression reads, not to the statement's
|
||||
/// lookback: a five-minute window under a `topk` reads five minutes of history.
|
||||
#[tokio::test]
|
||||
async fn native_fused_topk_scan_covers_the_inner_range() {
|
||||
for (query, bounds) in [
|
||||
(
|
||||
"topk(2, rate(some_metric[5m]))",
|
||||
(
|
||||
"TimestampMillisecond(-299999, None)",
|
||||
"TimestampMillisecond(100000000, None)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"topk(2, rate(some_metric[5m] offset 10s))",
|
||||
(
|
||||
"TimestampMillisecond(-309999, None)",
|
||||
"TimestampMillisecond(99990000, None)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"topk(2, rate(some_metric[5m] @ 300))",
|
||||
(
|
||||
"TimestampMillisecond(1, None)",
|
||||
"TimestampMillisecond(300000, None)",
|
||||
),
|
||||
),
|
||||
] {
|
||||
let plan = build_native_fused_plan(query, true).await;
|
||||
let filters = native_scan_filters(&plan);
|
||||
assert!(filters.contains(bounds.0), "`{query}`: {filters}");
|
||||
assert!(filters.contains(bounds.1), "`{query}`: {filters}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn single_abs() {
|
||||
do_single_instant_function_call("abs", "abs").await;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -23,14 +24,24 @@ use common_base::Plugins;
|
||||
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
|
||||
use common_query::{Output, OutputData};
|
||||
use common_recordbatch::util::collect_batches;
|
||||
use datafusion::physical_plan::ExecutionPlanProperties;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::physical_expr::PhysicalExpr;
|
||||
use datafusion::physical_plan::sorts::sort::SortExec;
|
||||
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use datafusion::physical_plan::{
|
||||
DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
|
||||
SendableRecordBatchStream,
|
||||
};
|
||||
use datatypes::arrow::array::{
|
||||
Array, Float64Array, Int64Array, StringArray, TimestampMillisecondArray,
|
||||
};
|
||||
use datatypes::arrow::compute::cast;
|
||||
use datatypes::arrow::compute::{SortOptions, cast};
|
||||
use datatypes::arrow::datatypes::DataType;
|
||||
use frontend::instance::Instance;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use query::datafusion::QUERY_PARALLELISM_HINT;
|
||||
use query::dist_plan::MergeScanExec;
|
||||
use query::options::QueryOptions;
|
||||
use query::parser::{PromQuery, QueryLanguageParser, QueryStatement};
|
||||
use query::physical_wrapper::{PhysicalPlanWrapper, PhysicalPlanWrapperRef};
|
||||
@@ -39,6 +50,7 @@ use rstest::rstest;
|
||||
use rstest_reuse::apply;
|
||||
use servers::query_handler::sql::SqlQueryHandler;
|
||||
use session::context::QueryContext;
|
||||
use table::table::scan::SeriesScanExec;
|
||||
|
||||
use super::test_util::{
|
||||
both_instances_cases, check_unordered_output_stream, distributed, standalone,
|
||||
@@ -1760,37 +1772,240 @@ async fn f06_scalar_metric_table_lag_order_by_ts_desc(instance: Arc<dyn MockInst
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct NativePlanObserver(Mutex<Option<Arc<dyn datafusion::physical_plan::ExecutionPlan>>>);
|
||||
struct NativePlanObserver {
|
||||
fused: Mutex<Option<Arc<dyn ExecutionPlan>>>,
|
||||
ranked: Mutex<Option<Arc<dyn ExecutionPlan>>>,
|
||||
gate_fused: bool,
|
||||
gate: Mutex<Option<Arc<PartitionGate>>>,
|
||||
}
|
||||
|
||||
impl NativePlanObserver {
|
||||
fn clear(&self) {
|
||||
*self.0.lock().unwrap() = None;
|
||||
/// An observer that also holds every fused execution partition behind one test barrier.
|
||||
fn with_partition_gate() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
gate_fused: true,
|
||||
..Self::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn take(&self) -> Arc<dyn datafusion::physical_plan::ExecutionPlan> {
|
||||
self.0
|
||||
fn clear(&self) {
|
||||
*self.fused.lock().unwrap() = None;
|
||||
*self.ranked.lock().unwrap() = None;
|
||||
*self.gate.lock().unwrap() = None;
|
||||
}
|
||||
|
||||
fn take(&self) -> Arc<dyn ExecutionPlan> {
|
||||
self.fused
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("native fused plan was captured")
|
||||
}
|
||||
|
||||
fn take_topk(&self) -> Arc<dyn ExecutionPlan> {
|
||||
self.ranked
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("native ranking plan was captured")
|
||||
}
|
||||
|
||||
fn take_gate(&self) -> Arc<PartitionGate> {
|
||||
self.gate
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("the native fused gate was installed")
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicalPlanWrapper for NativePlanObserver {
|
||||
fn wrap(
|
||||
&self,
|
||||
origin: Arc<dyn datafusion::physical_plan::ExecutionPlan>,
|
||||
origin: Arc<dyn ExecutionPlan>,
|
||||
_ctx: session::context::QueryContextRef,
|
||||
) -> Arc<dyn datafusion::physical_plan::ExecutionPlan> {
|
||||
let mut stack = vec![origin.clone()];
|
||||
) -> Arc<dyn ExecutionPlan> {
|
||||
// The gate wraps the real fused node instead of replacing it: the node kept for the metrics
|
||||
// is the execution that computes them, and its own scan child is left untouched.
|
||||
let plan = if self.gate_fused {
|
||||
let gate = Arc::new(PartitionGate::new(4));
|
||||
let (plan, installed) = gate_native_fused(origin, Arc::clone(&gate));
|
||||
if installed {
|
||||
*self.gate.lock().unwrap() = Some(gate);
|
||||
}
|
||||
plan
|
||||
} else {
|
||||
origin
|
||||
};
|
||||
let mut stack = vec![plan.clone()];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.name() == "FusedSeriesExec" {
|
||||
*self.0.lock().unwrap() = Some(node);
|
||||
break;
|
||||
match node.name() {
|
||||
"FusedSeriesExec" => *self.fused.lock().unwrap() = Some(node.clone()),
|
||||
"VectorSelectExec" => *self.ranked.lock().unwrap() = Some(node.clone()),
|
||||
_ => {}
|
||||
}
|
||||
stack.extend(node.children().into_iter().cloned());
|
||||
}
|
||||
origin
|
||||
plan
|
||||
}
|
||||
}
|
||||
|
||||
/// A test barrier shared by the four execution partitions of one fused node.
|
||||
///
|
||||
/// Each partition arrives only after it has computed its own first output batch, so a plan that
|
||||
/// drains its partitions one after another times out instead of passing a count-only assertion.
|
||||
struct PartitionGate {
|
||||
barrier: tokio::sync::Barrier,
|
||||
timeout: Duration,
|
||||
arrived: AtomicUsize,
|
||||
partitions: usize,
|
||||
}
|
||||
|
||||
impl PartitionGate {
|
||||
fn new(partitions: usize) -> Self {
|
||||
Self {
|
||||
barrier: tokio::sync::Barrier::new(partitions),
|
||||
timeout: Duration::from_secs(10),
|
||||
arrived: AtomicUsize::new(0),
|
||||
partitions,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait(&self) -> DataFusionResult<()> {
|
||||
self.arrived.fetch_add(1, AtomicOrdering::SeqCst);
|
||||
match tokio::time::timeout(self.timeout, self.barrier.wait()).await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(DataFusionError::Execution(format!(
|
||||
"only {} of {} native fused partitions produced a first batch concurrently",
|
||||
self.arrived.load(AtomicOrdering::SeqCst),
|
||||
self.partitions
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn arrived(&self) -> usize {
|
||||
self.arrived.load(AtomicOrdering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the fused node with a gated wrapper over it, leaving the rest of the plan alone.
|
||||
fn gate_native_fused(
|
||||
plan: Arc<dyn ExecutionPlan>,
|
||||
gate: Arc<PartitionGate>,
|
||||
) -> (Arc<dyn ExecutionPlan>, bool) {
|
||||
if plan.name() == "FusedSeriesExec" {
|
||||
let gated = Arc::new(NativeFusedGateExec { child: plan, gate }) as Arc<dyn ExecutionPlan>;
|
||||
return (gated, true);
|
||||
}
|
||||
let children = plan.children().into_iter().cloned().collect::<Vec<_>>();
|
||||
if children.is_empty() {
|
||||
return (plan, false);
|
||||
}
|
||||
let mut installed = false;
|
||||
let rewritten = children
|
||||
.iter()
|
||||
.map(|child| {
|
||||
let (child, child_installed) = gate_native_fused(Arc::clone(child), Arc::clone(&gate));
|
||||
installed |= child_installed;
|
||||
child
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !installed {
|
||||
return (plan, false);
|
||||
}
|
||||
(
|
||||
plan.with_new_children(rewritten)
|
||||
.expect("the test gate rebuilds the plan above the fused node"),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
/// The test-only wrapper that holds one real fused partition until every partition has computed a
|
||||
/// first batch.
|
||||
struct NativeFusedGateExec {
|
||||
child: Arc<dyn ExecutionPlan>,
|
||||
gate: Arc<PartitionGate>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NativeFusedGateExec {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NativeFusedGateExec").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayAs for NativeFusedGateExec {
|
||||
fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "NativeFusedGateExec")
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionPlan for NativeFusedGateExec {
|
||||
fn name(&self) -> &str {
|
||||
"NativeFusedGateExec"
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
self.child.properties()
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
|
||||
vec![&self.child]
|
||||
}
|
||||
|
||||
fn apply_expressions(
|
||||
&self,
|
||||
f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
|
||||
) -> DataFusionResult<TreeNodeRecursion> {
|
||||
self.child.apply_expressions(f)
|
||||
}
|
||||
|
||||
fn with_new_children(
|
||||
self: Arc<Self>,
|
||||
children: Vec<Arc<dyn ExecutionPlan>>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
let [child] = <[Arc<dyn ExecutionPlan>; 1]>::try_from(children).map_err(|children| {
|
||||
DataFusionError::Plan(format!(
|
||||
"NativeFusedGateExec requires exactly one child, got {}",
|
||||
children.len()
|
||||
))
|
||||
})?;
|
||||
Ok(Arc::new(Self {
|
||||
child,
|
||||
gate: Arc::clone(&self.gate),
|
||||
}))
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&self,
|
||||
partition: usize,
|
||||
context: Arc<datafusion::execution::TaskContext>,
|
||||
) -> DataFusionResult<SendableRecordBatchStream> {
|
||||
let child = Arc::clone(&self.child);
|
||||
let gate = Arc::clone(&self.gate);
|
||||
let schema = self.child.schema();
|
||||
// The first batch is computed before the barrier: an error or an empty partition is
|
||||
// reported as such and never counts as an arrival.
|
||||
let first_then_rest = futures::stream::once(async move {
|
||||
let mut input = child.execute(partition, context)?;
|
||||
let first = match input.next().await {
|
||||
Some(Ok(batch)) => batch,
|
||||
Some(Err(error)) => return Err(error),
|
||||
None => {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"fused partition {partition} produced no first batch for the test barrier"
|
||||
)));
|
||||
}
|
||||
};
|
||||
gate.wait().await?;
|
||||
Ok::<_, DataFusionError>(
|
||||
futures::stream::iter([Ok::<_, DataFusionError>(first)]).chain(input),
|
||||
)
|
||||
})
|
||||
.try_flatten();
|
||||
Ok(Box::pin(RecordBatchStreamAdapter::new(
|
||||
schema,
|
||||
first_then_rest,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1867,6 +2082,40 @@ async fn native_result_rows(output: Output) -> Vec<(i64, String, f64)> {
|
||||
rows
|
||||
}
|
||||
|
||||
fn native_metric_count(plan: &Arc<dyn ExecutionPlan>, name: &str) -> usize {
|
||||
use datafusion::physical_plan::metrics::MetricValue;
|
||||
|
||||
plan.metrics()
|
||||
.map(|metrics| {
|
||||
metrics
|
||||
.iter()
|
||||
.filter_map(|metric| match metric.value() {
|
||||
MetricValue::Count {
|
||||
name: metric_name,
|
||||
count,
|
||||
} if metric_name.as_ref() == name => Some(count.value()),
|
||||
_ => None,
|
||||
})
|
||||
.sum()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn collect_plan_nodes(plan: Arc<dyn ExecutionPlan>, nodes: &mut Vec<Arc<dyn ExecutionPlan>>) {
|
||||
nodes.push(Arc::clone(&plan));
|
||||
for child in plan.children() {
|
||||
collect_plan_nodes(Arc::clone(child), nodes);
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_plan_node(plan: &Arc<dyn ExecutionPlan>, name: &str) -> bool {
|
||||
plan.name() == name
|
||||
|| plan
|
||||
.children()
|
||||
.into_iter()
|
||||
.any(|child| contains_plan_node(child, name))
|
||||
}
|
||||
|
||||
fn assert_four_native_partitions(plan: &Arc<dyn datafusion::physical_plan::ExecutionPlan>) {
|
||||
use datafusion::physical_plan::metrics::MetricValue;
|
||||
|
||||
@@ -1899,7 +2148,27 @@ async fn native_test_instance(
|
||||
crate::standalone::GreptimeDbStandalone,
|
||||
Arc<NativePlanObserver>,
|
||||
) {
|
||||
let observer = Arc::new(NativePlanObserver::default());
|
||||
native_test_instance_with_observer(builder, Arc::new(NativePlanObserver::default())).await
|
||||
}
|
||||
|
||||
/// The same fixture with a barrier around the real fused node, so its four partitions must all
|
||||
/// compute a first batch before any of them continues.
|
||||
async fn native_test_instance_with_gate(
|
||||
builder: GreptimeDbStandaloneBuilder,
|
||||
) -> (
|
||||
crate::standalone::GreptimeDbStandalone,
|
||||
Arc<NativePlanObserver>,
|
||||
) {
|
||||
native_test_instance_with_observer(builder, NativePlanObserver::with_partition_gate()).await
|
||||
}
|
||||
|
||||
async fn native_test_instance_with_observer(
|
||||
builder: GreptimeDbStandaloneBuilder,
|
||||
observer: Arc<NativePlanObserver>,
|
||||
) -> (
|
||||
crate::standalone::GreptimeDbStandalone,
|
||||
Arc<NativePlanObserver>,
|
||||
) {
|
||||
let plugins = Plugins::new();
|
||||
let wrapper: PhysicalPlanWrapperRef = observer.clone();
|
||||
plugins.insert(wrapper);
|
||||
@@ -2102,3 +2371,346 @@ async fn native_promql_metric_logical_tables_are_isolated() {
|
||||
assert_eq!(native_rows, legacy_rows);
|
||||
}
|
||||
}
|
||||
|
||||
/// A global `topk` must keep the two winners of the whole vector while its prefix still runs as
|
||||
/// four real, non-empty execution partitions of one region.
|
||||
///
|
||||
/// The barrier sits on the fused node's own output: a partition arrives only after it computed its
|
||||
/// first batch, so a plan that drains its partitions one after another fails instead of passing on
|
||||
/// a count. The winners are the independent maxima of all sixteen series, so a per-partition
|
||||
/// ranking or a local maximum cannot produce them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_global_topk_preserves_four_real_prefix_partitions() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let mito_config = mito2::config::MitoConfig {
|
||||
experimental_series_scan_v2: true,
|
||||
..Default::default()
|
||||
};
|
||||
let builder = GreptimeDbStandaloneBuilder::new("native_promql_global_topk_e2e")
|
||||
.with_mito_config(mito_config);
|
||||
let (standalone, observer) = native_test_instance_with_gate(builder).await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
execute_all(
|
||||
&instance,
|
||||
r#"CREATE TABLE native_topk_phy (
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
val DOUBLE
|
||||
) ENGINE=metric WITH ("physical_metric_table" = "true");
|
||||
CREATE TABLE native_topk (
|
||||
host STRING,
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
val DOUBLE,
|
||||
PRIMARY KEY (host)
|
||||
) ENGINE=metric WITH ("on_physical_table" = 'native_topk_phy')"#,
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Sixteen real series, seven samples each: sample `t` holds `scale * t`, so `rate` over any
|
||||
// five-minute window is exactly the series' scale.
|
||||
let mut values = Vec::with_capacity(16 * 7);
|
||||
for scale in 1..=16u32 {
|
||||
for timestamp_sec in [0_i64, 60, 120, 180, 240, 300, 360] {
|
||||
values.push(format!(
|
||||
"('{}', {timestamp_sec}, {})",
|
||||
(b'a' + (scale as u8 - 1)) as char,
|
||||
scale as f64 * timestamp_sec as f64
|
||||
));
|
||||
}
|
||||
}
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"INSERT INTO native_topk (host, ts, val) VALUES {}",
|
||||
values.join(", ")
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let query = PromQuery {
|
||||
query: "topk(2, rate(native_topk[5m]))".to_string(),
|
||||
start: "300".to_string(),
|
||||
end: "360".to_string(),
|
||||
step: "60s".to_string(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
observer.clear();
|
||||
let native = instance
|
||||
.do_promql_query(&query, native_query_context(true, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap();
|
||||
let native_rows = native_result_rows(native).await;
|
||||
|
||||
// The global half: one output partition, an ordered frame input, and no local `fetch k`.
|
||||
let ranked = observer.take_topk();
|
||||
assert_eq!(ranked.name(), "VectorSelectExec");
|
||||
assert_eq!(ranked.output_partitioning().partition_count(), 1);
|
||||
let required = ranked.required_input_ordering();
|
||||
assert_eq!(required.len(), 1);
|
||||
let required = required[0]
|
||||
.as_ref()
|
||||
.expect("the ranking requires an ordered input");
|
||||
// One hard requirement, two keys: producer, then the frame ordinal.
|
||||
let keys = required.first();
|
||||
assert_eq!(keys.len(), 2, "{keys:?}");
|
||||
assert!(keys[0].expr.to_string().contains("producer"), "{}", keys[0]);
|
||||
assert_eq!(
|
||||
keys[0].options,
|
||||
Some(SortOptions {
|
||||
descending: false,
|
||||
nulls_first: false,
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
keys[1].expr.to_string().contains("frame_ordinal"),
|
||||
"{}",
|
||||
keys[1]
|
||||
);
|
||||
assert!(
|
||||
format!("{:?}", ranked.input_distribution_requirements()).contains("SinglePartition"),
|
||||
"{:?}",
|
||||
ranked.input_distribution_requirements()
|
||||
);
|
||||
// The frames reach the ranking as one stream ordered by producer and then ordinal. The
|
||||
// optimizer may keep the single coalesce-and-sort pair or split it into per-partition sorts
|
||||
// merged by a `SortPreservingMergeExec`, so the ordering is read off the child's properties
|
||||
// and every sort in that subtree is checked for a fetch.
|
||||
let ordered = ranked.children()[0].clone();
|
||||
assert_eq!(
|
||||
1,
|
||||
ordered.properties().output_partitioning().partition_count(),
|
||||
"the ranking reads one global ordered stream"
|
||||
);
|
||||
let ordering = ordered
|
||||
.properties()
|
||||
.output_ordering()
|
||||
.unwrap_or_else(|| panic!("the frames reach the ranking ordered: {}", ordered.name()));
|
||||
let keys = ordering
|
||||
.iter()
|
||||
.map(|sort| sort.expr.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(2, keys.len(), "{keys:?}");
|
||||
assert!(keys[0].contains("producer"), "{keys:?}");
|
||||
assert!(keys[1].contains("frame_ordinal"), "{keys:?}");
|
||||
assert!(
|
||||
ordering.iter().all(|sort| sort.options
|
||||
== SortOptions {
|
||||
descending: false,
|
||||
nulls_first: false,
|
||||
}),
|
||||
"{ordering}"
|
||||
);
|
||||
let mut stack = vec![ordered];
|
||||
let mut sorts = 0;
|
||||
while let Some(plan) = stack.pop() {
|
||||
if let Some(sort) = plan.downcast_ref::<SortExec>() {
|
||||
sorts += 1;
|
||||
assert!(
|
||||
sort.fetch().is_none(),
|
||||
"a global ranking must not read a fetch limit"
|
||||
);
|
||||
}
|
||||
stack.extend(plan.children().into_iter().cloned());
|
||||
}
|
||||
assert!(
|
||||
sorts > 0,
|
||||
"the frames are ordered by a sort below the ranking"
|
||||
);
|
||||
let display = datafusion::physical_plan::displayable(ranked.as_ref())
|
||||
.indent(false)
|
||||
.to_string();
|
||||
assert!(
|
||||
display.contains("VectorSelectExec: topk(2, rate(native_topk[5m]))"),
|
||||
"{display}"
|
||||
);
|
||||
assert!(display.contains("root Vector topk 2 by []"), "{display}");
|
||||
assert!(
|
||||
display.contains("input Input evaluated samples, contiguous"),
|
||||
"{display}"
|
||||
);
|
||||
assert!(!display.contains("fetch="), "no local fetch k: {display}");
|
||||
let mut ranked_nodes = Vec::new();
|
||||
collect_plan_nodes(Arc::clone(&ranked), &mut ranked_nodes);
|
||||
assert_eq!(
|
||||
ranked_nodes
|
||||
.iter()
|
||||
.filter(|plan| plan.name() == "VectorSelectExec")
|
||||
.count(),
|
||||
1,
|
||||
"one global ranking node"
|
||||
);
|
||||
assert_eq!(
|
||||
ranked_nodes
|
||||
.iter()
|
||||
.filter(|plan| plan.name() == "FusedSeriesExec")
|
||||
.count(),
|
||||
0,
|
||||
"the region prefix is behind the opaque merge scan"
|
||||
);
|
||||
let merge_scans = ranked_nodes
|
||||
.iter()
|
||||
.filter(|plan| plan.name() == "MergeScanExec")
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(merge_scans.len(), 1, "one region boundary");
|
||||
let merge_scan = merge_scans[0]
|
||||
.downcast_ref::<MergeScanExec>()
|
||||
.expect("the region boundary is a region scan");
|
||||
assert_eq!(
|
||||
merge_scan.regions().len(),
|
||||
1,
|
||||
"the fixture reads exactly one region: {:?}",
|
||||
merge_scan.regions()
|
||||
);
|
||||
assert_eq!(
|
||||
merge_scan.sub_stage_metrics().len(),
|
||||
1,
|
||||
"exactly one region executed: {:?}",
|
||||
merge_scan.regions()
|
||||
);
|
||||
// The global ranking answered the whole vector: it closed exactly the two series it kept, even
|
||||
// though the prefix handed it sixteen.
|
||||
assert_eq!(
|
||||
native_metric_count(&ranked, "native.root.completed_series"),
|
||||
2,
|
||||
"the ranking kept two series out of the sixteen the prefix produced"
|
||||
);
|
||||
|
||||
// The prefix half: the real fused node, four non-empty partitions, over the real series scan
|
||||
// and with nothing coalesced between them.
|
||||
let prefix = observer.take();
|
||||
assert_eq!(prefix.name(), "FusedSeriesExec");
|
||||
assert_four_native_partitions(&prefix);
|
||||
let scan = prefix.children()[0].clone();
|
||||
// The optimizer may wrap the scan in DataFusion's cooperative fairness node, which inherits
|
||||
// its input's partitioning and only changes the scheduling type: the real scan is under it.
|
||||
let mut scan = scan;
|
||||
while scan.name() == "CooperativeExec" {
|
||||
scan = scan.children()[0].clone();
|
||||
}
|
||||
assert_eq!(scan.name(), "SeriesScanExec");
|
||||
assert!(
|
||||
scan.downcast_ref::<SeriesScanExec>().is_some(),
|
||||
"the fused node reads the real series scan"
|
||||
);
|
||||
assert_eq!(scan.output_partitioning().partition_count(), 4);
|
||||
assert!(!contains_plan_node(&prefix, "CoalescePartitionsExec"));
|
||||
let gate = observer.take_gate();
|
||||
assert_eq!(
|
||||
gate.arrived(),
|
||||
4,
|
||||
"all four fused partitions computed a first batch before any continued"
|
||||
);
|
||||
|
||||
// The ranking is checked against the same window ranked by nothing: the whole vector, computed
|
||||
// by the per-series route, ordered by value at each grid point. Taking its own top two is an
|
||||
// answer this node cannot influence, so a per-partition or partial ranking cannot match it.
|
||||
let unranked = PromQuery {
|
||||
query: "rate(native_topk[5m])".to_string(),
|
||||
..query.clone()
|
||||
};
|
||||
let unranked_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(&unranked, native_query_context(true, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let mut hosts = unranked_rows
|
||||
.iter()
|
||||
.map(|(_, host, _)| host.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
hosts.sort_unstable();
|
||||
hosts.dedup();
|
||||
assert_eq!(
|
||||
16,
|
||||
hosts.len(),
|
||||
"the unranked window answers every series, so its top two mean something"
|
||||
);
|
||||
let mut timestamps = unranked_rows
|
||||
.iter()
|
||||
.map(|(timestamp, _, _)| *timestamp)
|
||||
.collect::<Vec<_>>();
|
||||
timestamps.sort_unstable();
|
||||
timestamps.dedup();
|
||||
let mut expected = Vec::new();
|
||||
for timestamp in ×tamps {
|
||||
let mut at_point = unranked_rows
|
||||
.iter()
|
||||
.filter(|(point, _, _)| point == timestamp)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
at_point.sort_by(|left, right| right.2.total_cmp(&left.2).then(left.1.cmp(&right.1)));
|
||||
at_point.truncate(2);
|
||||
expected.extend(at_point);
|
||||
}
|
||||
expected.sort_by(|left, right| (left.0, &left.1).cmp(&(right.0, &right.1)));
|
||||
assert_eq!(
|
||||
native_rows, expected,
|
||||
"the ranking keeps exactly the two largest values of each grid point"
|
||||
);
|
||||
let mut winners = expected
|
||||
.iter()
|
||||
.map(|(_, host, _)| host.clone())
|
||||
.collect::<Vec<_>>();
|
||||
winners.sort_unstable();
|
||||
winners.dedup();
|
||||
assert_eq!(
|
||||
vec!["o".to_string(), "p".to_string()],
|
||||
winners,
|
||||
"the winners are the two largest scales"
|
||||
);
|
||||
|
||||
let legacy_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(&query, native_query_context(false, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(native_rows, expected);
|
||||
assert_eq!(
|
||||
native_rows, legacy_rows,
|
||||
"the native global ranking must answer exactly what the existing planner does"
|
||||
);
|
||||
|
||||
// The executed plans, not a string-only rendering: `ANALYZE` runs the same node tree and the
|
||||
// observer keeps both halves of it, and `EXPLAIN` names the logical ranking over its prefix.
|
||||
observer.clear();
|
||||
let analyze_text = native_output_text(
|
||||
native_tql_output(
|
||||
&instance,
|
||||
"TQL ANALYZE (300, 360, '60s') topk(2, rate(native_topk[5m]))",
|
||||
true,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(analyze_text.contains("VectorSelectExec"), "{analyze_text}");
|
||||
assert!(analyze_text.contains("FusedSeriesExec"), "{analyze_text}");
|
||||
assert_eq!(observer.take_topk().name(), "VectorSelectExec");
|
||||
assert_eq!(observer.take().name(), "FusedSeriesExec");
|
||||
|
||||
observer.clear();
|
||||
let explain_text = native_output_text(
|
||||
native_tql_output(
|
||||
&instance,
|
||||
"TQL EXPLAIN (300, 360, '60s') topk(2, rate(native_topk[5m]))",
|
||||
true,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
explain_text.contains("VectorSelect: topk(2, rate(native_topk[5m]))"),
|
||||
"{explain_text}"
|
||||
);
|
||||
assert!(
|
||||
explain_text.contains("FusedSeries: evaluated frames for topk(2, rate(native_topk[5m]))"),
|
||||
"{explain_text}"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user