mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-29 06:04:06 +00:00
feat(promql): rank unified series frames across parallel prefixes
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -29,6 +29,7 @@ mod series_gather;
|
||||
#[cfg(test)]
|
||||
mod test_util;
|
||||
mod union_distinct_on;
|
||||
mod vector_select;
|
||||
|
||||
pub use absent::{Absent, AbsentExec, AbsentStream};
|
||||
pub use aggregate_finalize::AggregateFinalize;
|
||||
@@ -57,6 +58,7 @@ pub use raw_series_source::{RawSeriesSource, RawSeriesSourceExec};
|
||||
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, VectorSelectExec};
|
||||
|
||||
pub type Millisecond = <TimestampMillisecondType as ArrowPrimitiveType>::Native;
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ use common_query::series_frame::{
|
||||
};
|
||||
use datafusion::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray};
|
||||
use datafusion::arrow::buffer::ScalarBuffer;
|
||||
use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit};
|
||||
use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef, TimeUnit};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::common::DFSchemaRef;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
@@ -179,6 +179,15 @@ pub enum FusedOutputFormat {
|
||||
PlainRows,
|
||||
/// A self-describing evaluated SeriesFrame.
|
||||
SeriesFrame,
|
||||
/// An evaluated SeriesFrame with local producer and frame-row provenance.
|
||||
SeriesFrameWithProvenance,
|
||||
}
|
||||
|
||||
impl FusedOutputFormat {
|
||||
/// Whether this format emits the evaluated frame layout, with or without provenance.
|
||||
fn is_frame(self) -> bool {
|
||||
matches!(self, Self::SeriesFrame | Self::SeriesFrameWithProvenance)
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluated_output(tree: &NativeTree) -> DataFusionResult<Arc<SeriesSchema>> {
|
||||
@@ -196,7 +205,10 @@ fn evaluated_output(tree: &NativeTree) -> DataFusionResult<Arc<SeriesSchema>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn series_frame_output_schema(schema: &SeriesSchema) -> DataFusionResult<SchemaRef> {
|
||||
pub(crate) const NATIVE_PRODUCER_COLUMN: &str = "__greptime_native_producer";
|
||||
pub(crate) const NATIVE_FRAME_ORDINAL_COLUMN: &str = "__greptime_native_frame_ordinal";
|
||||
|
||||
pub(crate) fn series_frame_output_schema(schema: &SeriesSchema) -> DataFusionResult<SchemaRef> {
|
||||
let stream =
|
||||
pack_evaluated_series(Box::pin(futures::stream::empty()), Arc::new(schema.clone()))
|
||||
.map_err(|error| {
|
||||
@@ -205,6 +217,25 @@ fn series_frame_output_schema(schema: &SeriesSchema) -> DataFusionResult<SchemaR
|
||||
Ok(stream.schema())
|
||||
}
|
||||
|
||||
pub(crate) fn provenance_frame_output_schema(schema: &SeriesSchema) -> DataFusionResult<SchemaRef> {
|
||||
let frame = series_frame_output_schema(schema)?;
|
||||
let mut fields = frame.fields().to_vec();
|
||||
fields.push(Arc::new(datafusion::arrow::datatypes::Field::new(
|
||||
NATIVE_PRODUCER_COLUMN,
|
||||
datafusion::arrow::datatypes::DataType::UInt64,
|
||||
false,
|
||||
)));
|
||||
fields.push(Arc::new(datafusion::arrow::datatypes::Field::new(
|
||||
NATIVE_FRAME_ORDINAL_COLUMN,
|
||||
datafusion::arrow::datatypes::DataType::UInt64,
|
||||
false,
|
||||
)));
|
||||
Ok(Arc::new(Schema::new_with_metadata(
|
||||
fields,
|
||||
frame.metadata().clone(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The logical plan of one node that runs a compiled native tree.
|
||||
///
|
||||
/// The node adds nothing to the tree: it records the query the tree was compiled from, so
|
||||
@@ -265,13 +296,18 @@ impl FusedSeries {
|
||||
format: FusedOutputFormat,
|
||||
) -> DataFusionResult<Self> {
|
||||
validate_binding(&tree, &binding, children.len())?;
|
||||
if format == FusedOutputFormat::SeriesFrame && children.len() > 1 {
|
||||
if format.is_frame() && children.len() > 1 {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeries SeriesFrame output does not yet support multiple sources".into(),
|
||||
));
|
||||
}
|
||||
if format == FusedOutputFormat::SeriesFrame {
|
||||
let expected = series_frame_output_schema(evaluated_output(&tree)?.as_ref())?;
|
||||
if format.is_frame() {
|
||||
let evaluated = evaluated_output(&tree)?;
|
||||
let expected = if format == FusedOutputFormat::SeriesFrameWithProvenance {
|
||||
provenance_frame_output_schema(evaluated.as_ref())?
|
||||
} else {
|
||||
series_frame_output_schema(evaluated.as_ref())?
|
||||
};
|
||||
if output_schema.as_arrow() != expected.as_ref() {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeries SeriesFrame output schema does not match the evaluated frame layout"
|
||||
@@ -329,6 +365,11 @@ impl FusedSeries {
|
||||
self.partial_fold.as_ref()
|
||||
}
|
||||
|
||||
/// Whether the node emits evaluated frames with producer provenance.
|
||||
pub fn has_frame_provenance(&self) -> bool {
|
||||
self.format == FusedOutputFormat::SeriesFrameWithProvenance
|
||||
}
|
||||
|
||||
/// The PromQL text this node was compiled from.
|
||||
pub fn promql(&self) -> &str {
|
||||
&self.promql
|
||||
@@ -435,7 +476,8 @@ impl UserDefinedLogicalNodeCore for FusedSeries {
|
||||
self.promql,
|
||||
render_partial_fold(op)
|
||||
),
|
||||
None if self.format == FusedOutputFormat::SeriesFrame => {
|
||||
None if self.format.is_frame() =>
|
||||
{
|
||||
write!(f, "FusedSeries: {} (output: series_frame)", self.promql)
|
||||
}
|
||||
None => write!(f, "FusedSeries: {}", self.promql),
|
||||
@@ -956,7 +998,10 @@ impl FusedSeriesExec {
|
||||
partial_fold: Option<BoundAggregate>,
|
||||
format: FusedOutputFormat,
|
||||
) -> DataFusionResult<Self> {
|
||||
if partial_fold.is_none() && format == FusedOutputFormat::SeriesFrame && inputs.len() > 1 {
|
||||
if partial_fold.is_none()
|
||||
&& format.is_frame()
|
||||
&& inputs.len() > 1
|
||||
{
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeries SeriesFrame output does not yet support multiple sources".into(),
|
||||
));
|
||||
@@ -981,8 +1026,13 @@ impl FusedSeriesExec {
|
||||
"FusedSeries partial fold requires one raw source and a per-series prefix".into(),
|
||||
));
|
||||
}
|
||||
let frame_schema = if partial_fold.is_none() && format == FusedOutputFormat::SeriesFrame {
|
||||
let declared = series_frame_output_schema(evaluated_output(&tree)?.as_ref())?;
|
||||
let frame_schema = if partial_fold.is_none() && format.is_frame() {
|
||||
let evaluated = evaluated_output(&tree)?;
|
||||
let declared = if format == FusedOutputFormat::SeriesFrameWithProvenance {
|
||||
provenance_frame_output_schema(evaluated.as_ref())?
|
||||
} else {
|
||||
series_frame_output_schema(evaluated.as_ref())?
|
||||
};
|
||||
if declared != output_schema {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeriesExec output schema does not match the evaluated frame layout"
|
||||
@@ -1099,7 +1149,7 @@ impl DisplayAs for FusedSeriesExec {
|
||||
write!(f, "FusedSeriesExec: {}\n{}", self.promql, self.tree)?;
|
||||
if let Some(op) = &self.partial_fold {
|
||||
write!(f, "\npartial state: {}", render_partial_fold(op))?;
|
||||
} else if self.format == FusedOutputFormat::SeriesFrame {
|
||||
} else if self.format.is_frame() {
|
||||
write!(f, "\noutput: series_frame")?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1257,8 +1307,12 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
};
|
||||
// A frame is encoded from the tree's own evaluated output, and only when the node answers
|
||||
// values rather than state: partial state is a third output the format does not reach.
|
||||
let frame_mode =
|
||||
self.partial_fold.is_none() && self.format == FusedOutputFormat::SeriesFrame;
|
||||
let frame_mode = self.partial_fold.is_none() && self.format.is_frame();
|
||||
let producer = (self.format == FusedOutputFormat::SeriesFrameWithProvenance).then_some(
|
||||
u64::try_from(partition).map_err(|_| {
|
||||
DataFusionError::Execution("FusedSeries producer partition exceeds UInt64".into())
|
||||
})?,
|
||||
);
|
||||
let stream = FusedSeriesStream {
|
||||
inputs,
|
||||
executor: Some(executor),
|
||||
@@ -1276,7 +1330,20 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
let schema = evaluated_output(&self.tree)?;
|
||||
let source: SendableEvaluatedSeriesStream =
|
||||
Box::pin(FusedEvaluatedStream { source: stream });
|
||||
Ok(pack_evaluated_series(source, schema)?)
|
||||
let packed = pack_evaluated_series(source, schema)?;
|
||||
match producer {
|
||||
// Provenance rides after the packed frame, not inside the evaluator: each
|
||||
// partition numbers the frame rows it hands on, before any downstream gather can
|
||||
// interleave two producers.
|
||||
Some(producer) => Ok(Box::pin(ProvenanceStream {
|
||||
input: packed,
|
||||
producer,
|
||||
next_ordinal: 0,
|
||||
schema: self.output_schema.clone(),
|
||||
done: false,
|
||||
})),
|
||||
None => Ok(packed),
|
||||
}
|
||||
} else {
|
||||
Ok(Box::pin(stream))
|
||||
}
|
||||
@@ -1622,6 +1689,85 @@ impl Stream for FusedSeriesStream {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the local producer and a continuous frame-row ordinal after the shared frame packer.
|
||||
///
|
||||
/// The frame payload itself is untouched: the two helper columns exist only on this process-local
|
||||
/// execution edge, so a producer's rows can be restored after downstream gathering interleaves
|
||||
/// several producers. Ordinals count actual emitted frame rows and continue across batches.
|
||||
struct ProvenanceStream {
|
||||
input: SendableRecordBatchStream,
|
||||
producer: u64,
|
||||
next_ordinal: u64,
|
||||
schema: SchemaRef,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl Stream for ProvenanceStream {
|
||||
type Item = DataFusionResult<RecordBatch>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
if self.done {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
match self.input.as_mut().poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(batch))) => {
|
||||
let rows = batch.num_rows();
|
||||
let count = match u64::try_from(rows) {
|
||||
Ok(count) => count,
|
||||
Err(_) => {
|
||||
self.done = true;
|
||||
return Poll::Ready(Some(Err(DataFusionError::Execution(
|
||||
"frame row count exceeds UInt64".into(),
|
||||
))));
|
||||
}
|
||||
};
|
||||
let end = match self.next_ordinal.checked_add(count) {
|
||||
Some(end) => end,
|
||||
None => {
|
||||
self.done = true;
|
||||
return Poll::Ready(Some(Err(DataFusionError::Execution(
|
||||
"frame ordinal overflow".into(),
|
||||
))));
|
||||
}
|
||||
};
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns.push(Arc::new(datafusion::arrow::array::UInt64Array::from(vec![
|
||||
self.producer;
|
||||
rows
|
||||
])) as ArrayRef);
|
||||
columns.push(Arc::new(
|
||||
datafusion::arrow::array::UInt64Array::from_iter_values(
|
||||
self.next_ordinal..end,
|
||||
),
|
||||
) as ArrayRef);
|
||||
self.next_ordinal = end;
|
||||
match RecordBatch::try_new(self.schema.clone(), columns) {
|
||||
Ok(batch) => Poll::Ready(Some(Ok(batch))),
|
||||
Err(error) => {
|
||||
self.done = true;
|
||||
Poll::Ready(Some(Err(DataFusionError::from(error))))
|
||||
}
|
||||
}
|
||||
}
|
||||
Poll::Ready(Some(Err(error))) => {
|
||||
self.done = true;
|
||||
Poll::Ready(Some(Err(error)))
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
self.done = true;
|
||||
Poll::Ready(None)
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordBatchStream for ProvenanceStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
struct FusedEvaluatedStream {
|
||||
source: FusedSeriesStream,
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ use table::table::scan::{RegionScanExec, SeriesScanExec};
|
||||
use crate::extension_plan::{
|
||||
Absent, AggregateFinalize, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate,
|
||||
RangeManipulate, RawSeriesSource, ScalarCalculate, SeriesDivide, SeriesNormalize,
|
||||
UnionDistinctOn,
|
||||
UnionDistinctOn, VectorSelect,
|
||||
};
|
||||
|
||||
pub struct PromExtensionPlanner;
|
||||
@@ -85,6 +85,14 @@ impl ExtensionPlanner for PromExtensionPlanner {
|
||||
session.config_options().execution.target_partitions,
|
||||
)
|
||||
.map(Some)
|
||||
} else if let Some(node) = node.as_any().downcast_ref::<VectorSelect>() {
|
||||
let [input] = physical_inputs else {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"the VectorSelect node takes exactly one input, but {} were planned",
|
||||
physical_inputs.len()
|
||||
)));
|
||||
};
|
||||
node.to_execution_plan(Arc::clone(input)).map(Some)
|
||||
} else if let Some(node) = node.as_any().downcast_ref::<AggregateFinalize>() {
|
||||
// The merge runs where every partition's state arrives, so its own input is the plan
|
||||
// that exports them.
|
||||
|
||||
@@ -0,0 +1,916 @@
|
||||
// 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.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt::{self, Formatter};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
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::{ExecutionPlanMetricsSet, 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::fused_series::{
|
||||
FusedOutputFormat, FusedSeries, FusedSeriesBinding, NATIVE_FRAME_ORDINAL_COLUMN,
|
||||
NATIVE_PRODUCER_COLUMN, OutputColumn, classify_output, series_frame_output_schema,
|
||||
series_to_record_batch,
|
||||
};
|
||||
use crate::grid_series::{fields_bytes, series_bytes};
|
||||
use crate::native::execute::{Emitted, InputId, NativeExecutionState, NativeExecutor};
|
||||
use crate::native::plan::{
|
||||
BoundInput, BoundVectorOp, NativeExpr, NativeNode, NativeTree, reads_across_series,
|
||||
};
|
||||
use datafusion::arrow::array::UInt64Array;
|
||||
use datatypes::series::frame::{FrameLabelMode, SeriesFrameDecoder};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// 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_tree = NativeTree::try_new(child.as_ref().clone())?;
|
||||
let prefix_schema = crate::extension_plan::fused_series::provenance_frame_output_schema(
|
||||
child_schema.as_ref(),
|
||||
)?;
|
||||
let prefix = FusedSeries::try_new_with_format(
|
||||
Arc::clone(&promql),
|
||||
prefix_tree,
|
||||
binding,
|
||||
vec![raw_input],
|
||||
Arc::new(datafusion::common::DFSchema::try_from(prefix_schema)?),
|
||||
FusedOutputFormat::SeriesFrameWithProvenance,
|
||||
)?;
|
||||
// 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(),
|
||||
source_index: 0,
|
||||
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 = |name: &str, 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()
|
||||
))
|
||||
})?;
|
||||
if field.name() != name {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"expected provenance column {name}, found {}",
|
||||
field.name()
|
||||
)));
|
||||
}
|
||||
Ok(Arc::new(Column::new(field.name(), index)))
|
||||
};
|
||||
LexOrdering::new([
|
||||
PhysicalSortExpr::new(
|
||||
column(NATIVE_PRODUCER_COLUMN, schema.fields().len() - 2)?,
|
||||
ASCENDING,
|
||||
),
|
||||
PhysicalSortExpr::new(
|
||||
column(NATIVE_FRAME_ORDINAL_COLUMN, schema.fields().len() - 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>,
|
||||
/// 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,
|
||||
tags: Arc<[String]>,
|
||||
classification: Arc<[OutputColumn]>,
|
||||
/// The ordering the frames arrive in, which is also what this node requires.
|
||||
ordering: LexOrdering,
|
||||
/// The counters every execution of the suffix registered, retained so the plan reports them
|
||||
/// after that execution is gone.
|
||||
///
|
||||
/// The set is synchronised by DataFusion itself, so it needs no lock of this node's own.
|
||||
metrics: ExecutionPlanMetricsSet,
|
||||
/// 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> {
|
||||
let tagged_schema = input.schema();
|
||||
let provenance_schema =
|
||||
crate::extension_plan::fused_series::provenance_frame_output_schema(
|
||||
series_schema.as_ref(),
|
||||
)?;
|
||||
if tagged_schema != provenance_schema {
|
||||
return Err(DataFusionError::Plan(
|
||||
"VectorSelectExec reads tagged evaluated frames, but its input schema is incompatible".into(),
|
||||
));
|
||||
}
|
||||
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 producer = Arc::new(Column::new(
|
||||
NATIVE_PRODUCER_COLUMN,
|
||||
input.schema().fields().len() - 2,
|
||||
));
|
||||
let ordinal = Arc::new(Column::new(
|
||||
NATIVE_FRAME_ORDINAL_COLUMN,
|
||||
input.schema().fields().len() - 1,
|
||||
));
|
||||
let ordering = LexOrdering::new([
|
||||
PhysicalSortExpr::new(producer, ASCENDING),
|
||||
PhysicalSortExpr::new(ordinal, ASCENDING),
|
||||
])
|
||||
.ok_or_else(|| DataFusionError::Plan("the provenance frame ordering is empty".into()))?;
|
||||
let classification =
|
||||
classify_output(&output_schema, &series_schema.fields, &tags, &time_column)?;
|
||||
// Building a throwaway state proves the runtime executes this tree.
|
||||
let _ = NativeExecutionState::try_new(&suffix, Arc::new(UnboundedMemoryPool::default()))?;
|
||||
// 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,
|
||||
tags: tags.into(),
|
||||
classification: classification.into(),
|
||||
time_column,
|
||||
output_schema,
|
||||
ordering,
|
||||
metrics: ExecutionPlanMetricsSet::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 belongs to this execution and is released as the stream finishes.
|
||||
let input = self.input.execute(partition, Arc::clone(&context))?;
|
||||
let state = NativeExecutionState::try_new(
|
||||
&self.suffix,
|
||||
Arc::clone(&context.runtime_env().memory_pool),
|
||||
)?;
|
||||
// The counters are the plan's rather than the stream's: the execution registers them once,
|
||||
// and the plan keeps reporting them after that execution is dropped.
|
||||
state.register_metrics(&self.metrics, partition);
|
||||
// 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,
|
||||
decoded_batch: None,
|
||||
frame_schema: series_frame_output_schema(self.series_schema.as_ref())?,
|
||||
held_batch_bytes: 0,
|
||||
producer: None,
|
||||
next_ordinal: 0,
|
||||
previous_closed: true,
|
||||
emitted: Emitted::new(),
|
||||
occupancy: MemoryConsumer::new("VectorSelectExec occupied positions")
|
||||
.register(&context.runtime_env().memory_pool),
|
||||
decoder: Some(
|
||||
SeriesFrameDecoder::try_new(&self.series_schema, FrameLabelMode::Explicit, None)
|
||||
.map_err(|e| DataFusionError::Plan(e.to_string()))?,
|
||||
),
|
||||
executor: Some(NativeExecutor::new(state)),
|
||||
input_id: InputId::new(0),
|
||||
series_schema: Some(Arc::clone(&self.series_schema)),
|
||||
output_schema: self.output_schema.clone(),
|
||||
classification: Arc::clone(&self.classification),
|
||||
tags: Arc::clone(&self.tags),
|
||||
frames,
|
||||
draining: false,
|
||||
done: false,
|
||||
}))
|
||||
}
|
||||
|
||||
fn metrics(&self) -> Option<MetricsSet> {
|
||||
// The set holds the executions' counter handles, so reading it again hands back the same
|
||||
// entries and registers nothing.
|
||||
Some(self.metrics.clone_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 current frame batch with provenance columns removed, decoded schema and original batch retained.
|
||||
decoded_batch: Option<RecordBatch>,
|
||||
frame_schema: SchemaRef,
|
||||
/// Bytes charged for the current Arrow batch and transient decoded row.
|
||||
held_batch_bytes: usize,
|
||||
/// Last producer and next required ordinal.
|
||||
producer: Option<u64>,
|
||||
emitted: Emitted,
|
||||
occupancy: MemoryReservation,
|
||||
next_ordinal: u64,
|
||||
previous_closed: bool,
|
||||
/// Decoder for the declared evaluated frame schema.
|
||||
decoder: Option<SeriesFrameDecoder>,
|
||||
/// 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 retained while frames remain to be decoded.
|
||||
series_schema: Option<Arc<SeriesSchema>>,
|
||||
/// The schema of every batch this stream yields.
|
||||
output_schema: SchemaRef,
|
||||
classification: Arc<[OutputColumn]>,
|
||||
tags: Arc<[String]>,
|
||||
/// 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.held_batch_bytes = batch.get_array_memory_size();
|
||||
self.frames.try_resize(self.held_batch_bytes)?;
|
||||
let count = batch.num_columns() - 2;
|
||||
self.decoded_batch = Some(RecordBatch::try_new(
|
||||
self.frame_schema.clone(),
|
||||
batch.columns()[..count].to_vec(),
|
||||
)?);
|
||||
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.decoded_batch = None;
|
||||
self.row = 0;
|
||||
self.held_batch_bytes = 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(),
|
||||
));
|
||||
};
|
||||
if self.series_schema.is_none() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"VectorSelectExec read a frame after it gave up its series schema".to_string(),
|
||||
));
|
||||
}
|
||||
let producer = batch
|
||||
.column(batch.num_columns() - 2)
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.ok_or_else(|| DataFusionError::Execution("invalid producer provenance".into()))?
|
||||
.value(row);
|
||||
let ordinal = batch
|
||||
.column(batch.num_columns() - 1)
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.ok_or_else(|| DataFusionError::Execution("invalid ordinal provenance".into()))?
|
||||
.value(row);
|
||||
if self.producer != Some(producer) {
|
||||
if self.producer.is_some() && !self.previous_closed {
|
||||
return Err(DataFusionError::Execution(
|
||||
"producer changed before its final series frame".into(),
|
||||
));
|
||||
}
|
||||
self.producer = Some(producer);
|
||||
self.next_ordinal = 0;
|
||||
}
|
||||
if ordinal != self.next_ordinal {
|
||||
return Err(DataFusionError::Execution(
|
||||
"invalid producer/frame ordinal sequence".into(),
|
||||
));
|
||||
}
|
||||
self.next_ordinal = self
|
||||
.next_ordinal
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| DataFusionError::Execution("frame ordinal overflow".into()))?;
|
||||
let frame = self
|
||||
.decoded_batch
|
||||
.as_ref()
|
||||
.ok_or_else(|| DataFusionError::Execution("decoded frame payload is missing".into()))?
|
||||
.slice(row, 1);
|
||||
let decoder = self.decoder.as_mut().ok_or_else(|| {
|
||||
DataFusionError::Execution(
|
||||
"VectorSelectExec decoded after releasing its decoder".into(),
|
||||
)
|
||||
})?;
|
||||
let decoded = match decoder.decode_evaluated(&frame) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
self.frames.try_resize(self.held_batch_bytes)?;
|
||||
return Err(DataFusionError::Execution(error.to_string()));
|
||||
}
|
||||
};
|
||||
let (series, is_last) = decoded.into_iter().next().ok_or_else(|| {
|
||||
DataFusionError::Execution("VectorSelect frame row is missing".into())
|
||||
})?;
|
||||
self.previous_closed = is_last;
|
||||
let row_bytes = series_bytes(&series)
|
||||
.saturating_sub(fields_bytes(&series.fields))
|
||||
.saturating_add(
|
||||
series
|
||||
.time
|
||||
.runs()
|
||||
.count()
|
||||
.saturating_mul(std::mem::size_of::<usize>()),
|
||||
);
|
||||
self.frames
|
||||
.try_resize(self.held_batch_bytes.saturating_add(row_bytes))?;
|
||||
let evaluated = crate::evaluated::EvaluatedChunk::try_new(series, is_last)?;
|
||||
self.emitted.check_and_occupy(&evaluated)?;
|
||||
self.occupancy.try_resize(self.emitted.bytes())?;
|
||||
self.frames.try_resize(self.held_batch_bytes)?;
|
||||
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, evaluated)?;
|
||||
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<()> {
|
||||
if let Some(executor) = self.executor.as_mut() {
|
||||
executor.end_of_input()?;
|
||||
}
|
||||
self.emitted = Emitted::new();
|
||||
self.occupancy.try_resize(0)?;
|
||||
self.series_schema = None;
|
||||
self.decoder = 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);
|
||||
};
|
||||
let evaluated = crate::evaluated::EvaluatedChunk::try_new(chunk.series, chunk.is_last)?;
|
||||
let batch = series_to_record_batch(
|
||||
&self.classification,
|
||||
&self.tags,
|
||||
&self.output_schema,
|
||||
&evaluated,
|
||||
)?;
|
||||
Ok(Some(batch))
|
||||
}
|
||||
|
||||
/// Ends the stream in an error, releasing the execution, the held frame and the input at once.
|
||||
///
|
||||
/// The label-set map belongs to this stream and is released with it.
|
||||
fn fail(&mut self) {
|
||||
self.done = true;
|
||||
self.executor = None;
|
||||
self.input = None;
|
||||
self.series_schema = None;
|
||||
self.decoder = None;
|
||||
self.emitted = Emitted::new();
|
||||
let _ = self.occupancy.try_resize(0);
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
// 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.
|
||||
|
||||
use super::*;
|
||||
use datafusion::arrow::array::{Float64Array, UInt64Array};
|
||||
use datafusion::arrow::datatypes::{DataType, Field, TimeUnit};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
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::{GreedyMemoryPool, 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, collect,
|
||||
};
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, SeriesLabels, SeriesOrdering};
|
||||
use futures::StreamExt;
|
||||
use std::fmt::Formatter;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use crate::native::plan::{
|
||||
BoundInput, BoundVectorOp, Grouping, NativeExpr, NativeNode, NativeTree, NativeType,
|
||||
};
|
||||
|
||||
const GRID_START: i64 = 300_000;
|
||||
const GRID_STEP: i64 = 60_000;
|
||||
const GRID_LEN: usize = 8;
|
||||
const TIME: &str = "time";
|
||||
const VALUE: &str = "value";
|
||||
const HOST: &str = "host";
|
||||
const NAME: &str = "__name__";
|
||||
const METRIC: &str = "requests";
|
||||
|
||||
fn grid() -> Arc<EvalGrid> {
|
||||
Arc::new(
|
||||
EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP, GRID_LEN as u64).unwrap())
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
fn schema(raw: bool) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: VALUE.into() }]),
|
||||
eval_grid: (!raw).then(grid),
|
||||
})
|
||||
}
|
||||
fn output_schema() -> SchemaRef {
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new(VALUE, DataType::Float64, true),
|
||||
Field::new(HOST, DataType::Utf8, true),
|
||||
Field::new(NAME, DataType::Utf8, true),
|
||||
Field::new(
|
||||
TIME,
|
||||
DataType::Timestamp(TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
]))
|
||||
}
|
||||
fn memory_exec(parts: Vec<Vec<RecordBatch>>) -> Arc<dyn ExecutionPlan> {
|
||||
Arc::new(DataSourceExec::new(Arc::new(
|
||||
MemorySourceConfig::try_new(
|
||||
&parts,
|
||||
crate::extension_plan::fused_series::provenance_frame_output_schema(&schema(false))
|
||||
.unwrap(),
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
)))
|
||||
}
|
||||
fn chunk(
|
||||
host: &str,
|
||||
values: &[Option<f64>],
|
||||
start: usize,
|
||||
last: bool,
|
||||
) -> crate::evaluated::EvaluatedChunk {
|
||||
let axis = TimeAxis::from_grid_spans(grid(), vec![GridSpan::new(start, values.len())]).unwrap();
|
||||
let series = Series {
|
||||
metric: SeriesLabels::try_new(
|
||||
Some(Arc::from(METRIC)),
|
||||
vec![Label {
|
||||
name: Arc::from(HOST),
|
||||
value: Arc::from(host),
|
||||
}],
|
||||
)
|
||||
.unwrap(),
|
||||
time: axis,
|
||||
fields: SeriesFields::one(Samples::from_float(Float64Array::from(values.to_vec()))),
|
||||
};
|
||||
crate::evaluated::EvaluatedChunk::try_new(series, last).unwrap()
|
||||
}
|
||||
fn frame_chunk(c: crate::evaluated::EvaluatedChunk, producer: u64, ordinal: u64) -> RecordBatch {
|
||||
let is_last = c.is_last;
|
||||
let close_host = c.series.metric.get(HOST).unwrap().to_string();
|
||||
let items = if is_last {
|
||||
vec![Ok::<_, common_error::ext::BoxedError>((c.series, true))]
|
||||
} else {
|
||||
let close = chunk(&close_host, &[], 0, true);
|
||||
vec![
|
||||
Ok::<_, common_error::ext::BoxedError>((c.series, false)),
|
||||
Ok((close.series, true)),
|
||||
]
|
||||
};
|
||||
let mut stream = common_query::series_frame::pack_evaluated_series(
|
||||
Box::pin(futures::stream::iter(items)),
|
||||
schema(false),
|
||||
)
|
||||
.unwrap();
|
||||
let batch = futures::executor::block_on(stream.next()).unwrap().unwrap();
|
||||
let batch = if is_last { batch } else { batch.slice(0, 1) };
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns.push(Arc::new(UInt64Array::from(vec![producer])));
|
||||
columns.push(Arc::new(UInt64Array::from(vec![ordinal])));
|
||||
RecordBatch::try_new(
|
||||
crate::extension_plan::fused_series::provenance_frame_output_schema(&schema(false))
|
||||
.unwrap(),
|
||||
columns,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn frame(host: &str, value: f64, producer: u64, ordinal: u64) -> RecordBatch {
|
||||
frame_chunk(
|
||||
chunk(host, &[Some(value); GRID_LEN], 0, true),
|
||||
producer,
|
||||
ordinal,
|
||||
)
|
||||
}
|
||||
fn suffix() -> NativeTree {
|
||||
let input = NativeType::Samples(schema(false));
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Vector {
|
||||
input: Box::new(NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: input.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
output: input.clone(),
|
||||
}),
|
||||
op: BoundVectorOp::TopK {
|
||||
k: 2.0,
|
||||
top: true,
|
||||
group: Grouping::By(Arc::from([])),
|
||||
},
|
||||
},
|
||||
output: input,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
fn exec_with_input(input: Arc<dyn ExecutionPlan>) -> VectorSelectExec {
|
||||
VectorSelectExec::try_new(
|
||||
Arc::from("topk(2, x)"),
|
||||
input,
|
||||
Arc::new(suffix()),
|
||||
schema(false),
|
||||
output_schema(),
|
||||
TIME.into(),
|
||||
vec![HOST.into(), NAME.into()],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn exec(frames: Vec<RecordBatch>) -> VectorSelectExec {
|
||||
exec_with_input(memory_exec(vec![frames]))
|
||||
}
|
||||
|
||||
struct TestInput {
|
||||
schema: SchemaRef,
|
||||
batch: Option<RecordBatch>,
|
||||
error_after: bool,
|
||||
dropped: Arc<AtomicBool>,
|
||||
props: Arc<PlanProperties>,
|
||||
}
|
||||
impl std::fmt::Debug for TestInput {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TestInput").finish()
|
||||
}
|
||||
}
|
||||
impl DisplayAs for TestInput {
|
||||
fn fmt_as(&self, _: DisplayFormatType, _: &mut Formatter) -> std::fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl ExecutionPlan for TestInput {
|
||||
fn name(&self) -> &str {
|
||||
"TestInput"
|
||||
}
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
&self.props
|
||||
}
|
||||
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
|
||||
vec![]
|
||||
}
|
||||
fn apply_expressions(
|
||||
&self,
|
||||
_: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
|
||||
) -> DataFusionResult<TreeNodeRecursion> {
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
}
|
||||
fn execute(
|
||||
&self,
|
||||
_: usize,
|
||||
_: Arc<TaskContext>,
|
||||
) -> DataFusionResult<SendableRecordBatchStream> {
|
||||
Ok(Box::pin(TestInputStream {
|
||||
schema: self.schema.clone(),
|
||||
batch: self.batch.clone(),
|
||||
error_after: self.error_after,
|
||||
dropped: Arc::clone(&self.dropped),
|
||||
}))
|
||||
}
|
||||
fn with_new_children(
|
||||
self: Arc<Self>,
|
||||
_: Vec<Arc<dyn ExecutionPlan>>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
struct TestInputStream {
|
||||
schema: SchemaRef,
|
||||
batch: Option<RecordBatch>,
|
||||
error_after: bool,
|
||||
dropped: Arc<AtomicBool>,
|
||||
}
|
||||
impl RecordBatchStream for TestInputStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
impl futures::Stream for TestInputStream {
|
||||
type Item = DataFusionResult<RecordBatch>;
|
||||
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
if let Some(batch) = self.batch.take() {
|
||||
return Poll::Ready(Some(Ok(batch)));
|
||||
}
|
||||
if std::mem::replace(&mut self.error_after, false) {
|
||||
return Poll::Ready(Some(Err(DataFusionError::Execution(
|
||||
"upstream test failure".into(),
|
||||
))));
|
||||
}
|
||||
Poll::Ready(None)
|
||||
}
|
||||
}
|
||||
impl Drop for TestInputStream {
|
||||
fn drop(&mut self) {
|
||||
self.dropped.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
fn test_input(
|
||||
batch: Option<RecordBatch>,
|
||||
error_after: bool,
|
||||
) -> (Arc<dyn ExecutionPlan>, Arc<AtomicBool>) {
|
||||
let schema =
|
||||
crate::extension_plan::fused_series::provenance_frame_output_schema(&schema(false))
|
||||
.unwrap();
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let props = Arc::new(PlanProperties::new(
|
||||
EquivalenceProperties::new(schema.clone()),
|
||||
Partitioning::UnknownPartitioning(1),
|
||||
EmissionType::Incremental,
|
||||
Boundedness::Bounded,
|
||||
));
|
||||
(
|
||||
Arc::new(TestInput {
|
||||
schema,
|
||||
batch,
|
||||
error_after,
|
||||
dropped: Arc::clone(&dropped),
|
||||
props,
|
||||
}),
|
||||
dropped,
|
||||
)
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum RejectAllocation {
|
||||
Frames,
|
||||
Occupancy,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct ControlledPool {
|
||||
inner: GreedyMemoryPool,
|
||||
reject: RejectAllocation,
|
||||
accepted_frames: AtomicBool,
|
||||
}
|
||||
impl std::fmt::Display for ControlledPool {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "ControlledPool")
|
||||
}
|
||||
}
|
||||
impl MemoryPool for ControlledPool {
|
||||
fn name(&self) -> &str {
|
||||
"controlled vector-select pool"
|
||||
}
|
||||
fn register(&self, consumer: &datafusion::execution::memory_pool::MemoryConsumer) {
|
||||
self.inner.register(consumer);
|
||||
}
|
||||
fn unregister(&self, consumer: &datafusion::execution::memory_pool::MemoryConsumer) {
|
||||
self.inner.unregister(consumer);
|
||||
}
|
||||
fn grow(
|
||||
&self,
|
||||
reservation: &datafusion::execution::memory_pool::MemoryReservation,
|
||||
additional: usize,
|
||||
) {
|
||||
self.inner.grow(reservation, additional);
|
||||
}
|
||||
fn shrink(
|
||||
&self,
|
||||
reservation: &datafusion::execution::memory_pool::MemoryReservation,
|
||||
shrink: usize,
|
||||
) {
|
||||
self.inner.shrink(reservation, shrink);
|
||||
}
|
||||
fn try_grow(
|
||||
&self,
|
||||
reservation: &datafusion::execution::memory_pool::MemoryReservation,
|
||||
additional: usize,
|
||||
) -> DataFusionResult<()> {
|
||||
let name = reservation.consumer().name();
|
||||
let is_frames = name.contains("VectorSelectExec frames");
|
||||
let is_occupancy = name.contains("VectorSelectExec occupied positions");
|
||||
let initial_frame_allocation = is_frames && reservation.size() == 0 && additional > 0;
|
||||
let reject = match self.reject {
|
||||
RejectAllocation::Frames => is_frames && reservation.size() > 0 && additional > 0,
|
||||
RejectAllocation::Occupancy => is_occupancy && additional > 0,
|
||||
};
|
||||
if reject {
|
||||
return Err(DataFusionError::ResourcesExhausted(format!(
|
||||
"controlled allocation rejection: {name}"
|
||||
)));
|
||||
}
|
||||
let result = self.inner.try_grow(reservation, additional);
|
||||
if result.is_ok() && initial_frame_allocation {
|
||||
self.accepted_frames.store(true, Ordering::SeqCst);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn reserved(&self) -> usize {
|
||||
self.inner.reserved()
|
||||
}
|
||||
fn memory_limit(&self) -> datafusion::execution::memory_pool::MemoryLimit {
|
||||
self.inner.memory_limit()
|
||||
}
|
||||
}
|
||||
fn controlled_pool(reject: RejectAllocation) -> Arc<ControlledPool> {
|
||||
Arc::new(ControlledPool {
|
||||
inner: GreedyMemoryPool::new(1 << 20),
|
||||
reject,
|
||||
accepted_frames: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
fn context(pool: Arc<dyn MemoryPool>) -> Arc<TaskContext> {
|
||||
let runtime = RuntimeEnvBuilder::new()
|
||||
.with_memory_pool(pool)
|
||||
.build()
|
||||
.unwrap();
|
||||
Arc::new(TaskContext::default().with_runtime(Arc::new(runtime)))
|
||||
}
|
||||
async fn next(stream: &mut SendableRecordBatchStream) -> Option<DataFusionResult<RecordBatch>> {
|
||||
futures::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn topk_overlap_is_rejected_before_ranking() {
|
||||
let error = collect(
|
||||
Arc::new(exec(vec![
|
||||
frame("same", 10.0, 0, 0),
|
||||
frame("same", 9.0, 1, 0),
|
||||
])),
|
||||
SessionContext::default().task_ctx(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("both hold a value"), "{error}");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn topk_loser_collision_is_rejected_but_control_is_valid() {
|
||||
// The colliding pair ranks below both distinct winners. Collision validation must therefore
|
||||
// cover losers too, rather than only the candidates retained by topk.
|
||||
let error = collect(
|
||||
Arc::new(exec(vec![
|
||||
frame("winner-a", 100.0, 0, 0),
|
||||
frame("winner-b", 90.0, 1, 0),
|
||||
frame("same-loser", 2.0, 2, 0),
|
||||
frame("same-loser", 1.0, 3, 0),
|
||||
])),
|
||||
SessionContext::default().task_ctx(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("both hold a value"), "{error}");
|
||||
|
||||
let control = collect(
|
||||
Arc::new(exec(vec![
|
||||
frame("winner-a", 100.0, 0, 0),
|
||||
frame("winner-b", 90.0, 1, 0),
|
||||
frame("loser-a", 2.0, 2, 0),
|
||||
frame("loser-b", 1.0, 3, 0),
|
||||
])),
|
||||
SessionContext::default().task_ctx(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
2 * GRID_LEN,
|
||||
control.iter().map(RecordBatch::num_rows).sum::<usize>()
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn disjoint_fragments_and_null_samples_are_valid() {
|
||||
let first = frame_chunk(chunk("same", &[Some(10.0), None], 0, true), 0, 0);
|
||||
let second = frame_chunk(chunk("same", &[Some(1.0), Some(2.0)], 2, true), 1, 0);
|
||||
let batches = collect(
|
||||
Arc::new(exec(vec![first, second])),
|
||||
SessionContext::default().task_ctx(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(3, batches.iter().map(RecordBatch::num_rows).sum::<usize>());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn malformed_ordinal_unfinished_producer_and_upstream_error_end_once() {
|
||||
for (batches, expected) in [
|
||||
(
|
||||
vec![frame("a", 1.0, 0, 0), frame("b", 2.0, 0, 2)],
|
||||
"ordinal",
|
||||
),
|
||||
(
|
||||
vec![
|
||||
frame_chunk(chunk("a", &[Some(1.0)], 0, false), 0, 0),
|
||||
frame("b", 2.0, 1, 0),
|
||||
],
|
||||
"producer",
|
||||
),
|
||||
] {
|
||||
// Keep the rows in one input partition so producer/ordinal sequence is checked directly.
|
||||
let input = memory_exec(vec![batches]);
|
||||
let mut stream = exec_with_input(input)
|
||||
.execute(0, SessionContext::default().task_ctx())
|
||||
.unwrap();
|
||||
let error = next(&mut stream).await.unwrap().unwrap_err();
|
||||
assert!(error.to_string().contains(expected), "{error}");
|
||||
assert!(next(&mut stream).await.is_none());
|
||||
}
|
||||
let (input, dropped) = test_input(Some(frame("a", 1.0, 0, 0)), true);
|
||||
let mut stream = exec_with_input(input)
|
||||
.execute(0, SessionContext::default().task_ctx())
|
||||
.unwrap();
|
||||
let error = next(&mut stream).await.unwrap().unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("upstream test failure"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(next(&mut stream).await.is_none());
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn targeted_allocation_failures_release_resources() {
|
||||
for reject in [RejectAllocation::Frames, RejectAllocation::Occupancy] {
|
||||
let plan = exec(vec![frame("a", 1.0, 0, 0)]);
|
||||
let pool = controlled_pool(reject);
|
||||
let mut stream = plan
|
||||
.execute(0, context(Arc::clone(&pool) as Arc<dyn MemoryPool>))
|
||||
.unwrap();
|
||||
let error = next(&mut stream).await.unwrap().unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("controlled allocation rejection"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(next(&mut stream).await.is_none());
|
||||
if matches!(reject, RejectAllocation::Frames) {
|
||||
assert!(pool.accepted_frames.load(Ordering::SeqCst));
|
||||
}
|
||||
assert_eq!(0, pool.reserved());
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn constrained_pool_error_releases_reservations() {
|
||||
let plan = exec(vec![frame("a", 1.0, 0, 0)]);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(1));
|
||||
let mut stream = plan
|
||||
.execute(0, context(Arc::clone(&pool) as Arc<dyn MemoryPool>))
|
||||
.unwrap();
|
||||
let error = next(&mut stream).await.unwrap().unwrap_err();
|
||||
assert!(
|
||||
error.to_string().to_lowercase().contains("memory"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(next(&mut stream).await.is_none());
|
||||
drop(stream);
|
||||
assert_eq!(0, pool.reserved());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn cancellation_after_feed_releases_occupancy_and_upstream() {
|
||||
let batch = frame("a", 1.0, 0, 0);
|
||||
let (input, dropped) = test_input(None, false);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
|
||||
let task_ctx = context(Arc::clone(&pool) as Arc<dyn MemoryPool>);
|
||||
let suffix = Arc::new(suffix());
|
||||
let state =
|
||||
NativeExecutionState::try_new(&suffix, Arc::clone(&pool) as Arc<dyn MemoryPool>).unwrap();
|
||||
let mut stream = VectorSelectStream {
|
||||
input: Some(input.execute(0, task_ctx).unwrap()),
|
||||
batch: None,
|
||||
row: 0,
|
||||
decoded_batch: None,
|
||||
frame_schema: crate::extension_plan::fused_series::series_frame_output_schema(&schema(
|
||||
false,
|
||||
))
|
||||
.unwrap(),
|
||||
held_batch_bytes: 0,
|
||||
producer: None,
|
||||
next_ordinal: 0,
|
||||
previous_closed: true,
|
||||
emitted: Emitted::new(),
|
||||
occupancy: datafusion::execution::memory_pool::MemoryConsumer::new(
|
||||
"VectorSelectExec occupied positions",
|
||||
)
|
||||
.register(&(pool.clone() as Arc<dyn MemoryPool>)),
|
||||
decoder: Some(
|
||||
datatypes::series::frame::SeriesFrameDecoder::try_new(
|
||||
&schema(false),
|
||||
FrameLabelMode::Explicit,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
executor: Some(NativeExecutor::new(state)),
|
||||
input_id: InputId::new(0),
|
||||
series_schema: Some(schema(false)),
|
||||
output_schema: output_schema(),
|
||||
classification: Arc::from([]),
|
||||
tags: Arc::from([]),
|
||||
frames: datafusion::execution::memory_pool::MemoryConsumer::new("VectorSelectExec frames")
|
||||
.register(&(pool.clone() as Arc<dyn MemoryPool>)),
|
||||
draining: false,
|
||||
done: false,
|
||||
};
|
||||
stream.hold(batch).unwrap();
|
||||
stream.feed(0).unwrap();
|
||||
assert!(stream.occupancy.size() > 0, "feed established occupancy");
|
||||
assert!(pool.reserved() > 0);
|
||||
assert!(
|
||||
!dropped.load(Ordering::SeqCst),
|
||||
"input remains attached before cancellation"
|
||||
);
|
||||
drop(stream);
|
||||
assert!(
|
||||
dropped.load(Ordering::SeqCst),
|
||||
"dropping the stream releases upstream"
|
||||
);
|
||||
assert_eq!(0, pool.reserved(), "cancellation releases all reservations");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn eof_releases_decoder_and_drop_releases_pool() {
|
||||
let (input, _) = test_input(Some(frame("a", 1.0, 0, 0)), false);
|
||||
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
|
||||
let task_ctx = context(Arc::clone(&pool) as Arc<dyn MemoryPool>);
|
||||
let suffix = Arc::new(suffix());
|
||||
let state =
|
||||
NativeExecutionState::try_new(&suffix, Arc::clone(&pool) as Arc<dyn MemoryPool>).unwrap();
|
||||
let mut ended = VectorSelectStream {
|
||||
input: Some(input.execute(0, Arc::clone(&task_ctx)).unwrap()),
|
||||
batch: None,
|
||||
row: 0,
|
||||
decoded_batch: None,
|
||||
frame_schema: crate::extension_plan::fused_series::series_frame_output_schema(&schema(
|
||||
false,
|
||||
))
|
||||
.unwrap(),
|
||||
held_batch_bytes: 0,
|
||||
producer: None,
|
||||
next_ordinal: 0,
|
||||
previous_closed: true,
|
||||
emitted: Emitted::new(),
|
||||
occupancy: datafusion::execution::memory_pool::MemoryConsumer::new(
|
||||
"VectorSelectExec occupied positions",
|
||||
)
|
||||
.register(&(pool.clone() as Arc<dyn MemoryPool>)),
|
||||
decoder: Some(
|
||||
datatypes::series::frame::SeriesFrameDecoder::try_new(
|
||||
&schema(false),
|
||||
FrameLabelMode::Explicit,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
executor: Some(NativeExecutor::new(state)),
|
||||
input_id: InputId::new(0),
|
||||
series_schema: Some(schema(false)),
|
||||
output_schema: output_schema(),
|
||||
classification: Arc::from([
|
||||
OutputColumn::Field(0),
|
||||
OutputColumn::Tag(0),
|
||||
OutputColumn::Tag(1),
|
||||
OutputColumn::Time,
|
||||
]),
|
||||
tags: Arc::from([HOST.to_string(), NAME.to_string()]),
|
||||
frames: datafusion::execution::memory_pool::MemoryConsumer::new("VectorSelectExec frames")
|
||||
.register(&(pool.clone() as Arc<dyn MemoryPool>)),
|
||||
draining: false,
|
||||
done: false,
|
||||
};
|
||||
while let Some(item) = futures::future::poll_fn(|cx| Pin::new(&mut ended).poll_next(cx)).await {
|
||||
item.unwrap();
|
||||
}
|
||||
assert_eq!(0, pool.reserved(), "EOF releases execution reservations");
|
||||
assert!(ended.done);
|
||||
assert!(ended.decoder.is_none());
|
||||
assert!(ended.series_schema.is_none());
|
||||
assert!(ended.executor.is_none());
|
||||
assert!(ended.input.is_none());
|
||||
assert!(ended.batch.is_none());
|
||||
assert!(ended.decoded_batch.is_none());
|
||||
drop(ended);
|
||||
assert_eq!(0, pool.reserved());
|
||||
|
||||
let (input, dropped) = test_input(Some(frame("a", 1.0, 0, 0)), false);
|
||||
let stream = exec_with_input(input)
|
||||
.execute(0, SessionContext::default().task_ctx())
|
||||
.unwrap();
|
||||
drop(stream);
|
||||
assert!(
|
||||
dropped.load(Ordering::SeqCst),
|
||||
"dropping the stream releases upstream"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn provenance_ordering_uses_producer_then_row_ordinal() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("payload", DataType::Utf8, true),
|
||||
Field::new(NATIVE_PRODUCER_COLUMN, DataType::UInt64, false),
|
||||
Field::new(NATIVE_FRAME_ORDINAL_COLUMN, DataType::UInt64, false),
|
||||
]));
|
||||
let ordering = frame_ordering(&schema).unwrap();
|
||||
assert_eq!(2, ordering.len());
|
||||
assert!(
|
||||
ordering[0]
|
||||
.expr
|
||||
.to_string()
|
||||
.starts_with(NATIVE_PRODUCER_COLUMN)
|
||||
);
|
||||
assert!(
|
||||
ordering[1]
|
||||
.expr
|
||||
.to_string()
|
||||
.starts_with(NATIVE_FRAME_ORDINAL_COLUMN)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn producer_ordinal_sort_rejects_wrong_helper_columns() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("wrong", DataType::UInt64, false),
|
||||
Field::new(NATIVE_FRAME_ORDINAL_COLUMN, DataType::UInt64, false),
|
||||
]));
|
||||
assert!(frame_ordering(&schema).is_err());
|
||||
}
|
||||
@@ -508,7 +508,7 @@ impl NodeBuffer {
|
||||
/// the node below kept, so a label set costs its bytes again in every node that keeps a table, and
|
||||
/// what is deduplicated here is one node's history rather than a plan's.
|
||||
#[derive(Default)]
|
||||
struct Emitted {
|
||||
pub(crate) struct Emitted {
|
||||
sets: HashMap<LabelSet, History>,
|
||||
/// How many run vectors, runs and label payload bytes every entry holds, counted as the entries
|
||||
/// change rather than by walking them.
|
||||
@@ -563,6 +563,16 @@ fn metric_bytes(metric: &SeriesLabels) -> usize {
|
||||
}
|
||||
|
||||
impl Emitted {
|
||||
/// Creates a label-set occupancy table for global vector results.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Checks and records occupancy for one output chunk.
|
||||
pub(crate) fn check_and_occupy(&mut self, chunk: &EvaluatedChunk) -> Result<()> {
|
||||
self.occupy(chunk)
|
||||
}
|
||||
|
||||
/// Records what `chunk` occupies, rejecting it against what this node already handed out.
|
||||
///
|
||||
/// A second series onto a label set is legal when it holds its values where the first one held
|
||||
@@ -630,7 +640,7 @@ impl Emitted {
|
||||
/// running total, so the figure is read in constant time however many series the node has
|
||||
/// handed out; it leaves out the map's buckets, the slack of a vector's capacity and the `Arc`
|
||||
/// headers of the strings it shares, so it is an approximation rather than a measurement.
|
||||
fn bytes(&self) -> usize {
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
let slots =
|
||||
self.sets.len() * (std::mem::size_of::<LabelSet>() + std::mem::size_of::<History>());
|
||||
slots
|
||||
|
||||
@@ -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::{AggregateFinalize, FusedSeries, SeriesDivide};
|
||||
use promql::extension_plan::{AggregateFinalize, FusedSeries, SeriesDivide, VectorSelect};
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
use table::metadata::TableType;
|
||||
use table::table::adapter::DfTableProviderAdapter;
|
||||
@@ -590,6 +590,11 @@ fn is_in_process_plan(plan: &LogicalPlan) -> bool {
|
||||
if is_fused_series_plan(plan) {
|
||||
return true;
|
||||
}
|
||||
if let LogicalPlan::Extension(extension) = plan
|
||||
&& extension.node.as_any().is::<VectorSelect>()
|
||||
{
|
||||
return matches!(extension.node.inputs().as_slice(), [LogicalPlan::Extension(prefix)] if prefix.node.as_any().downcast_ref::<FusedSeries>().is_some_and(FusedSeries::has_frame_provenance) && matches!(prefix.node.inputs().as_slice(), [LogicalPlan::TableScan(_)]));
|
||||
}
|
||||
let LogicalPlan::Extension(extension) = plan else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -22,7 +22,7 @@ use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
|
||||
use promql::extension_plan::{
|
||||
AggregateFinalize, EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate,
|
||||
RawSeriesSource, SeriesDivide, SeriesNormalize,
|
||||
RawSeriesSource, SeriesDivide, SeriesNormalize, VectorSelect,
|
||||
};
|
||||
use promql::native::plan::reads_across_series;
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
|
||||
@@ -282,7 +282,9 @@ impl Categorizer {
|
||||
}
|
||||
// The merge reads every partition's state, so it cannot run in one of them: a region
|
||||
// would merge the state its own scan produced and report that as the whole group.
|
||||
name if name == AggregateFinalize::name() => Commutativity::NonCommutative,
|
||||
name if name == AggregateFinalize::name() || name == VectorSelect::name() => {
|
||||
Commutativity::NonCommutative
|
||||
}
|
||||
name if name == SeriesNormalize::name()
|
||||
|| name == InstantManipulate::name()
|
||||
|| name == RangeManipulate::name() =>
|
||||
|
||||
@@ -36,6 +36,7 @@ use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
use catalog::kvbackend::KvBackendCatalogManager;
|
||||
use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE, MITO2_ENGINE};
|
||||
use common_query::prelude::OTLP_AGGREGATION_TEMPORALITY_LABEL;
|
||||
use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit};
|
||||
@@ -46,8 +47,10 @@ use datafusion::prelude::Expr as DfExpr;
|
||||
use datafusion_expr::Expr;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::extension_plan::{AggregateFinalize, FusedSeries, FusedSeriesBinding, RawSeriesSource};
|
||||
use promql::native::plan::{NativeExpr, NativeNode, reads_across_series};
|
||||
use promql::extension_plan::{
|
||||
AggregateFinalize, FusedSeries, FusedSeriesBinding, RawSeriesSource, VectorSelect,
|
||||
};
|
||||
use promql::native::plan::{BoundVectorOp, NativeExpr, NativeNode, reads_across_series};
|
||||
use promql::vector_match::{Cardinality, MatchingLabels, SetOp};
|
||||
use promql_parser::label::Matchers;
|
||||
use promql_parser::parser::value::ValueType;
|
||||
@@ -583,8 +586,88 @@ impl PromPlanner {
|
||||
// several, are answered per partition. Aggregate splits are restricted to one raw scan
|
||||
// child.
|
||||
let root = compiled.tree.root();
|
||||
let ranked = matches!(
|
||||
&root.expr,
|
||||
NativeExpr::Vector {
|
||||
op: BoundVectorOp::TopK { .. },
|
||||
..
|
||||
}
|
||||
);
|
||||
let ranked_fields = series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.name.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
if ranked {
|
||||
let Some(scan) = children.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let LogicalPlan::TableScan(scan) = scan else {
|
||||
return Ok(None);
|
||||
};
|
||||
let table = self.table_from_source(&scan.source)?;
|
||||
if selectors.len() != 1
|
||||
|| !matches!(&root.expr, NativeExpr::Vector { op: BoundVectorOp::TopK { .. }, input } if !reads_across_series(input))
|
||||
|| series_schema.fields.len() != 1
|
||||
|| Self::field_column_type(
|
||||
children[0].schema(),
|
||||
ranked_fields
|
||||
.first()
|
||||
.map(String::as_str)
|
||||
.unwrap_or_default(),
|
||||
) != Some(&ArrowDataType::Float64)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let (table_id, Some(manager)) = (
|
||||
table.table_info().table_id(),
|
||||
query_engine_state
|
||||
.catalog_manager()
|
||||
.as_any()
|
||||
.downcast_ref::<KvBackendCatalogManager>(),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let route = match manager
|
||||
.partition_manager()
|
||||
.find_physical_table_route_with_id(table_id)
|
||||
.await
|
||||
{
|
||||
Ok((_, route)) if route.region_routes.len() == 1 => route,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let _ = route;
|
||||
}
|
||||
let per_partition =
|
||||
!reads_across_series(root) || pointwise_operand(root) || independent_scan_pair(root);
|
||||
!ranked && (!reads_across_series(root) || pointwise_operand(root) || independent_scan_pair(root));
|
||||
if ranked {
|
||||
let output_schema = fused_output_schema(&ranked_fields, &tags, &time)?;
|
||||
let Some(raw_input) = children.into_iter().next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let node = match VectorSelect::try_new(
|
||||
Arc::from(prom_expr.to_string()),
|
||||
compiled.tree,
|
||||
FusedSeriesBinding {
|
||||
grid,
|
||||
time_index: time,
|
||||
tags,
|
||||
metric_name: metric,
|
||||
},
|
||||
raw_input,
|
||||
output_schema,
|
||||
) {
|
||||
Ok(node) => node,
|
||||
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
return Ok(Some((
|
||||
LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(node),
|
||||
}),
|
||||
single_input_context,
|
||||
)));
|
||||
}
|
||||
if !per_partition {
|
||||
if selectors.len() != 1
|
||||
|| !AggregateFinalize::can_split(&compiled.tree, &series_schema.fields, &time)
|
||||
|
||||
@@ -17,6 +17,7 @@ use std::fmt;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crate::dist_plan::MergeScanExec;
|
||||
use async_trait::async_trait;
|
||||
use catalog::CatalogManagerRef;
|
||||
use common_base::Plugins;
|
||||
@@ -42,6 +43,9 @@ use datafusion::physical_optimizer::PhysicalOptimizerRule;
|
||||
use datafusion::physical_optimizer::optimizer::PhysicalOptimizer;
|
||||
use datafusion::physical_optimizer::sanity_checker::SanityCheckPlan;
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
|
||||
use datafusion::physical_plan::coop::CooperativeExec;
|
||||
use datafusion::physical_plan::sorts::sort::SortExec;
|
||||
use datafusion::physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner};
|
||||
use datafusion_expr::{AggregateUDF, LogicalPlan as DfLogicalPlan, WindowUDF};
|
||||
use datafusion_optimizer::Analyzer;
|
||||
@@ -49,6 +53,7 @@ use datafusion_optimizer::analyzer::function_rewrite::ApplyFunctionRewrites;
|
||||
use datafusion_optimizer::optimizer::Optimizer;
|
||||
use partition::manager::PartitionRuleManagerRef;
|
||||
use promql::extension_plan::PromExtensionPlanner;
|
||||
use promql::extension_plan::VectorSelectExec;
|
||||
use session::context::QueryContextRef;
|
||||
use table::TableRef;
|
||||
use table::table::adapter::DfTableProviderAdapter;
|
||||
@@ -562,12 +567,68 @@ impl QueryPlanner for DfQueryPlanner {
|
||||
logical_plan: &DfLogicalPlan,
|
||||
session: &dyn Session,
|
||||
) -> DfResult<Arc<dyn ExecutionPlan>> {
|
||||
self.physical_planner
|
||||
let plan = self
|
||||
.physical_planner
|
||||
.create_physical_plan(logical_plan, session)
|
||||
.await
|
||||
.await?;
|
||||
validate_vector_select_regions(&plan)?;
|
||||
Ok(plan)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_vector_select_regions(plan: &Arc<dyn ExecutionPlan>) -> DfResult<()> {
|
||||
if let Some(select) = plan.as_ref().downcast_ref::<VectorSelectExec>() {
|
||||
let select_children = select.children();
|
||||
let [input] = select_children.as_slice() else {
|
||||
return Err(datafusion::error::DataFusionError::Plan(
|
||||
"VectorSelectExec has unexpected children".into(),
|
||||
));
|
||||
};
|
||||
let mut child = *input;
|
||||
if let Some(sort) = child.as_ref().downcast_ref::<SortExec>() {
|
||||
let sort_children = sort.children();
|
||||
let [next] = sort_children.as_slice() else {
|
||||
return Err(datafusion::error::DataFusionError::Plan(
|
||||
"VectorSelect sort has unexpected children".into(),
|
||||
));
|
||||
};
|
||||
child = *next;
|
||||
}
|
||||
if let Some(coalesce) = child.as_ref().downcast_ref::<CoalescePartitionsExec>() {
|
||||
let coalesce_children = coalesce.children();
|
||||
let [next] = coalesce_children.as_slice() else {
|
||||
return Err(datafusion::error::DataFusionError::Plan(
|
||||
"VectorSelect coalesce has unexpected children".into(),
|
||||
));
|
||||
};
|
||||
child = *next;
|
||||
}
|
||||
if let Some(cooperative) = child.as_ref().downcast_ref::<CooperativeExec>() {
|
||||
child = cooperative.input();
|
||||
}
|
||||
let merge = child
|
||||
.as_ref()
|
||||
.downcast_ref::<MergeScanExec>()
|
||||
.ok_or_else(|| {
|
||||
datafusion::error::DataFusionError::Plan(format!(
|
||||
"VectorSelect expected a one-region MergeScanExec, found child {}. Physical subtree:\\n{}",
|
||||
child.name(),
|
||||
datafusion::physical_plan::displayable(select).indent(true)
|
||||
))
|
||||
})?;
|
||||
if merge.region_count() != 1 {
|
||||
return Err(datafusion::error::DataFusionError::Plan(format!(
|
||||
"native global topk requires one physical region, got {}",
|
||||
merge.region_count()
|
||||
)));
|
||||
}
|
||||
}
|
||||
for child in plan.children() {
|
||||
validate_vector_select_regions(child)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// MySQL-compatible scalar function aliases: (target_name, alias)
|
||||
const SCALAR_FUNCTION_ALIASES: &[(&str, &str)] = &[
|
||||
("upper", "ucase"),
|
||||
@@ -740,14 +801,37 @@ impl MemoryPool for MetricsMemoryPool {
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::dist_plan::MergeScanExec;
|
||||
use crate::region_query::{RegionQueryHandler, RegionQueryTarget};
|
||||
use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate};
|
||||
use async_trait::async_trait;
|
||||
use common_base::Plugins;
|
||||
use common_base::memory_limit::MemoryLimit;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_query::request::QueryRequest;
|
||||
use common_query::series_frame::pack_evaluated_series;
|
||||
use common_recordbatch::SendableRecordBatchStream;
|
||||
use datafusion::arrow::datatypes::{
|
||||
DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema, TimeUnit,
|
||||
};
|
||||
use datafusion::error::DataFusionError;
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryLimit as DfMemoryLimit};
|
||||
use datafusion::execution::runtime_env::{RuntimeEnv, RuntimeEnvBuilder};
|
||||
use datafusion::logical_expr::LogicalPlanBuilder;
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datafusion_common::config::SpillCompression;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
use promql::extension_plan::VectorSelectExec;
|
||||
use promql::native::plan::{
|
||||
BoundInput, BoundVectorOp, Grouping, NativeExpr, NativeNode, NativeTree, NativeType,
|
||||
};
|
||||
use session::ReadPreference;
|
||||
use session::context::QueryContext;
|
||||
use store_api::storage::RegionId;
|
||||
use table::table_name::TableName;
|
||||
|
||||
use super::*;
|
||||
use crate::options::{QueryOptions, QuerySpillCompression, QuerySpillMode};
|
||||
@@ -756,6 +840,199 @@ mod tests {
|
||||
QueryRuntimeProviderRef,
|
||||
};
|
||||
|
||||
struct UnusedRegionQueryHandler;
|
||||
#[async_trait]
|
||||
impl RegionQueryHandler for UnusedRegionQueryHandler {
|
||||
async fn select_target(
|
||||
&self,
|
||||
_: ReadPreference,
|
||||
_: RegionId,
|
||||
) -> crate::error::Result<RegionQueryTarget> {
|
||||
unreachable!("region guard test does not execute")
|
||||
}
|
||||
async fn do_get(
|
||||
&self,
|
||||
_: &RegionQueryTarget,
|
||||
_: QueryRequest,
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
unreachable!("region guard test does not execute")
|
||||
}
|
||||
async fn handle_remote_dyn_filter_update(
|
||||
&self,
|
||||
_: &RegionQueryTarget,
|
||||
_: String,
|
||||
_: RemoteDynFilterUpdate,
|
||||
) -> crate::error::Result<()> {
|
||||
unreachable!("region guard test does not execute")
|
||||
}
|
||||
async fn handle_remote_dyn_filter_unregister(
|
||||
&self,
|
||||
_: &RegionQueryTarget,
|
||||
_: String,
|
||||
_: RemoteDynFilterUnregister,
|
||||
) -> crate::error::Result<()> {
|
||||
unreachable!("region guard test does not execute")
|
||||
}
|
||||
}
|
||||
|
||||
fn vector_select_for_region_count(region_count: u32) -> Arc<dyn ExecutionPlan> {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 2).unwrap()).unwrap());
|
||||
let series_schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec {
|
||||
name: Arc::from("value"),
|
||||
}]),
|
||||
eval_grid: Some(Arc::clone(&grid)),
|
||||
});
|
||||
let input_type = NativeType::Samples(Arc::clone(&series_schema));
|
||||
let suffix = NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Vector {
|
||||
input: Box::new(NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: input_type.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
output: input_type.clone(),
|
||||
}),
|
||||
op: BoundVectorOp::TopK {
|
||||
k: 1.0,
|
||||
top: true,
|
||||
group: Grouping::By(Arc::from([])),
|
||||
},
|
||||
},
|
||||
output: input_type,
|
||||
})
|
||||
.unwrap();
|
||||
let packed = pack_evaluated_series(
|
||||
Box::pin(futures::stream::empty()),
|
||||
Arc::clone(&series_schema),
|
||||
)
|
||||
.unwrap();
|
||||
let payload_schema = packed.schema();
|
||||
let tagged_schema = Arc::new(ArrowSchema::new_with_metadata(
|
||||
payload_schema
|
||||
.fields()
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain([
|
||||
Arc::new(ArrowField::new(
|
||||
"__greptime_native_producer",
|
||||
ArrowDataType::UInt64,
|
||||
false,
|
||||
)),
|
||||
Arc::new(ArrowField::new(
|
||||
"__greptime_native_frame_ordinal",
|
||||
ArrowDataType::UInt64,
|
||||
false,
|
||||
)),
|
||||
])
|
||||
.collect::<Vec<_>>(),
|
||||
payload_schema.metadata().clone(),
|
||||
));
|
||||
let raw_plan = LogicalPlanBuilder::empty(true)
|
||||
.project(
|
||||
tagged_schema
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let null = match field.data_type() {
|
||||
ArrowDataType::Boolean => datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::Boolean(None),
|
||||
),
|
||||
ArrowDataType::UInt64 => datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::UInt64(Some(0)),
|
||||
),
|
||||
ArrowDataType::Float64 => datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::Float64(None),
|
||||
),
|
||||
ArrowDataType::Utf8 => datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::Utf8(None),
|
||||
),
|
||||
ArrowDataType::Binary => datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::Binary(None),
|
||||
),
|
||||
ArrowDataType::Struct(_) | ArrowDataType::List(_) => {
|
||||
datafusion::logical_expr::Expr::Cast(
|
||||
datafusion::logical_expr::Cast::new(
|
||||
Box::new(datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::Null,
|
||||
)),
|
||||
field.data_type().clone(),
|
||||
),
|
||||
)
|
||||
}
|
||||
ArrowDataType::Timestamp(TimeUnit::Millisecond, timezone) => {
|
||||
datafusion::logical_expr::lit(
|
||||
datafusion::scalar::ScalarValue::TimestampMillisecond(
|
||||
None,
|
||||
timezone.clone(),
|
||||
),
|
||||
)
|
||||
}
|
||||
_ => unreachable!(
|
||||
"unexpected evaluated-frame schema field {:?}",
|
||||
field.data_type()
|
||||
),
|
||||
};
|
||||
null.alias(field.name())
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let session_state = datafusion::execution::SessionStateBuilder::new().build();
|
||||
let regions = (0..region_count).map(|i| RegionId::new(1024, i)).collect();
|
||||
let merge = MergeScanExec::new(
|
||||
&session_state,
|
||||
TableName::new("catalog", "schema", "table"),
|
||||
regions,
|
||||
raw_plan,
|
||||
tagged_schema.as_ref(),
|
||||
Arc::new(UnusedRegionQueryHandler),
|
||||
QueryContext::arc(),
|
||||
1,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
Arc::new(
|
||||
VectorSelectExec::try_new(
|
||||
Arc::from("topk(1, metric)"),
|
||||
Arc::new(merge),
|
||||
Arc::new(suffix),
|
||||
series_schema,
|
||||
Arc::new(ArrowSchema::new(vec![
|
||||
ArrowField::new("value", ArrowDataType::Float64, true),
|
||||
ArrowField::new("host", ArrowDataType::Utf8, true),
|
||||
ArrowField::new("__name__", ArrowDataType::Utf8, true),
|
||||
ArrowField::new(
|
||||
"time",
|
||||
ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
])),
|
||||
"time".into(),
|
||||
vec!["host".into(), "__name__".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_select_region_guard_accepts_one_region_and_rejects_two() {
|
||||
let one = vector_select_for_region_count(1);
|
||||
assert!(validate_vector_select_regions(&one).is_ok());
|
||||
let two = vector_select_for_region_count(2);
|
||||
let error = validate_vector_select_regions(&two).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("native global topk requires one physical region, got 2"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
fn new_query_engine_state() -> QueryEngineState {
|
||||
new_query_engine_state_with(Plugins::default(), QueryOptions::default())
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -25,14 +26,22 @@ use common_query::prelude::{GREPTIME_TEMPORALITY_DELTA, OTLP_AGGREGATION_TEMPORA
|
||||
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
|
||||
use common_query::{Output, OutputData};
|
||||
use common_recordbatch::util::collect_batches;
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::physical_expr::PhysicalExpr;
|
||||
use datafusion::physical_plan::coop::CooperativeExec;
|
||||
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties};
|
||||
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::datatypes::DataType;
|
||||
use frontend::instance::Instance;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use query::datafusion::{QUERY_FALLBACK_HINT, QUERY_PARALLELISM_HINT};
|
||||
use query::dist_plan::MergeScanExec;
|
||||
use query::options::QueryOptions;
|
||||
@@ -1776,6 +1785,13 @@ struct NativePlanObserver(
|
||||
Mutex<Option<Arc<dyn datafusion::physical_plan::ExecutionPlan>>>,
|
||||
Mutex<Vec<Arc<dyn datafusion::physical_plan::ExecutionPlan>>>,
|
||||
);
|
||||
#[derive(Default)]
|
||||
struct GlobalTopkObserver {
|
||||
fused: Mutex<Option<Arc<dyn datafusion::physical_plan::ExecutionPlan>>>,
|
||||
select: Mutex<Option<Arc<dyn datafusion::physical_plan::ExecutionPlan>>>,
|
||||
gate_enabled: std::sync::atomic::AtomicBool,
|
||||
gate: Mutex<Option<Arc<PartitionGate>>>,
|
||||
}
|
||||
|
||||
impl NativePlanObserver {
|
||||
fn clear(&self) {
|
||||
@@ -1801,6 +1817,215 @@ impl NativePlanObserver {
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalTopkObserver {
|
||||
fn gate_next_fused_execution(&self) {
|
||||
self.gate_enabled.store(true, AtomicOrdering::SeqCst);
|
||||
}
|
||||
|
||||
fn take_gate(&self) -> Arc<PartitionGate> {
|
||||
self.gate
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("fused gate installed")
|
||||
}
|
||||
|
||||
fn clear(&self) {
|
||||
*self.fused.lock().unwrap() = None;
|
||||
*self.select.lock().unwrap() = None;
|
||||
}
|
||||
fn take_fused(&self) -> Arc<dyn datafusion::physical_plan::ExecutionPlan> {
|
||||
self.fused.lock().unwrap().take().unwrap()
|
||||
}
|
||||
fn take_select(&self) -> Arc<dyn datafusion::physical_plan::ExecutionPlan> {
|
||||
self.select.lock().unwrap().take().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicalPlanWrapper for GlobalTopkObserver {
|
||||
fn wrap(
|
||||
&self,
|
||||
origin: Arc<dyn datafusion::physical_plan::ExecutionPlan>,
|
||||
_ctx: session::context::QueryContextRef,
|
||||
) -> Arc<dyn datafusion::physical_plan::ExecutionPlan> {
|
||||
// Wrapper callbacks can see outer plans before the region's fused node exists. Keep the
|
||||
// request armed until a callback actually installs the gate around that node.
|
||||
let gate_fused = self.gate_enabled.load(AtomicOrdering::SeqCst);
|
||||
let gate = Arc::new(PartitionGate::new(4));
|
||||
let (plan, installed) = if gate_fused {
|
||||
gate_native_fused(origin, Arc::clone(&gate))
|
||||
} else {
|
||||
(origin, false)
|
||||
};
|
||||
if installed {
|
||||
self.gate_enabled.store(false, AtomicOrdering::SeqCst);
|
||||
*self.gate.lock().unwrap() = Some(gate);
|
||||
}
|
||||
let mut stack = vec![plan.clone()];
|
||||
while let Some(node) = stack.pop() {
|
||||
match node.name() {
|
||||
"FusedSeriesExec" => *self.fused.lock().unwrap() = Some(node.clone()),
|
||||
"VectorSelectExec" => *self.select.lock().unwrap() = Some(node.clone()),
|
||||
_ => {}
|
||||
}
|
||||
stack.extend(node.children().into_iter().cloned());
|
||||
}
|
||||
plan
|
||||
}
|
||||
}
|
||||
|
||||
/// Each partition must compute a non-empty first batch before any partition can continue.
|
||||
struct PartitionGate {
|
||||
barrier: tokio::sync::Barrier,
|
||||
arrived: AtomicUsize,
|
||||
}
|
||||
|
||||
impl PartitionGate {
|
||||
fn new(partitions: usize) -> Self {
|
||||
Self {
|
||||
barrier: tokio::sync::Barrier::new(partitions),
|
||||
arrived: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait(&self) -> DataFusionResult<()> {
|
||||
self.arrived.fetch_add(1, AtomicOrdering::SeqCst);
|
||||
tokio::time::timeout(Duration::from_secs(10), self.barrier.wait())
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|_| {
|
||||
DataFusionError::Execution(format!(
|
||||
"only {} of 4 native fused partitions produced a first batch concurrently",
|
||||
self.arrived.load(AtomicOrdering::SeqCst)
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn arrived(&self) -> usize {
|
||||
self.arrived.load(AtomicOrdering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
fn gate_native_fused(
|
||||
plan: Arc<dyn ExecutionPlan>,
|
||||
gate: Arc<PartitionGate>,
|
||||
) -> (Arc<dyn ExecutionPlan>, bool) {
|
||||
if plan.name() == "FusedSeriesExec" {
|
||||
return (Arc::new(NativeFusedGateExec { child: plan, gate }), 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("test gate rebuilds plan above fused node"),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
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 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();
|
||||
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 test barrier"
|
||||
)));
|
||||
}
|
||||
};
|
||||
if first.num_rows() == 0 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"fused partition {partition} produced an empty first batch for 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,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicalPlanWrapper for NativePlanObserver {
|
||||
fn wrap(
|
||||
&self,
|
||||
@@ -2214,6 +2439,172 @@ async fn native_promql_executes_fused_node_and_matches_legacy() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Global native topk spans the four real producer partitions and the region coalesce.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_global_topk_preserves_four_real_prefix_partitions() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let config = mito2::config::MitoConfig {
|
||||
experimental_series_scan_v2: true,
|
||||
..Default::default()
|
||||
};
|
||||
let observer = Arc::new(GlobalTopkObserver::default());
|
||||
let plugins = Plugins::new();
|
||||
let wrapper: PhysicalPlanWrapperRef = observer.clone();
|
||||
plugins.insert(wrapper);
|
||||
let standalone = GreptimeDbStandaloneBuilder::new("native_promql_global_topk")
|
||||
.with_mito_config(config)
|
||||
.with_plugin(plugins)
|
||||
.with_query_options(QueryOptions {
|
||||
experimental_native_promql: true,
|
||||
..Default::default()
|
||||
})
|
||||
.build()
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
execute_all(&instance,
|
||||
"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'); INSERT INTO native_topk (host, ts, val) VALUES ('a', 0, 2), ('b', 0, 4), ('c', 0, 6), ('d', 0, 8), ('e', 0, 10), ('f', 0, 12), ('g', 0, 14), ('h', 0, 16), ('i', 0, 18), ('j', 0, 20), ('k', 0, 22), ('l', 0, 24), ('m', 0, 26), ('n', 0, 28), ('o', 0, 30), ('p', 0, 32)", QueryContext::arc()).await;
|
||||
let query = PromQuery {
|
||||
query: "topk(3, native_topk)".into(),
|
||||
start: "0".into(),
|
||||
end: "0".into(),
|
||||
step: "1s".into(),
|
||||
..PromQuery::default()
|
||||
};
|
||||
// Run the native prefix without ranking as the reference for the global top-k result.
|
||||
// Derive the expected winners from actual producer output rather than fixture assumptions.
|
||||
let reference = PromQuery {
|
||||
query: "native_topk".into(),
|
||||
..query.clone()
|
||||
};
|
||||
observer.clear();
|
||||
let reference_rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(&reference, native_query_context(true, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let mut ranked_reference = reference_rows;
|
||||
ranked_reference.sort_by(|left, right| {
|
||||
right
|
||||
.2
|
||||
.total_cmp(&left.2)
|
||||
.then_with(|| left.1.cmp(&right.1))
|
||||
});
|
||||
ranked_reference.truncate(3);
|
||||
ranked_reference.sort_by(|left, right| left.1.cmp(&right.1));
|
||||
|
||||
observer.clear();
|
||||
observer.gate_next_fused_execution();
|
||||
let rows = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(&query, native_query_context(true, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let prefix = observer.take_fused();
|
||||
let select = observer.take_select();
|
||||
assert_eq!(
|
||||
select.name(),
|
||||
"VectorSelectExec",
|
||||
"query must execute the global native ranker"
|
||||
);
|
||||
assert_eq!(
|
||||
prefix.output_partitioning().partition_count(),
|
||||
4,
|
||||
"all four prefix producers must reach the global coalesce"
|
||||
);
|
||||
// The region MergeScan is owned by VectorSelect's raw-input side; the fused prefix is
|
||||
// instantiated inside that region and therefore consumes its physical SeriesScan child.
|
||||
let select_children = select.children();
|
||||
let [input] = select_children.as_slice() else {
|
||||
panic!("VectorSelectExec must have one raw-input child: {select:?}");
|
||||
};
|
||||
let mut raw_input = Arc::clone(input);
|
||||
if let Some(sort) = raw_input
|
||||
.as_ref()
|
||||
.downcast_ref::<datafusion::physical_plan::sorts::sort::SortExec>()
|
||||
{
|
||||
let children = sort.children();
|
||||
let [child] = children.as_slice() else {
|
||||
panic!("VectorSelect sort must have one child");
|
||||
};
|
||||
raw_input = Arc::clone(child);
|
||||
}
|
||||
if let Some(coalesce) = raw_input
|
||||
.as_ref()
|
||||
.downcast_ref::<datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec>(
|
||||
) {
|
||||
let children = coalesce.children();
|
||||
let [child] = children.as_slice() else {
|
||||
panic!("VectorSelect coalesce must have one child");
|
||||
};
|
||||
raw_input = Arc::clone(child);
|
||||
}
|
||||
if let Some(cooperative) = raw_input.as_ref().downcast_ref::<CooperativeExec>() {
|
||||
raw_input = Arc::clone(cooperative.input());
|
||||
}
|
||||
let merge = raw_input
|
||||
.as_ref()
|
||||
.downcast_ref::<query::dist_plan::MergeScanExec>()
|
||||
.expect("VectorSelect raw input is a real MergeScanExec");
|
||||
assert_eq!(
|
||||
merge.region_count(),
|
||||
1,
|
||||
"logical metric resolves to one physical region"
|
||||
);
|
||||
let prefix_children = prefix.children();
|
||||
let [region_scan] = prefix_children.as_slice() else {
|
||||
panic!("region fused prefix must have one scan child: {prefix:?}");
|
||||
};
|
||||
let physical_scan = region_scan
|
||||
.as_ref()
|
||||
.downcast_ref::<CooperativeExec>()
|
||||
.map_or(*region_scan, |cooperative| cooperative.input());
|
||||
assert_eq!(
|
||||
physical_scan.name(),
|
||||
"SeriesScanExec",
|
||||
"region fused child is actual SeriesScanExec, optionally under CooperativeExec"
|
||||
);
|
||||
use datafusion::physical_plan::metrics::MetricValue;
|
||||
let mut nonempty = [false; 4];
|
||||
for metric in prefix.metrics().unwrap().iter() {
|
||||
if let MetricValue::Count { count, .. } = metric.value()
|
||||
&& metric.value().name() == "native.root.output_values"
|
||||
&& let Some(partition) = metric.partition()
|
||||
&& let Some(slot) = nonempty.get_mut(partition)
|
||||
{
|
||||
*slot |= count.value() > 0;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
nonempty.iter().all(|value| *value),
|
||||
"all four real fused partitions must produce: {nonempty:?}"
|
||||
);
|
||||
let gate = observer.take_gate();
|
||||
assert_eq!(
|
||||
gate.arrived(),
|
||||
4,
|
||||
"all four fused partitions computed a first batch before any continued"
|
||||
);
|
||||
assert_eq!(
|
||||
rows, ranked_reference,
|
||||
"global topk must match ranking the unranked native prefix"
|
||||
);
|
||||
let legacy = native_result_rows(
|
||||
instance
|
||||
.do_promql_query(&query, native_query_context(false, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(rows, legacy);
|
||||
}
|
||||
|
||||
/// Native instant selectors preserve anchored evaluation and sample timestamps in standalone.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_instant_at_uses_sample_time_and_anchor() {
|
||||
|
||||
Reference in New Issue
Block a user