mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-29 22:24:02 +00:00
fix(promql): bind fused inputs only after full identity admission
Reuse the shared cross-series reads and pointwise/full-key proofs instead of
a temporary root Binary allowance: a single occurrence may broadcast or
negate, and two occurrences share one actual source only when the root is
one-to-one, both operands are pointwise, and the complete keys prove the
same series. Aggregates and vector nodes under a Binary, Map or scalar
now fall back. Also require the exact physical input arity before the
adapter indexes bindings, so a mismatched call returns a Plan error
instead of panicking.
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
(cherry picked from commit 988ac3616b)
This commit is contained in:
+12
-7
@@ -26,16 +26,21 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`.
|
||||
(`src/promql/src/extension_plan/planner.rs`) maps the logical nodes to their
|
||||
execution plans.
|
||||
- **Fused native-series route:** the query planner offers a PromQL statement to
|
||||
`native_compile::compile` only when the engine's
|
||||
`native_compile::compile_selectors` only when the engine's
|
||||
`in_process_region_transport` and `QueryOptions::experimental_native_promql`
|
||||
options are enabled and the per-request `query.experimental_native_promql`
|
||||
extension is true. Accepted plans use process-local `FusedSeries`; declined
|
||||
or unsupported shapes fall back to the existing planner. The supported subset
|
||||
requires one selector, a direct scan with a bound metric name, and no residual
|
||||
label matchers or `__field__` matcher that narrows the scan, plus an eligible
|
||||
raw-series table/field set and supported expression/grid. Metric scans retain
|
||||
the static `__table_id` predicate. Hybrid CTEs and CREATE VIEW TQL creation
|
||||
currently fall back to the existing planner.
|
||||
or unsupported shapes fall back to the existing planner. `compile_selectors`
|
||||
binds each selector to its own scan, and the route accepts one selector over a
|
||||
direct scan with a bound metric name, or two occurrences of one selector when
|
||||
both read one identical final scan, matched one-to-one over the whole series
|
||||
identity with a point-wise operand on each side. Label matchers are not a
|
||||
reason to decline: each scan applies its own. Only trees that read one series at
|
||||
a time are admitted, so an aggregate or a whole-vector operation (`sort`,
|
||||
`absent`, ...) anywhere in the tree falls back, as does an ineligible
|
||||
raw-series table/field set or an unsupported expression/grid. Metric scans
|
||||
retain the static `__table_id` predicate. Hybrid CTEs and CREATE VIEW TQL
|
||||
creation currently fall back to the existing planner.
|
||||
|
||||
## Change coupling
|
||||
|
||||
|
||||
@@ -541,11 +541,8 @@ fn validate_paths<'a>(
|
||||
/// partitions, which does not exist yet. Until it does the tree is refused where it can hurt: over
|
||||
/// one partition there is nothing to split, so only a tree run over more than one is checked.
|
||||
///
|
||||
/// The compiler cannot build a nested window today - [`compile`](crate::promql::native_compile::compile)
|
||||
/// requires a range function to apply directly to a selector, `<range function>(<selector>[<range>])`,
|
||||
/// and a selector is raw samples - so no tree it produces has a window above a window, and this
|
||||
/// check costs no executable query. It is checked because [`FusedSeriesExec::try_new`] accepts any
|
||||
/// well-formed tree, and a tree it accepts is a tree it must answer correctly.
|
||||
/// The standalone planner declines subqueries, so its admitted trees have no nested window. This
|
||||
/// check also protects [`FusedSeriesExec::try_new`] callers that supply a well-formed tree directly.
|
||||
fn reject_a_split_logical_series(
|
||||
tree: &NativeTree,
|
||||
partition_count: usize,
|
||||
|
||||
@@ -49,6 +49,7 @@ use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::context::TaskContext;
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
|
||||
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::{EmptyRelation, LogicalPlan, UserDefinedLogicalNodeCore};
|
||||
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
|
||||
use datafusion::physical_optimizer::PhysicalOptimizerRule;
|
||||
@@ -59,6 +60,7 @@ use datafusion::physical_plan::{
|
||||
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, Partitioning, PlanProperties,
|
||||
RecordBatchStream, SendableRecordBatchStream, collect, displayable,
|
||||
};
|
||||
use datafusion::physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner};
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datatypes::series::frame::{RawLabelMode, pack_raw_series_chunk, raw_series_frame_schema};
|
||||
use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
|
||||
@@ -73,6 +75,7 @@ use super::{
|
||||
LabelSets, OutputColumn, POLL_BUDGET, label_set, occupied_runs, series_to_record_batch,
|
||||
};
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
use crate::extension_plan::PromExtensionPlanner;
|
||||
use crate::native::execute::{NativeExecutionState, NativeExecutor};
|
||||
use crate::native::metrics::{NodeMetric, NodePath};
|
||||
use crate::native::plan::{
|
||||
@@ -1985,6 +1988,55 @@ fn the_execution_inputs_must_be_one_per_binding() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The physical inputs of the node must number its bindings, whoever plans it.
|
||||
///
|
||||
/// DataFusion plans every physical child before it asks for the node, so its own route always
|
||||
/// matches the count. A direct call of `plan_extension` need not, and the bindings are paired with
|
||||
/// the inputs by position, so a list of another length is a plan error naming both counts instead
|
||||
/// of a binding read past its end or an input silently ignored. The inputs here are memory sources,
|
||||
/// which this node cannot read as raw series: that they are refused for their count and not for
|
||||
/// their type is what shows the count is asked before a child is looked at, since the scan check
|
||||
/// would have answered `Ok(None)` for both counts instead.
|
||||
#[tokio::test]
|
||||
async fn the_physical_inputs_must_number_the_bindings() {
|
||||
let node = fused(rate_tree());
|
||||
let planner = DefaultPhysicalPlanner::default();
|
||||
let session = SessionContext::default();
|
||||
let state = session.state();
|
||||
let planning_ctx = PhysicalPlanningContext::default();
|
||||
for count in [0, 2] {
|
||||
let inputs = (0..count)
|
||||
.map(|_| memory_exec(Vec::new()))
|
||||
.collect::<Vec<_>>();
|
||||
let error = PromExtensionPlanner
|
||||
.plan_extension(&planner, &node, &[], &inputs, &state, &planning_ctx)
|
||||
.await
|
||||
.expect_err("the node binds one input, whatever it was given");
|
||||
assert!(matches!(error, DataFusionError::Plan(_)), "{error}");
|
||||
assert!(
|
||||
error.to_string().contains(&format!(
|
||||
"binds 1 inputs, but {count} physical inputs were given"
|
||||
)),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
let planned = PromExtensionPlanner
|
||||
.plan_extension(
|
||||
&planner,
|
||||
&node,
|
||||
&[],
|
||||
&[memory_exec(Vec::new())],
|
||||
&state,
|
||||
&planning_ctx,
|
||||
)
|
||||
.await
|
||||
.expect("one input is the node's own arity");
|
||||
assert!(
|
||||
planned.is_none(),
|
||||
"a memory source is not a region scan: {planned:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The physical children cover the tree's destinations exactly, one child per actual source.
|
||||
#[test]
|
||||
fn the_physical_children_must_cover_every_destination() {
|
||||
|
||||
@@ -102,8 +102,16 @@ fn plan_fused_series(
|
||||
physical_inputs: &[Arc<dyn ExecutionPlan>],
|
||||
target_partitions: usize,
|
||||
) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
|
||||
if physical_inputs.is_empty() {
|
||||
return Ok(None);
|
||||
// The bindings and the physical inputs are paired by position below, so an input list of another
|
||||
// length is refused before anything is read off it. DataFusion plans every child of an extension
|
||||
// node before it calls here, so its own route always matches this count; a direct call of
|
||||
// `plan_extension` need not.
|
||||
let expected = fused.fused_inputs().len();
|
||||
if physical_inputs.len() != expected {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"FusedSeries binds {expected} inputs, but {} physical inputs were given",
|
||||
physical_inputs.len()
|
||||
)));
|
||||
}
|
||||
let mut prepared = Vec::new();
|
||||
for (index, input) in physical_inputs.iter().enumerate() {
|
||||
|
||||
@@ -23,12 +23,14 @@ use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
|
||||
use promql::extension_plan::{
|
||||
EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize,
|
||||
};
|
||||
use promql::native::plan::{NativeExpr, NativeNode};
|
||||
use promql::native::plan::{NativeExpr, NativeNode, reads_across_series};
|
||||
use promql::vector_match::Cardinality;
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
|
||||
|
||||
use crate::dist_plan::MergeScanLogicalPlan;
|
||||
use crate::dist_plan::analyzer::AliasMapping;
|
||||
use crate::dist_plan::merge_sort::{MergeSortLogicalPlan, merge_sort_transformer};
|
||||
use crate::promql::planner::native::{matching_keys_on_identity, pointwise_operand};
|
||||
|
||||
pub struct StepTransformAction {
|
||||
extra_parent_plans: Vec<LogicalPlan>,
|
||||
@@ -246,36 +248,35 @@ impl Categorizer {
|
||||
// A region builds this node from the region scans themselves: the conversion takes a
|
||||
// scan's raw-series entrypoint and cannot look through anything in between, so a
|
||||
// node with an input that is not such a scan has nothing to read where it would be
|
||||
// placed and stays where it was planned. Every input also has to read the same
|
||||
// table: two tables need not share a region, and a region can only evaluate the tree
|
||||
// over the scans it can build for itself.
|
||||
let inputs = fused.inputs();
|
||||
let mut table = None;
|
||||
for input in &inputs {
|
||||
let LogicalPlan::TableScan(scan) = input else {
|
||||
return Commutativity::NonCommutative;
|
||||
};
|
||||
if table.is_some_and(|name| name != &scan.table_name) {
|
||||
return Commutativity::NonCommutative;
|
||||
}
|
||||
table = Some(&scan.table_name);
|
||||
}
|
||||
// The region asks each scan for the series of one named metric, so a node with an
|
||||
// input that binds no name cannot be built there at all.
|
||||
if fused
|
||||
.fused_inputs()
|
||||
.iter()
|
||||
.any(|input| input.metric_name.is_none())
|
||||
{
|
||||
// placed and stays where it was planned. A binding is one actual source, so a node
|
||||
// that lists its raw inputs as several bindings reads several plans and a region has
|
||||
// nothing to build for it either.
|
||||
let [input] = fused.fused_inputs() else {
|
||||
return Commutativity::NonCommutative;
|
||||
};
|
||||
let LogicalPlan::TableScan(_) = &input.input else {
|
||||
return Commutativity::NonCommutative;
|
||||
};
|
||||
// The region asks the scan for the series of one named metric, so a node that binds
|
||||
// no name cannot be built there at all.
|
||||
if input.metric_name.is_none() {
|
||||
return Commutativity::NonCommutative;
|
||||
}
|
||||
// A region evaluates the tree over whatever series its own scans return. A window,
|
||||
// a map and an instant read one series at a time, so one region's share of a series
|
||||
// is everything they need of it. An aggregate folds a label set's series together
|
||||
// and would fold one region's half of the group, so it stays where it was planned.
|
||||
// A binary operation pairs series by label, which a region can answer for every
|
||||
// pair whose two sides it holds; see the caveat below.
|
||||
if folds_across_series(fused.tree().root()) {
|
||||
// A region evaluates the tree over whatever series its own scan returns, so the tree
|
||||
// has to read one series at a time. An aggregate folds a label set's series together,
|
||||
// a vector operation reads the whole vector, and a match between two series sets
|
||||
// pairs one series with another; one region holds only part of them. What does read
|
||||
// one series at a time is a point-wise operand - a selection, a window, a map over
|
||||
// either, or a constant broadcast - or, for the two occurrences the planner
|
||||
// collapsed onto this one plan, a one-to-one match over the whole series identity
|
||||
// with a point-wise operand on each side.
|
||||
let root = fused.tree().root();
|
||||
let per_series = match input.paths.as_slice() {
|
||||
[_] => pointwise_operand(root),
|
||||
[_, _] => two_occurrences_pair_one_series(root, &input.tags),
|
||||
_ => false,
|
||||
};
|
||||
if reads_across_series(root) && !per_series {
|
||||
return Commutativity::NonCommutative;
|
||||
}
|
||||
|
||||
@@ -290,13 +291,6 @@ impl Categorizer {
|
||||
// region deployment satisfies it; a partitioned table over several regions does not,
|
||||
// and would return a wrong answer rather than an error.
|
||||
//
|
||||
// A binary operation adds one more way to be in this position: it pairs two series
|
||||
// by their labels, and the two sides of one pair need not reach one region - a table
|
||||
// partitioned by a column the match does not name puts `a{kind="a"}` and
|
||||
// `a{kind="b"}` with the same `host` in different regions, and the region holding
|
||||
// one of them finds no partner and drops the match. One region holds every series
|
||||
// both scans can return, so the pair is there.
|
||||
//
|
||||
// What would make this unconditional is a partition key the label set determines,
|
||||
// checked against the table's physical partition expressions. Until then the
|
||||
// placement is a proof of concept over one region.
|
||||
@@ -408,31 +402,25 @@ impl Categorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `tree` folds one label set's series into a single value.
|
||||
/// Whether `root` pairs the two occurrences one plan feeds point-wise over the whole identity.
|
||||
///
|
||||
/// An aggregate folds every series of a group together, so a region that holds part of the group
|
||||
/// would answer the fold of its own half and the union of the parts would be a wrong query answered
|
||||
/// silently. Everything else the native compiler emits reads one series at a time: an instant
|
||||
/// selection, a window and a point-wise map each select, fold or map the samples of the series they
|
||||
/// were handed. A binary operation pairs series rather than folding them, so it is not a fold here;
|
||||
/// what a region can pair is the subject of the caveat at the placement decision. A vector operation
|
||||
/// reads the whole vector at a grid point, so it folds across series the way an aggregate does.
|
||||
fn folds_across_series(node: &NativeNode) -> bool {
|
||||
match &node.expr {
|
||||
NativeExpr::Input(_) | NativeExpr::Scalar(_) => false,
|
||||
NativeExpr::Instant { input, .. }
|
||||
| NativeExpr::Window { input, .. }
|
||||
| NativeExpr::Map { input, .. } => folds_across_series(input),
|
||||
// A binary operation pairs the two sides rather than folding either of them, so what
|
||||
// decides is whether a side folds its own input.
|
||||
NativeExpr::Binary { left, right, .. } => {
|
||||
folds_across_series(left) || folds_across_series(right)
|
||||
}
|
||||
NativeExpr::Aggregate { .. } => true,
|
||||
// `sort`, `absent`, `topk` and `histogram_quantile` reorder or read every series of the
|
||||
// vector at a grid point, so one region's share of the series cannot answer them.
|
||||
NativeExpr::Vector { .. } => true,
|
||||
}
|
||||
/// The two occurrences are one scan, so both sides hold the same series in the same partition: what
|
||||
/// is left to check is that the tree between them is a one-to-one match over the key that names the
|
||||
/// whole series ([`matching_keys_on_identity`]) with a point-wise operand on each side, which is the
|
||||
/// shape `PromPlanner` collapses onto one input. Anything else keeps the node on the frontend.
|
||||
fn two_occurrences_pair_one_series(root: &NativeNode, tags: &[String]) -> bool {
|
||||
let NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
matching,
|
||||
} = &root.expr
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
matching.cardinality == Cardinality::OneToOne
|
||||
&& pointwise_operand(left)
|
||||
&& pointwise_operand(right)
|
||||
&& matching_keys_on_identity(&matching.labels, tags)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -458,10 +446,8 @@ mod tests {
|
||||
use promql::functions::{
|
||||
NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile,
|
||||
};
|
||||
use promql::native::plan::{
|
||||
AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, Grouping,
|
||||
NativeExpr, NativeNode, NativeType,
|
||||
};
|
||||
use promql::native::metrics::NodePath;
|
||||
use promql::native::plan::{NativeExpr, NativeTree};
|
||||
use promql_parser::parser;
|
||||
use store_api::storage::RegionId;
|
||||
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
@@ -469,7 +455,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::dist_plan::DistPlannerAnalyzer;
|
||||
use crate::optimizer::test_util::mock_table_provider;
|
||||
use crate::promql::native_compile::{compile, statement_grid};
|
||||
use crate::promql::native_compile::{compile, compile_selectors, statement_grid};
|
||||
use crate::query_engine::DefaultSerializer;
|
||||
|
||||
#[test]
|
||||
@@ -547,7 +533,7 @@ mod tests {
|
||||
// tree rather than assuming.
|
||||
let mut paths = Vec::new();
|
||||
promql::native::metrics::walk(tree.root(), &mut |node, path| {
|
||||
if matches!(node.expr, promql::native::plan::NativeExpr::Input(_)) {
|
||||
if matches!(node.expr, NativeExpr::Input(_)) {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
});
|
||||
@@ -774,51 +760,191 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// A tree built by something other than the compiler can hold a node that folds several
|
||||
/// series. The check is a property of the tree, so it is exercised on the node itself: the
|
||||
/// compiler emits no such node today, and nothing else would build a tree containing one.
|
||||
#[test]
|
||||
fn a_tree_that_folds_across_series_is_not_per_series() {
|
||||
let raw = NativeType::Samples(Arc::new(SeriesSchema {
|
||||
/// The statement `query` is planned as, on the grid these tests evaluate on.
|
||||
fn eval_statement(query: &str) -> promql_parser::parser::EvalStmt {
|
||||
let mut stmt = native_statement();
|
||||
stmt.expr = parser::parse(query).unwrap();
|
||||
stmt
|
||||
}
|
||||
|
||||
/// The tree `query` compiles to, with the raw-series schema every input is bound to.
|
||||
fn query_tree(
|
||||
query: &str,
|
||||
) -> (
|
||||
NativeTree,
|
||||
Arc<SeriesSchema>,
|
||||
promql_parser::parser::EvalStmt,
|
||||
) {
|
||||
let stmt = eval_statement(query);
|
||||
let series_schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
eval_grid: None,
|
||||
}));
|
||||
let input = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
output: raw.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
output: raw,
|
||||
});
|
||||
let tree = {
|
||||
let bound = Arc::clone(&series_schema);
|
||||
compile_selectors(
|
||||
&stmt,
|
||||
&move |_| Ok(Arc::clone(&bound)),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
.unwrap()
|
||||
.tree
|
||||
};
|
||||
let group = Grouping::By(Arc::from(["k0".into()]));
|
||||
let aggregate = NativeNode {
|
||||
expr: NativeExpr::Aggregate {
|
||||
input: Box::new(input),
|
||||
op: BoundAggregate {
|
||||
kind: AggregateKind::Sum,
|
||||
group: group.clone(),
|
||||
stage: AggregateStage::Partial,
|
||||
},
|
||||
},
|
||||
output: NativeType::AggregateState(Arc::new(AggregateStateSchema {
|
||||
group,
|
||||
accumulators: Arc::from([]),
|
||||
grid: statement_grid(&native_statement()).unwrap(),
|
||||
})),
|
||||
};
|
||||
assert!(folds_across_series(&aggregate));
|
||||
(tree, series_schema, stmt)
|
||||
}
|
||||
|
||||
// The same walk over what the compiler emits stays per-series.
|
||||
let single_selector = compile(
|
||||
&native_statement(),
|
||||
Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
eval_grid: None,
|
||||
}),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!folds_across_series(single_selector.root()));
|
||||
/// The paths of a tree's raw inputs, in walk order.
|
||||
fn tree_input_paths(tree: &NativeTree) -> Vec<NodePath> {
|
||||
let mut paths = Vec::new();
|
||||
promql::native::metrics::walk(tree.root(), &mut |node, path| {
|
||||
if matches!(node.expr, NativeExpr::Input(_)) {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
});
|
||||
paths
|
||||
}
|
||||
|
||||
/// A `FusedSeries` node over `query`, with `one_source` deciding how its raw inputs bind.
|
||||
///
|
||||
/// `one_source` binds every tree input to one plan - the shape a two-occurrence statement
|
||||
/// collapses to - and otherwise binds one plan per input.
|
||||
fn occurrence_plan(query: &str, tags: &[&str], one_source: bool) -> LogicalPlan {
|
||||
let (tree, series_schema, stmt) = query_tree(query);
|
||||
let paths = tree_input_paths(&tree);
|
||||
let binding = |paths| FusedSeriesInput {
|
||||
series_schema: Arc::clone(&series_schema),
|
||||
metric_name: Some(Arc::from("some_metric")),
|
||||
time_index: "ts".to_string(),
|
||||
tags: tags.iter().map(|tag| (*tag).to_string()).collect(),
|
||||
input: table_scan_plan(),
|
||||
paths,
|
||||
};
|
||||
let inputs = if one_source {
|
||||
vec![binding(paths)]
|
||||
} else {
|
||||
paths.into_iter().map(|path| binding(vec![path])).collect()
|
||||
};
|
||||
let output_schema: DFSchemaRef = Arc::new(
|
||||
DFSchema::new_with_metadata(
|
||||
vec![
|
||||
(
|
||||
None,
|
||||
Arc::new(Field::new("v0", ArrowDataType::Float64, true)),
|
||||
),
|
||||
(
|
||||
None,
|
||||
Arc::new(Field::new(
|
||||
"ts",
|
||||
ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
|
||||
false,
|
||||
)),
|
||||
),
|
||||
],
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(
|
||||
FusedSeries::try_new(
|
||||
Arc::from(query),
|
||||
tree,
|
||||
FusedSeriesBinding {
|
||||
grid: statement_grid(&stmt).unwrap(),
|
||||
},
|
||||
inputs,
|
||||
output_schema,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn commutativity_of(plan: &LogicalPlan) -> Commutativity {
|
||||
Categorizer::check_plan(plan, None).unwrap()
|
||||
}
|
||||
|
||||
/// One source read twice point-wise over the whole identity is one series per partition, so the
|
||||
/// node is placed as it was planned.
|
||||
#[test]
|
||||
fn fused_series_over_one_source_read_twice_is_commutative() {
|
||||
for query in [
|
||||
"some_metric + on(host) some_metric",
|
||||
"abs(some_metric) + on(host) some_metric",
|
||||
"(some_metric > bool 0) + on(host) some_metric",
|
||||
] {
|
||||
let plan = occurrence_plan(query, &["host"], true);
|
||||
assert!(
|
||||
matches!(commutativity_of(&plan), Commutativity::Commutative),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A statement that names its selector once is placed from the shape that reads one series'
|
||||
/// samples: a selection, a window or a map over one, or a constant broadcast.
|
||||
#[test]
|
||||
fn fused_series_over_one_pointwise_operand_is_commutative() {
|
||||
for query in [
|
||||
"some_metric",
|
||||
"rate(some_metric[5m])",
|
||||
"abs(some_metric)",
|
||||
"some_metric * 2",
|
||||
"-some_metric",
|
||||
] {
|
||||
let plan = occurrence_plan(query, &["host"], true);
|
||||
assert!(
|
||||
matches!(commutativity_of(&plan), Commutativity::Commutative),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A node that lists its raw inputs as two bindings reads two plans, and a region has nothing
|
||||
/// to build for it.
|
||||
#[test]
|
||||
fn fused_series_over_two_actual_scans_is_not_commutative() {
|
||||
let plan = occurrence_plan("some_metric + on(host) some_metric", &["host"], false);
|
||||
assert!(matches!(
|
||||
commutativity_of(&plan),
|
||||
Commutativity::NonCommutative
|
||||
));
|
||||
}
|
||||
|
||||
/// A match key that drops an identity tag, or a cardinality that pairs a group with a series,
|
||||
/// leaves a partition answering for the half of a series it holds.
|
||||
#[test]
|
||||
fn fused_series_over_a_partial_key_or_group_match_is_not_commutative() {
|
||||
for query in [
|
||||
"some_metric + on(host) some_metric",
|
||||
"some_metric + ignoring(zone) some_metric",
|
||||
"some_metric + on(host, zone) group_left some_metric",
|
||||
"some_metric + on(host, zone) group_right some_metric",
|
||||
] {
|
||||
let plan = occurrence_plan(query, &["host", "zone"], true);
|
||||
assert!(
|
||||
matches!(commutativity_of(&plan), Commutativity::NonCommutative),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree that reads a whole vector or folds a group reads across series, whether it is the
|
||||
/// root or sits below the match the planner collapsed.
|
||||
#[test]
|
||||
fn fused_series_whose_tree_reads_across_series_is_not_commutative() {
|
||||
for (query, one_source) in [
|
||||
("sort(some_metric)", true),
|
||||
("sum(some_metric)", true),
|
||||
("sort(some_metric) + on(host) sort(some_metric)", true),
|
||||
("sum(some_metric) + on(host) sum(some_metric)", true),
|
||||
] {
|
||||
let plan = occurrence_plan(query, &["host"], one_source);
|
||||
assert!(
|
||||
matches!(commutativity_of(&plan), Commutativity::NonCommutative),
|
||||
"{query}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoding gate is what kept the node on the frontend, and it only exists for a plan that
|
||||
|
||||
@@ -397,24 +397,6 @@ impl PromPlanner {
|
||||
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
|
||||
Err(e) => return Err(e).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
// An aggregate or a vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...)
|
||||
// reads the whole vector at each grid point rather than one series at a time, so it cannot
|
||||
// be evaluated by one executor per scan partition. Declining here is the only place that
|
||||
// still works: once the `FusedSeries` node exists the logical plan is fixed, and the
|
||||
// categorizer merely declining to push it down would leave a node the physical layer must
|
||||
// build anyway. A binary operation pairs one series with another and reads each of them
|
||||
// point-wise, so a tree rooted in one keeps the route: its operands are the independent
|
||||
// scans prepared above.
|
||||
//
|
||||
// TEMPORARY: the exception below is stated over the root alone, while the classifier it
|
||||
// narrows is a whole-tree walk. The two have to be reconciled with the per-operand
|
||||
// point-wise check the shared gate will own, so this narrowing is the first stage's anchor
|
||||
// rather than the shape to keep.
|
||||
if !matches!(compiled.tree.root().expr, NativeExpr::Binary { .. })
|
||||
&& reads_across_series(compiled.tree.root())
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
if compiled.inputs.len() != prepared.len() {
|
||||
return Err(DataFusionError::Internal(
|
||||
"the compiled tree reads a different number of inputs than the planner prepared"
|
||||
@@ -449,15 +431,28 @@ impl PromPlanner {
|
||||
input.paths = vec![compiled_input.path.clone()];
|
||||
inputs.push(input);
|
||||
}
|
||||
// A tree run once per scan partition has to read one series at a time: an aggregate folds a
|
||||
// label set's series together and a vector operation (`sort`, `absent`, `topk`,
|
||||
// `histogram_quantile`, ...) reads the whole vector at a grid point, so one region's share
|
||||
// of the series cannot answer either. Declining here is the only place that still works:
|
||||
// once the `FusedSeries` node exists the logical plan is fixed, and the categorizer merely
|
||||
// declining to push it down would leave a node the physical layer must build anyway. What
|
||||
// does read one series at a time is one occurrence's samples - a selection, a window, a map
|
||||
// over either, or a constant broadcast - and, for a statement that names one selector
|
||||
// twice, a one-to-one match whose key holds the whole identity, which the collapse below
|
||||
// then reads as one scan.
|
||||
if reads_across_series(compiled.tree.root())
|
||||
&& !(pointwise_operand(compiled.tree.root())
|
||||
|| (selectors.len() == 2
|
||||
&& two_occurrences_read_one_source(&compiled.tree, &inputs)))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
// Two occurrences of one selector read the same series only when the tree between them is
|
||||
// point-wise and both scans are the same scan. Then both inputs are one plan, and this node
|
||||
// runs one execution per partition of it instead of one execution over every partition.
|
||||
// Anything else keeps the existing plan: a match that pairs two scans' series needs an
|
||||
// exchange that pairs them, which this node does not have.
|
||||
// point-wise and both scans are the same scan, which the check above has just admitted.
|
||||
// Then both inputs are one plan, and this node runs one execution per partition of it
|
||||
// instead of one execution over every partition.
|
||||
if selectors.len() == 2 {
|
||||
if !two_occurrences_read_one_source(&compiled.tree, &inputs) {
|
||||
return Ok(None);
|
||||
}
|
||||
// The tree still names two input paths, so the second occurrence's destination moves
|
||||
// onto the first plan rather than being dropped with the plan that carried it. `append`
|
||||
// leaves the second list empty, which is what makes removing that plan lose nothing.
|
||||
@@ -657,9 +652,16 @@ fn literal_or_next(start: i64) -> Option<DfExpr> {
|
||||
/// selection or a window directly over the raw input, a point-wise map over either, and a binary
|
||||
/// operation with a constant on one side, which is a broadcast over the same positions.
|
||||
///
|
||||
/// A one-to-one match is admitted without looking at its fill values: the compiler refuses to bind
|
||||
/// `fill_left` or `fill_right` on anything but a `group_left`/`group_right` match, so a one-to-one
|
||||
/// node has none to account for.
|
||||
/// A one-to-one match is admitted without rejecting its fill values: the compiler binds
|
||||
/// `fill_left`/`fill_right` for a one-to-one match too, and what the admission rests on is the key
|
||||
/// and the operands, not the absence of a fill — see [`matching_keys_on_identity`].
|
||||
///
|
||||
/// The raw keys themselves are proven to name one logical series each by the caller's preparation,
|
||||
/// which checks the table's primary key against the tags this binding reports
|
||||
/// (`identity_keys_are_injective`). That is a planning-time check over the scan the planner
|
||||
/// prepared, not a property this function re-derives: a tree and binding built by anything other
|
||||
/// than this planner carries no such proof, so a manual `FusedSeries` node is only as safe as the
|
||||
/// binding its builder passed.
|
||||
fn two_occurrences_read_one_source(tree: &NativeTree, inputs: &[FusedSeriesInput]) -> bool {
|
||||
let NativeExpr::Binary {
|
||||
left,
|
||||
@@ -690,7 +692,7 @@ fn two_occurrences_read_one_source(tree: &NativeTree, inputs: &[FusedSeriesInput
|
||||
/// A node's output type is not checked here: [`NativeNode::validate`] already refuses a selection,
|
||||
/// a map or a binary operation whose operands are not evaluated vectors, so every branch below is
|
||||
/// one that produces values rather than raw samples.
|
||||
fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
pub(crate) fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
match &node.expr {
|
||||
// A selection reads the raw samples below it; anything else below it is a value computed
|
||||
// from a whole series, not a scan.
|
||||
@@ -713,10 +715,12 @@ fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::Aggregate { .. } => false,
|
||||
// A vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) reads the whole
|
||||
// vector at each grid point, so it is not a point-wise operand of one series.
|
||||
NativeExpr::Vector { .. } => false,
|
||||
// An aggregate folds a group, a vector operation reads the whole vector, and a bare input or
|
||||
// scalar is not a per-series evaluation.
|
||||
NativeExpr::Input(_)
|
||||
| NativeExpr::Scalar(_)
|
||||
| NativeExpr::Aggregate { .. }
|
||||
| NativeExpr::Vector { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -726,7 +730,7 @@ fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
/// tag then differ in the key. Anything else — a tag left out of `on`, or a tag named in
|
||||
/// `ignoring` — pairs two series that Prometheus reads as two, and each partition would then
|
||||
/// answer for the half it happens to hold.
|
||||
fn matching_keys_on_identity(labels: &MatchingLabels, tags: &[String]) -> bool {
|
||||
pub(crate) fn matching_keys_on_identity(labels: &MatchingLabels, tags: &[String]) -> bool {
|
||||
match labels {
|
||||
MatchingLabels::On(names) => tags
|
||||
.iter()
|
||||
|
||||
@@ -1089,6 +1089,9 @@ async fn build_test_identity_table_provider(
|
||||
));
|
||||
let table_meta = TableMetaBuilder::empty()
|
||||
.schema(Arc::new(Schema::new(columns)))
|
||||
// The engine decides whether the table can serve raw series at all, so a fixture that
|
||||
// leaves it unset declines the native route before any identity rule is reached.
|
||||
.engine(MITO_ENGINE.to_string())
|
||||
.primary_key_indices((0..tags.len()).collect())
|
||||
.value_indices(vec![tags.len() + 1])
|
||||
.next_column_id(1024)
|
||||
@@ -2084,6 +2087,58 @@ async fn native_fused_two_occurrences_decline_metadata_key() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A statement that names its selector once reads one scan, so it records one path however many
|
||||
/// positional operands its tree has.
|
||||
#[tokio::test]
|
||||
async fn native_fused_one_occurrence_records_one_path() {
|
||||
for query in [
|
||||
"some_metric",
|
||||
"some_metric * 2",
|
||||
"-some_metric",
|
||||
"2 - some_metric",
|
||||
"abs(some_metric)",
|
||||
"abs(some_metric * 2)",
|
||||
"some_metric > bool 0",
|
||||
] {
|
||||
let plan = build_native_fused_plan(query, true).await;
|
||||
let fused = find_fused_series(&plan)
|
||||
.unwrap_or_else(|| panic!("{query}: {}", plan.display_indent()));
|
||||
assert_eq!(1, fused.fused_inputs().len(), "{query}");
|
||||
let input = &fused.fused_inputs()[0];
|
||||
assert!(
|
||||
matches!(input.input, LogicalPlan::TableScan(_)),
|
||||
"{query}: {:?}",
|
||||
input.input
|
||||
);
|
||||
assert_eq!(1, input.paths.len(), "{query}: {:?}", input.paths);
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-vector operation or a group fold reads across series wherever it sits, so a statement
|
||||
/// that holds one keeps the existing plan — under a binary root, under a map, and under a constant
|
||||
/// broadcast over either.
|
||||
#[tokio::test]
|
||||
async fn native_fused_binary_holding_a_whole_vector_operation_falls_back() {
|
||||
let tags = [("host", false), ("zone", false)];
|
||||
for query in [
|
||||
"sort(some_metric{host!=\"\"}) + some_metric{host!=\"\"}",
|
||||
"abs(sort(some_metric{host!=\"\"})) + some_metric{host!=\"\"}",
|
||||
"sort(some_metric{host!=\"\"}) * 2",
|
||||
"sum(some_metric{host!=\"\"}) + some_metric{host!=\"\"}",
|
||||
"abs(sum(some_metric{host!=\"\"})) * 2",
|
||||
] {
|
||||
let native = build_identity_fused_plan(&tags, query, true).await;
|
||||
let legacy = build_identity_fused_plan(&tags, query, false).await;
|
||||
let display = native.display_indent().to_string();
|
||||
assert!(!display.contains("FusedSeries"), "{query}: {display}");
|
||||
assert_eq!(
|
||||
native.display_indent_schema().to_string(),
|
||||
legacy.display_indent_schema().to_string(),
|
||||
"{query}: a tree that reads across series must keep the existing plan"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two different metrics are two different scans, however alike their schemas are.
|
||||
#[tokio::test]
|
||||
async fn native_fused_two_occurrences_decline_different_table() {
|
||||
|
||||
Reference in New Issue
Block a user