mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
refactor(promql): bind fused inputs by execution source index
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
+29
-10
@@ -31,16 +31,18 @@ operators. Statement-to-plan translation lives in `src/query/src/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. `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.
|
||||
binds each selector to its own scan and stamps that scan's position on the
|
||||
tree input it creates (`BoundInput::source_index`), so `FusedSeries` holds one
|
||||
logical child per index and the tree itself says which child feeds which input.
|
||||
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
|
||||
|
||||
@@ -56,6 +58,16 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`.
|
||||
- A new logical node also needs its physical planner reachable from
|
||||
`DfQueryPlanner::create_physical_plan`, assembled in
|
||||
`src/query/src/query_engine/state.rs`.
|
||||
- A fused plan's inputs are described once. `BoundInput::source_index` names which
|
||||
source of one `NativeExecutor` invocation produced an input's chunks;
|
||||
`FusedSeries` maps that index to its DataFusion child by position, and the
|
||||
raw-series schema the input was compiled against is the layout its frame is
|
||||
decoded with. Neither the logical node nor `FusedSeriesExec` therefore keeps a
|
||||
per-child schema or destination list, while the binding's grid, time column,
|
||||
tags and metric name and the executor's `(plan, RawLabelSource, SeriesOrdering)`
|
||||
tuple stay as they are. A change to how a source is bound touches `BoundInput`
|
||||
(its `ordering` included, which the executor checks against the producer),
|
||||
`FusedSeries`'s source walk and the executor's `push_raw_source` together.
|
||||
|
||||
## Gotchas
|
||||
|
||||
@@ -66,6 +78,13 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`.
|
||||
its doc is written for a caller that does not exist.
|
||||
- **A native window requires non-interleaved input.** Only `Contiguous` and
|
||||
`KeyThenTime` are accepted; `Interleaved` is refused when compiled.
|
||||
- **A fused tree is logical over N sources, physical over one.** `FusedSeries`
|
||||
accepts one child per source index, but `FusedSeriesExec` runs exactly one
|
||||
child, at that child's own partition count, and queues its chunks with
|
||||
`NativeExecutor::push_raw_source(0, ..)`. A second source (needs a
|
||||
label-pairing exchange) and a constant scalar (needs a scalar-to-batch
|
||||
conversion) are refused when the physical node is built, never answered with
|
||||
an empty result.
|
||||
- **A series closes exactly once**, on the chunk that says so — per input series,
|
||||
not per label set. A node that rewrites labels can hand two input series over
|
||||
under one label set, and each closes on its own chunk, so a label set may be
|
||||
|
||||
@@ -38,9 +38,7 @@ use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::logical_expr::{Expr, Extension, LogicalPlan};
|
||||
use datatypes::data_type::DataType as _;
|
||||
pub use empty_metric::{EmptyMetric, EmptyMetricExec, EmptyMetricStream, build_special_time_expr};
|
||||
pub use fused_series::{
|
||||
FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, FusedSeriesStream,
|
||||
};
|
||||
pub use fused_series::{FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesStream};
|
||||
pub use histogram_fold::{
|
||||
HistogramFold, HistogramFoldExec, HistogramFoldOperation, HistogramFoldStream,
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -82,7 +82,7 @@ impl ExtensionPlanner for PromExtensionPlanner {
|
||||
/// column of any region.
|
||||
const METRIC_NAME: &str = "__name__";
|
||||
|
||||
/// Builds the physical node of a [`FusedSeries`] over the raw series leaf its input can provide.
|
||||
/// Builds the physical node of a [`FusedSeries`] over the raw series leaf its one child can provide.
|
||||
///
|
||||
/// The node reads a raw series frame, so what it needs below it is the region scan itself: the
|
||||
/// scan's own raw-series entrypoint is what packs a series' chunks contiguously and declares their
|
||||
@@ -96,29 +96,54 @@ const METRIC_NAME: &str = "__name__";
|
||||
/// reported as an error that names the reason instead of silently producing no plan.
|
||||
/// The fused leaf needs a prepared scan: range assignment runs after physical planning and cannot
|
||||
/// see a `SeriesScanExec`. Preparation keeps the scan's parallel layout, and the series-producer
|
||||
/// contract guarantees that one series stays in one scan partition.
|
||||
/// contract guarantees that one series stays in one scan partition. The fields the scan is asked
|
||||
/// for are the tree's own, and a node with no child (a constant scalar) or with several (which
|
||||
/// would need a label-pairing exchange) is refused here rather than planned into a node that
|
||||
/// cannot run it.
|
||||
fn plan_fused_series(
|
||||
fused: &FusedSeries,
|
||||
physical_inputs: &[Arc<dyn ExecutionPlan>],
|
||||
target_partitions: usize,
|
||||
) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
|
||||
// The bindings and the physical inputs are paired by position below, so an input list of another
|
||||
// The children 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 {
|
||||
let children = fused.children();
|
||||
if physical_inputs.len() != children.len() {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"FusedSeries binds {expected} inputs, but {} physical inputs were given",
|
||||
"FusedSeries binds {} inputs, but {} physical inputs were given",
|
||||
children.len(),
|
||||
physical_inputs.len()
|
||||
)));
|
||||
}
|
||||
let mut prepared = Vec::new();
|
||||
// One plan below is one actual source, which is what the physical node reads. A constant scalar
|
||||
// has no plan to read and several sources would have to be paired by label, which needs an
|
||||
// exchange this layer does not build: both are refused by name rather than planned into a node
|
||||
// that cannot run them.
|
||||
if children.is_empty() {
|
||||
return Err(DataFusionError::Plan(
|
||||
"the FusedSeries node reads no source: a constant scalar is not planned by this layer \
|
||||
yet"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
if children.len() > 1 {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"the FusedSeries node reads {} sources, and planning several of them as one tree is not \
|
||||
supported",
|
||||
children.len()
|
||||
)));
|
||||
}
|
||||
// Which columns the scan below must produce are the fields the tree's own input reads, not a
|
||||
// description kept beside the tree.
|
||||
let source_fields = super::fused_series::tree_source_fields(fused.tree())?;
|
||||
let binding = fused.binding();
|
||||
let mut prepared = Vec::with_capacity(children.len());
|
||||
for (index, input) in physical_inputs.iter().enumerate() {
|
||||
let Some(scan) = input.downcast_ref::<RegionScanExec>() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let binding = &fused.fused_inputs()[index];
|
||||
let Some(metric_name) = binding.metric_name.as_deref() else {
|
||||
return Err(DataFusionError::Plan(
|
||||
"the FusedSeries node binds no metric name".to_string(),
|
||||
@@ -130,12 +155,11 @@ fn plan_fused_series(
|
||||
.filter(|tag| tag.as_str() != METRIC_NAME)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let fields = binding
|
||||
.series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.name.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
let Some(fields) = source_fields.get(index) else {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"the FusedSeries tree reads no input at source {index}"
|
||||
)));
|
||||
};
|
||||
let scan = if scan.is_partition_set() {
|
||||
Arc::new(scan.clone())
|
||||
} else {
|
||||
@@ -147,7 +171,7 @@ fn plan_fused_series(
|
||||
.map_err(|e| DataFusionError::External(e.into_inner()))?,
|
||||
)
|
||||
};
|
||||
let Some(series_scan) = scan.try_to_named_series_scan(metric_name, &tags, &fields)? else {
|
||||
let Some(series_scan) = scan.try_to_named_series_scan(metric_name, &tags, fields)? else {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"the region scan under FusedSeries could not serve raw series for {metric_name:?}"
|
||||
)));
|
||||
|
||||
@@ -29,8 +29,8 @@ use crate::histogram_eval::HistogramFunction;
|
||||
use crate::map::MathOp;
|
||||
use crate::native::metrics::{self, NodePath};
|
||||
use crate::native::plan::{
|
||||
AggregateKind, AggregateStage, BoundVectorOp, BoundWindow, Grouping, MapOp, NativeExpr,
|
||||
NativeNode, NativeTree, NativeType,
|
||||
AggregateKind, AggregateStage, BoundInput, BoundVectorOp, BoundWindow, Grouping, MapOp,
|
||||
NativeExpr, NativeNode, NativeTree, NativeType,
|
||||
};
|
||||
use crate::range_eval::RangeFunction;
|
||||
use crate::select::SortOrder;
|
||||
@@ -84,14 +84,11 @@ fn ordering(ordering: SeriesOrdering) -> &'static str {
|
||||
/// The operation a node computes, in the words of the query that produced it.
|
||||
fn describe(node: &NativeNode) -> String {
|
||||
match &node.expr {
|
||||
NativeExpr::Input(input) => match &input.output {
|
||||
NativeType::Samples(schema) if schema.eval_grid.is_some() => {
|
||||
format!("evaluated samples{}", ordering(input.ordering))
|
||||
}
|
||||
NativeType::Samples(_) => format!("raw samples{}", ordering(input.ordering)),
|
||||
NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)),
|
||||
NativeType::AggregateState(_) => "aggregate state".to_string(),
|
||||
},
|
||||
// The source index is part of the input: inputs over different sources are different
|
||||
// inputs even when they hand over the same layout and ordering.
|
||||
NativeExpr::Input(input) => {
|
||||
format!("source={} {}", input.source_index, input_value(input))
|
||||
}
|
||||
NativeExpr::Scalar(scalar) => scalar.value.to_string(),
|
||||
NativeExpr::Instant { op, .. } => format!(
|
||||
"lookback {}ms offset {} on grid {}",
|
||||
@@ -165,6 +162,18 @@ fn describe(node: &NativeNode) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an input hands over: its samples or state, with the ordering it guarantees.
|
||||
fn input_value(input: &BoundInput) -> String {
|
||||
match &input.output {
|
||||
NativeType::Samples(schema) if schema.eval_grid.is_some() => {
|
||||
format!("evaluated samples{}", ordering(input.ordering))
|
||||
}
|
||||
NativeType::Samples(_) => format!("raw samples{}", ordering(input.ordering)),
|
||||
NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)),
|
||||
NativeType::AggregateState(_) => "aggregate state".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fill(values: FillValues) -> String {
|
||||
let side = |name: &str, value: Option<f64>| {
|
||||
value
|
||||
|
||||
@@ -48,6 +48,11 @@ fn evaluated(grid: Arc<EvalGrid>) -> NativeType {
|
||||
|
||||
/// An unqualified scan over raw samples, which is what a compiled query starts from.
|
||||
fn raw_input() -> NativeNode {
|
||||
raw_input_from(0)
|
||||
}
|
||||
|
||||
/// The same scan bound to child `source_index` of the final execution tree.
|
||||
fn raw_input_from(source_index: usize) -> NativeNode {
|
||||
// One allocation shared by the binding and the output: `validate` checks allocation identity.
|
||||
// The fields are the ones a window over this input reports, because a window keeps its input's
|
||||
// layout and `validate` rejects a node that declares a different count.
|
||||
@@ -57,6 +62,7 @@ fn raw_input() -> NativeNode {
|
||||
}));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -117,7 +123,7 @@ fn the_first_line_names_the_tree() {
|
||||
|
||||
assert_eq!(
|
||||
tree.to_string(),
|
||||
shown(&["NativeTree", " root Input raw samples"])
|
||||
shown(&["NativeTree", " root Input source=0 raw samples"])
|
||||
);
|
||||
assert_eq!(tree.to_string().lines().next(), Some("NativeTree"));
|
||||
}
|
||||
@@ -141,7 +147,7 @@ fn a_window_over_raw_samples_is_shown_once_per_node() {
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Window rate [300000ms] offset 0 anchor - on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -169,7 +175,7 @@ fn a_map_nests_below_the_window_it_maps() {
|
||||
"NativeTree",
|
||||
" root Map abs, round 3",
|
||||
" input Window rate [300000ms] offset 60000 anchor - on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -193,7 +199,7 @@ fn a_window_names_its_constant_argument_and_its_anchor() {
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Window quantile_over_time 0.9 [60000ms] offset 0 anchor 42 on grid 1000/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -208,6 +214,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
}));
|
||||
let evaluated_input = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: contiguous.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
@@ -216,7 +223,10 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
let tree = NativeTree::try_new(evaluated_input).unwrap();
|
||||
assert_eq!(
|
||||
tree.to_string(),
|
||||
shown(&["NativeTree", " root Input evaluated samples, contiguous",])
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Input source=0 evaluated samples, contiguous",
|
||||
])
|
||||
);
|
||||
|
||||
let interleaved = NativeType::Samples(Arc::new(SeriesSchema {
|
||||
@@ -225,6 +235,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
}));
|
||||
let raw_input = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: interleaved.clone(),
|
||||
ordering: SeriesOrdering::Interleaved,
|
||||
}),
|
||||
@@ -233,7 +244,72 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
let tree = NativeTree::try_new(raw_input).unwrap();
|
||||
assert_eq!(
|
||||
tree.to_string(),
|
||||
shown(&["NativeTree", " root Input raw samples, interleaved"])
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Input source=0 raw samples, interleaved"
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// The child an input reads is part of its line: two trees over different children, or over one
|
||||
/// child shared by both inputs, do not render as the same text.
|
||||
#[test]
|
||||
fn an_input_names_the_child_it_reads() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
let selected = |source_index: usize| NativeNode {
|
||||
expr: NativeExpr::Instant {
|
||||
input: Box::new(raw_input_from(source_index)),
|
||||
op: BoundInstant {
|
||||
lookback_ms: 300_000,
|
||||
offset_ms: 0,
|
||||
output_grid: Arc::clone(&out),
|
||||
},
|
||||
},
|
||||
output: evaluated(Arc::clone(&out)),
|
||||
};
|
||||
let tree = |left: usize, right: usize| {
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Binary {
|
||||
left: Box::new(selected(left)),
|
||||
right: Box::new(selected(right)),
|
||||
matching: BinaryMatching {
|
||||
op: BinaryOp::Add,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
},
|
||||
},
|
||||
output: evaluated(Arc::clone(&out)),
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let distinct = tree(0, 1).to_string();
|
||||
assert_eq!(
|
||||
distinct,
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Binary + ignoring [] one-to-one",
|
||||
" left Instant lookback 300000ms offset 0 on grid 0/60000x4",
|
||||
" input Input source=0 raw samples",
|
||||
" right Instant lookback 300000ms offset 0 on grid 0/60000x4",
|
||||
" input Input source=1 raw samples",
|
||||
])
|
||||
);
|
||||
|
||||
let shared = tree(0, 0).to_string();
|
||||
assert_eq!(
|
||||
shared
|
||||
.lines()
|
||||
.filter(|line| line.ends_with("Input source=0 raw samples"))
|
||||
.count(),
|
||||
2,
|
||||
"{shared}"
|
||||
);
|
||||
assert_ne!(
|
||||
shared, distinct,
|
||||
"two trees differ in the child each input reads"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -266,7 +342,7 @@ fn a_scalar_and_an_instant_line_show_what_they_hold() {
|
||||
shown(&[
|
||||
"NativeTree",
|
||||
" root Instant lookback 300000ms offset 60000 on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -301,7 +377,7 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
"NativeTree",
|
||||
" root Aggregate sum by [job] complete",
|
||||
" input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
|
||||
@@ -339,7 +415,7 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
" root Binary + ignoring [] one-to-one",
|
||||
" left Scalar 2",
|
||||
" right Window rate [300000ms] offset 0 anchor - on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
|
||||
@@ -392,7 +468,7 @@ fn a_without_grouping_does_not_read_as_by() {
|
||||
"NativeTree",
|
||||
" root Aggregate sum without [job] complete",
|
||||
" input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -384,6 +384,10 @@ struct NodeSpec {
|
||||
/// The index of this node's input, which is the node the build pass reaches next: the one
|
||||
/// input of a unary node, the left operand of a binary node, and none for an input node.
|
||||
input: Option<usize>,
|
||||
/// The index of the input source an input node reads; `None` for every other node.
|
||||
///
|
||||
/// The index is local to this execution, and several inputs may carry the same one.
|
||||
source_index: Option<usize>,
|
||||
}
|
||||
|
||||
/// The series whose first chunk this buffer received and whose closing chunk it has not seen.
|
||||
@@ -2885,6 +2889,7 @@ pub struct NativeExecutionState {
|
||||
///
|
||||
/// A tree of unary nodes has one, and a binary node adds one per operand: a tree of nested
|
||||
/// binary nodes has as many as it has leaves, and a queued chunk names the one it belongs to.
|
||||
/// Several of them may share a `NodeSpec::source_index`, so one source's chunk feeds them all.
|
||||
sources: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -3129,9 +3134,15 @@ impl NativeExecutionState {
|
||||
true
|
||||
}
|
||||
};
|
||||
// The source an input reads; every other node is fed by the one its spec names.
|
||||
let source_index = match &node.expr {
|
||||
NativeExpr::Input(bound) => Some(bound.source_index),
|
||||
_ => None,
|
||||
};
|
||||
nodes.push(NodeSpec {
|
||||
tag,
|
||||
input: reads_input.then_some(index + 1),
|
||||
source_index,
|
||||
});
|
||||
exprs.push(&node.expr);
|
||||
paths.push(path.clone());
|
||||
@@ -3557,6 +3568,20 @@ impl NativeExecutor {
|
||||
self.push_source(Some(path), NativeChunk::Raw(chunk))
|
||||
}
|
||||
|
||||
/// Queues one raw source chunk at every input bound to source `source_index`.
|
||||
///
|
||||
/// The index is local to this execution, and several inputs may name one source: each of them
|
||||
/// gets the chunk -- all but the last from a copy. The inputs of one index have to read the
|
||||
/// same raw samples, and an index no input names is refused; either stops the execution.
|
||||
pub fn push_raw_source(&mut self, source_index: usize, chunk: RawSeriesChunk) -> Result<()> {
|
||||
self.check_running()?;
|
||||
let result = self.queue_raw_source(source_index, chunk);
|
||||
if let Err(error) = &result {
|
||||
self.stop(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Queues one evaluated source chunk at the input node at `path`.
|
||||
pub fn push_evaluated_at(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result<()> {
|
||||
self.push_source(Some(path), NativeChunk::Evaluated(chunk))
|
||||
@@ -4097,6 +4122,76 @@ impl NativeExecutor {
|
||||
/// Queues a source chunk at one input node, checking it against that input's binding.
|
||||
fn queue_source(&mut self, path: Option<&NodePath>, chunk: NativeChunk) -> Result<()> {
|
||||
let source = self.source_index(path)?;
|
||||
self.queue_source_at(source, chunk)
|
||||
}
|
||||
|
||||
/// Queues one raw source chunk at every input bound to source `source_index`, in traversal
|
||||
/// order: the last of them takes the caller's chunk, the ones before it a copy.
|
||||
fn queue_raw_source(&mut self, source_index: usize, chunk: RawSeriesChunk) -> Result<()> {
|
||||
let last = self
|
||||
.state
|
||||
.sources
|
||||
.iter()
|
||||
.rposition(|&source| self.state.nodes[source].source_index == Some(source_index))
|
||||
.ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"the native execution has no input bound to source {source_index}"
|
||||
))
|
||||
})?;
|
||||
// One chunk reaches every one of them, so they have to read the same raw samples: an input
|
||||
// of another layout, or one over an evaluated series, cannot take it. The check runs before
|
||||
// the first copy is queued, so a refusal leaves no input holding one.
|
||||
let mut baseline: Option<(usize, Arc<SeriesSchema>)> = None;
|
||||
for &source in &self.state.sources[..=last] {
|
||||
if self.state.nodes[source].source_index != Some(source_index) {
|
||||
continue;
|
||||
}
|
||||
let at = &self.state.paths[source];
|
||||
let schema = self.state.runtimes[source]
|
||||
.source_schema
|
||||
.clone()
|
||||
.ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"the input node at {at} does not produce samples"
|
||||
))
|
||||
})?;
|
||||
if schema.eval_grid.is_some() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"the native source {source_index} hands over raw samples, but the input at {at} \
|
||||
reads an evaluated series"
|
||||
)));
|
||||
}
|
||||
match &baseline {
|
||||
None => baseline = Some((source, schema)),
|
||||
Some((first, bound)) => {
|
||||
if !schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| &field.name)
|
||||
.eq(bound.fields.iter().map(|field| &field.name))
|
||||
{
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"the native source {source_index} feeds two layouts: the inputs at {} \
|
||||
and {at} differ in their fields",
|
||||
self.state.paths[*first]
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for position in 0..last {
|
||||
let source = self.state.sources[position];
|
||||
if self.state.nodes[source].source_index != Some(source_index) {
|
||||
continue;
|
||||
}
|
||||
self.queue_source_at(source, NativeChunk::Raw(chunk.clone()))?;
|
||||
}
|
||||
let source = self.state.sources[last];
|
||||
self.queue_source_at(source, NativeChunk::Raw(chunk))
|
||||
}
|
||||
|
||||
/// Queues a source chunk at the input node at `source`, checking it against its binding.
|
||||
fn queue_source_at(&mut self, source: usize, chunk: NativeChunk) -> Result<()> {
|
||||
let at = &self.state.paths[source];
|
||||
let Some(binding) = self.state.runtimes[source].source_schema.as_ref() else {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
|
||||
@@ -107,9 +107,17 @@ fn input() -> NativeNode {
|
||||
|
||||
/// The same raw source, declaring `ordering`.
|
||||
fn raw_input_with_ordering(ordering: SeriesOrdering) -> NativeNode {
|
||||
raw_input_from(0, ordering)
|
||||
}
|
||||
|
||||
/// A raw source bound to input source `source_index`, declaring `ordering`.
|
||||
///
|
||||
/// Two nodes built from one index read the same source: a chunk queued for it reaches both.
|
||||
fn raw_input_from(source_index: usize, ordering: SeriesOrdering) -> NativeNode {
|
||||
let output = NativeType::Samples(raw_schema());
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: output.clone(),
|
||||
ordering,
|
||||
}),
|
||||
@@ -122,6 +130,7 @@ fn raw_input_of(count: usize) -> NativeNode {
|
||||
let output = NativeType::Samples(raw_schema_of(field_count(count)));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -139,6 +148,7 @@ fn evaluated_input_with_ordering(grid: Arc<EvalGrid>, ordering: SeriesOrdering)
|
||||
let output = evaluated(grid);
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering,
|
||||
}),
|
||||
@@ -4207,6 +4217,7 @@ fn evaluated_input_of(count: usize, grid: Arc<EvalGrid>) -> NativeNode {
|
||||
}));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -5869,6 +5880,341 @@ fn a_queued_chunk_names_its_input() {
|
||||
assert_eq!(left, NodePath::root().left());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source routing: one input source, one or more inputs reading it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One queued chunk of a shared source reaches every input bound to it.
|
||||
///
|
||||
/// Both inputs read source 0, and the subtraction is not commutative: the right selection reads one
|
||||
/// step earlier, so a chunk that reached one input only would not produce this answer.
|
||||
#[test]
|
||||
fn a_raw_source_feeds_every_input_bound_to_it() {
|
||||
let out = grid(0, 60_000, 3);
|
||||
let shared = |source_index: usize| raw_input_from(source_index, SeriesOrdering::KeyThenTime);
|
||||
let tree = NativeTree::try_new(binary_of(
|
||||
instant(shared(0), 1, 0, Arc::clone(&out)),
|
||||
instant(shared(0), 60_000, 60_000, Arc::clone(&out)),
|
||||
binary_matching(BinaryOp::Sub),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let pool = pool();
|
||||
let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new());
|
||||
execution
|
||||
.push_raw_source(
|
||||
0,
|
||||
raw_chunk(
|
||||
&raw_schema(),
|
||||
&[0, 60_000, 120_000],
|
||||
&[1.0, 10.0, 100.0],
|
||||
true,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// p0 has no earlier sample for the right side, so the subtraction decides p1 and p2 only.
|
||||
assert_eq!(
|
||||
decided(&run(&mut execution)),
|
||||
vec![(1, Some(9.0)), (2, Some(90.0))]
|
||||
);
|
||||
// Both nodes were handed the same chunk, and each copy was released with its node.
|
||||
assert_eq!(execution.state().reserved_bytes(), 0);
|
||||
assert_eq!(pool.reserved(), 0);
|
||||
}
|
||||
|
||||
/// Inputs bound to different sources are fed separately: a chunk reaches only the inputs bound to
|
||||
/// the index it was queued at.
|
||||
#[test]
|
||||
fn a_raw_source_reaches_only_the_inputs_bound_to_it() {
|
||||
let out = grid(0, 60_000, 2);
|
||||
let source = |source_index: usize| raw_input_from(source_index, SeriesOrdering::KeyThenTime);
|
||||
let tree = NativeTree::try_new(binary_of(
|
||||
instant(source(0), 1, 0, Arc::clone(&out)),
|
||||
instant(source(1), 1, 0, Arc::clone(&out)),
|
||||
binary_matching(BinaryOp::Add),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let schema = raw_schema();
|
||||
let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new());
|
||||
execution
|
||||
.push_raw_source(
|
||||
0,
|
||||
raw_chunk_of(
|
||||
&schema,
|
||||
b"series-a",
|
||||
metric(),
|
||||
&[0, 60_000],
|
||||
&[1.0, 2.0],
|
||||
true,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
execution
|
||||
.push_raw_source(
|
||||
1,
|
||||
raw_chunk_of(
|
||||
&schema,
|
||||
b"series-b",
|
||||
metric(),
|
||||
&[0, 60_000],
|
||||
&[10.0, 20.0],
|
||||
true,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// The two sources hold one series each, and the add pairs them.
|
||||
assert_eq!(
|
||||
decided(&run(&mut execution)),
|
||||
vec![(0, Some(11.0)), (1, Some(22.0))]
|
||||
);
|
||||
}
|
||||
|
||||
/// A chunk queued for a source no input is bound to is refused, and the execution stops holding
|
||||
/// anything, like any other refused chunk.
|
||||
#[test]
|
||||
fn a_chunk_for_an_unknown_source_stops_the_execution() {
|
||||
let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap();
|
||||
let pool = pool();
|
||||
let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new());
|
||||
let schema = raw_schema();
|
||||
|
||||
// The tree's one input is bound to source 0, so the queued chunk is held for it.
|
||||
execution
|
||||
.push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true))
|
||||
.unwrap();
|
||||
assert!(pool.reserved() > 0, "the queued chunk reserved nothing");
|
||||
|
||||
// Source 7 is read by no input of this tree: the chunk has nowhere to go, and reporting that
|
||||
// must not leave the chunk already queued charged to the pool.
|
||||
let error = execution
|
||||
.push_raw_source(7, raw_chunk(&schema, &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("no input bound to source 7"),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(pool.reserved(), 0, "the stopped execution kept its queue");
|
||||
assert_eq!(execution.state().reserved_bytes(), 0);
|
||||
|
||||
// The execution stopped rather than waiting for another chunk, so even a source it knows is
|
||||
// refused from here on.
|
||||
let again = execution
|
||||
.push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
again.to_string().contains("stopped after an earlier error"),
|
||||
"{again}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared source whose second copy the pool refuses stops the execution and gives the first back.
|
||||
///
|
||||
/// Both inputs here read source 0, so one queued chunk is held by two queues: a budget of one copy
|
||||
/// admits the first queue and refuses the second, which leaves a copy already queued when the
|
||||
/// handover fails. Nothing of it may be handed out, and its bytes must go back while the executor
|
||||
/// is alive.
|
||||
#[test]
|
||||
fn a_refused_copy_of_a_shared_source_stops_the_execution() {
|
||||
let out = grid(0, 60_000, 1);
|
||||
let shared = || raw_input_from(0, SeriesOrdering::KeyThenTime);
|
||||
let tree = NativeTree::try_new(binary_of(
|
||||
instant(shared(), 1, 0, Arc::clone(&out)),
|
||||
instant(shared(), 1, 0, Arc::clone(&out)),
|
||||
binary_matching(BinaryOp::Add),
|
||||
))
|
||||
.unwrap();
|
||||
let schema = raw_schema();
|
||||
let chunk = raw_chunk(&schema, &[0], &[1.0], true);
|
||||
|
||||
// What one input charges for the chunk, which is the figure its queue grows by. The unbounded
|
||||
// pool holds exactly one copy per input and nothing before them, so that figure is the budget
|
||||
// that admits the first copy and refuses the second.
|
||||
let one = raw_bytes(&chunk);
|
||||
let reference = pool();
|
||||
let mut measured = executor(
|
||||
&tree,
|
||||
Arc::clone(&reference),
|
||||
&ExecutionPlanMetricsSet::new(),
|
||||
);
|
||||
assert_eq!(
|
||||
measured.state().reserved_bytes(),
|
||||
0,
|
||||
"the tree holds bytes before its input"
|
||||
);
|
||||
measured.push_raw_source(0, chunk.clone()).unwrap();
|
||||
assert_eq!(
|
||||
reference.reserved(),
|
||||
2 * one,
|
||||
"one handover is not held once per input"
|
||||
);
|
||||
|
||||
let pool = bounded_pool(one);
|
||||
let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new());
|
||||
let error = execution.push_raw_source(0, chunk).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, DataFusionError::ResourcesExhausted(_)),
|
||||
"{error}"
|
||||
);
|
||||
// The copy queued first is the left input's and the refused one the right's, so the handover
|
||||
// reached one input and no further.
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains(NodePath::root().right().input().as_str()),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(pool.reserved(), 0, "the stopped execution kept the copy");
|
||||
assert_eq!(execution.state().reserved_bytes(), 0);
|
||||
|
||||
// The half-fed tree hands nothing out, and another chunk of the same source is refused.
|
||||
let pulled = execution.next_chunk().unwrap_err();
|
||||
assert!(
|
||||
pulled
|
||||
.to_string()
|
||||
.contains("stopped after an earlier error"),
|
||||
"{pulled}"
|
||||
);
|
||||
let again = execution
|
||||
.push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
again.to_string().contains("stopped after an earlier error"),
|
||||
"{again}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Two layouts on one source index are refused before either input is handed a copy.
|
||||
///
|
||||
/// One queued chunk is the same columns for every input it reaches, so `[a, b]` and `[b, a]` --
|
||||
/// equal in width, different in order -- cannot share a handover. Nothing is queued, so neither
|
||||
/// input reports a batch nor reserves a byte, and the execution does not continue.
|
||||
#[test]
|
||||
fn a_shared_source_of_two_layouts_is_refused_before_any_copy() {
|
||||
let out = grid(0, 60_000, 1);
|
||||
let layout = |names: [&str; 2]| {
|
||||
let fields: Arc<[FieldSpec]> = names
|
||||
.iter()
|
||||
.map(|name| FieldSpec {
|
||||
name: (*name).into(),
|
||||
})
|
||||
.collect();
|
||||
let schema = raw_schema_of(fields);
|
||||
let output = NativeType::Samples(Arc::clone(&schema));
|
||||
let node = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
output,
|
||||
};
|
||||
(schema, node)
|
||||
};
|
||||
let (schema, left) = layout(["a", "b"]);
|
||||
let (_, right) = layout(["b", "a"]);
|
||||
let tree = NativeTree::try_new(binary_of(
|
||||
instant(left, 1, 0, Arc::clone(&out)),
|
||||
instant(right, 1, 0, Arc::clone(&out)),
|
||||
binary_matching(BinaryOp::Add),
|
||||
))
|
||||
.unwrap();
|
||||
let set = ExecutionPlanMetricsSet::new();
|
||||
let pool = pool();
|
||||
let mut execution = executor(&tree, Arc::clone(&pool), &set);
|
||||
let error = execution
|
||||
.push_raw_source(0, raw_chunk_repeated(&schema, &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, DataFusionError::Execution(_)),
|
||||
"a layout mismatch was answered by the pool: {error}"
|
||||
);
|
||||
assert!(
|
||||
error.to_string().contains("source 0 feeds two layouts"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains(NodePath::root().right().input().as_str()),
|
||||
"the refusal does not name the conflicting input: {error}"
|
||||
);
|
||||
|
||||
// The check ran before the first copy, so neither input took the chunk.
|
||||
for path in [
|
||||
NodePath::root().left().input(),
|
||||
NodePath::root().right().input(),
|
||||
] {
|
||||
assert_eq!(count(&set, &path, NodeMetric::INPUT_BATCHES), 0, "{path}");
|
||||
}
|
||||
assert_eq!(pool.reserved(), 0, "a refused handover queued a copy");
|
||||
assert_eq!(execution.state().reserved_bytes(), 0);
|
||||
|
||||
// The execution stopped instead of waiting for a source it can feed.
|
||||
let again = execution
|
||||
.push_raw_source(0, raw_chunk_repeated(&schema, &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
again.to_string().contains("stopped after an earlier error"),
|
||||
"{again}"
|
||||
);
|
||||
assert!(execution.next_chunk().is_err(), "a stopped tree answered");
|
||||
}
|
||||
|
||||
/// A raw and an evaluated input on one source index are refused before either is fed.
|
||||
///
|
||||
/// `push_raw_source` hands raw chunks to every input it names, so an input bound to an evaluated
|
||||
/// series has no way to take one: the handover is refused whole, and the raw side keeps nothing.
|
||||
#[test]
|
||||
fn a_raw_and_an_evaluated_input_on_one_source_are_refused() {
|
||||
let out = grid(0, 60_000, 1);
|
||||
let tree = NativeTree::try_new(binary_of(
|
||||
instant(
|
||||
raw_input_from(0, SeriesOrdering::KeyThenTime),
|
||||
1,
|
||||
0,
|
||||
Arc::clone(&out),
|
||||
),
|
||||
evaluated_input_with_ordering(Arc::clone(&out), SeriesOrdering::KeyThenTime),
|
||||
binary_matching(BinaryOp::Add),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let set = ExecutionPlanMetricsSet::new();
|
||||
let pool = pool();
|
||||
let mut execution = executor(&tree, Arc::clone(&pool), &set);
|
||||
let error = execution
|
||||
.push_raw_source(0, raw_chunk(&raw_schema(), &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("the input at root.right reads an evaluated series"),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&set,
|
||||
&NodePath::root().left().input(),
|
||||
NodeMetric::INPUT_BATCHES
|
||||
),
|
||||
0,
|
||||
"the raw side took a copy of a refused handover"
|
||||
);
|
||||
assert_eq!(pool.reserved(), 0);
|
||||
assert_eq!(execution.state().reserved_bytes(), 0);
|
||||
|
||||
let again = execution
|
||||
.push_raw_source(0, raw_chunk(&raw_schema(), &[0], &[1.0], true))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
again.to_string().contains("stopped after an earlier error"),
|
||||
"{again}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A map above a binary, and a window above a binary, pull its result through their own loops.
|
||||
#[test]
|
||||
fn a_binary_beneath_a_map_and_a_window_is_pulled_recursively() {
|
||||
|
||||
@@ -386,6 +386,7 @@ mod tests {
|
||||
let output = NativeType::Samples(schema());
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: datatypes::series::SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
|
||||
@@ -129,6 +129,11 @@ pub struct AggregateStateSchema {
|
||||
/// rejecting an interleaved input; no other consumer reads it yet.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BoundInput {
|
||||
/// The index of the input source, of this execution, whose chunks feed this input.
|
||||
///
|
||||
/// The index is local to one execution: several inputs may name one source, and then share
|
||||
/// every chunk queued for it.
|
||||
pub source_index: usize,
|
||||
/// What the input produces: raw samples from a scan, or state from an exchange boundary.
|
||||
pub output: NativeType,
|
||||
/// The ordering the input guarantees.
|
||||
|
||||
@@ -61,6 +61,7 @@ fn input() -> NativeNode {
|
||||
let output = raw();
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -74,6 +75,7 @@ fn input_on(grid: Arc<EvalGrid>) -> NativeNode {
|
||||
let output = evaluated(Arc::new([]), grid);
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
@@ -89,6 +91,7 @@ fn input_with_fields(count: usize) -> NativeNode {
|
||||
}));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -101,6 +104,7 @@ fn interleaved_input() -> NativeNode {
|
||||
let output = raw();
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::Interleaved,
|
||||
}),
|
||||
@@ -1182,6 +1186,7 @@ fn a_scalar_node_must_produce_a_scalar() {
|
||||
fn an_input_must_report_the_binding_it_was_bound_to() {
|
||||
let node = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: raw(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
@@ -1197,6 +1202,7 @@ fn an_input_can_bind_aggregate_state() {
|
||||
let state = partial_aggregate(window_over(input(), None));
|
||||
let bound = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: state.output.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
@@ -1210,6 +1216,7 @@ fn an_input_can_bind_aggregate_state() {
|
||||
// A fresh state allocation is a different binding, so it cannot be reported as the bound one.
|
||||
let other = NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: state.output.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
|
||||
@@ -111,6 +111,7 @@ fn source(schema: &Arc<SeriesSchema>) -> NativeNode {
|
||||
let output = NativeType::Samples(Arc::clone(schema));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
|
||||
@@ -977,25 +977,10 @@ impl TreeNodeRewriter for EnforceDistRequirementRewriter {
|
||||
fn f_down(&mut self, node: Self::Node) -> DfResult<Transformed<Self::Node>> {
|
||||
// The level bookkeeping below describes one chain of nodes: a level names a node, and a
|
||||
// column requirement is scoped by the level it was recorded at. A node with several inputs
|
||||
// is a branch whose children would all share one level, so the walk stops at the branch
|
||||
// rather than assigning them levels that mean nothing.
|
||||
//
|
||||
// The one branch that is expected here is a fused PromQL node, whose inputs are the region
|
||||
// scans of its selectors: each is the scan itself, with no projection under it that a column
|
||||
// requirement could amend. Any other branch keeps the refusal, because a sub-plan this walk
|
||||
// has not been taught to read is not something to leave half-enforced.
|
||||
// is a branch whose children would all share one level, so the walk refuses it rather than
|
||||
// assigning them levels that mean nothing. Every node this rewriter expands is on one such
|
||||
// chain, and the fused PromQL node is one input over one scan like any other node here.
|
||||
if node.inputs().len() > 1 {
|
||||
if is_fused_series_plan(&node) {
|
||||
self.plan_per_level.insert(self.cur_level, node.clone());
|
||||
// The level still advances, because `f_up` gives it back for this node: a walk that
|
||||
// skipped the increment would leave every node above this one a level too low.
|
||||
self.cur_level += 1;
|
||||
return Ok(Transformed::new(
|
||||
node,
|
||||
false,
|
||||
datafusion_common::tree_node::TreeNodeRecursion::Jump,
|
||||
));
|
||||
}
|
||||
return Err(datafusion_common::DataFusionError::Internal(
|
||||
"EnforceDistRequirementRewriter: node with multiple inputs is not supported"
|
||||
.to_string(),
|
||||
|
||||
@@ -23,14 +23,13 @@ use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
|
||||
use promql::extension_plan::{
|
||||
EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize,
|
||||
};
|
||||
use promql::native::plan::{NativeExpr, NativeNode, reads_across_series};
|
||||
use promql::vector_match::Cardinality;
|
||||
use promql::native::plan::reads_across_series;
|
||||
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};
|
||||
use crate::promql::planner::native::{pointwise_operand, two_occurrences_pair_one_source};
|
||||
|
||||
pub struct StepTransformAction {
|
||||
extra_parent_plans: Vec<LogicalPlan>,
|
||||
@@ -245,21 +244,21 @@ impl Categorizer {
|
||||
}
|
||||
name if name == FusedSeries::name() => {
|
||||
let fused = plan.as_any().downcast_ref::<FusedSeries>().unwrap();
|
||||
// A region builds this node from the region scans themselves: the conversion takes a
|
||||
// A region builds this node from the region scan itself: 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. 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 {
|
||||
// node over anything but one scan has nothing to read where it would be placed and
|
||||
// stays where it was planned. A match over one selector is still one child: the
|
||||
// planner binds both occurrences of it to the one plan they read.
|
||||
let [child] = fused.children() else {
|
||||
return Commutativity::NonCommutative;
|
||||
};
|
||||
let LogicalPlan::TableScan(_) = &input.input else {
|
||||
let LogicalPlan::TableScan(_) = child 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() {
|
||||
let binding = fused.binding();
|
||||
if binding.metric_name.is_none() {
|
||||
return Commutativity::NonCommutative;
|
||||
}
|
||||
// A region evaluates the tree over whatever series its own scan returns, so the tree
|
||||
@@ -271,11 +270,8 @@ impl Categorizer {
|
||||
// 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,
|
||||
};
|
||||
let per_series =
|
||||
pointwise_operand(root) || two_occurrences_pair_one_source(root, &binding.tags);
|
||||
if reads_across_series(root) && !per_series {
|
||||
return Commutativity::NonCommutative;
|
||||
}
|
||||
@@ -402,27 +398,6 @@ impl Categorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `root` pairs the two occurrences one plan feeds point-wise over the whole identity.
|
||||
///
|
||||
/// 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)]
|
||||
mod tests {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -442,11 +417,10 @@ mod tests {
|
||||
use datafusion_optimizer::analyzer::AnalyzerRule;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding};
|
||||
use promql::functions::{
|
||||
NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile,
|
||||
};
|
||||
use promql::native::metrics::NodePath;
|
||||
use promql::native::plan::{NativeExpr, NativeTree};
|
||||
use promql_parser::parser;
|
||||
use store_api::storage::RegionId;
|
||||
@@ -456,6 +430,7 @@ mod tests {
|
||||
use crate::dist_plan::DistPlannerAnalyzer;
|
||||
use crate::optimizer::test_util::mock_table_provider;
|
||||
use crate::promql::native_compile::{compile, compile_selectors, statement_grid};
|
||||
use crate::promql::planner::native::collapsed_pair_tree;
|
||||
use crate::query_engine::DefaultSerializer;
|
||||
|
||||
#[test]
|
||||
@@ -528,23 +503,10 @@ mod tests {
|
||||
.unwrap();
|
||||
let binding = FusedSeriesBinding {
|
||||
grid: statement_grid(&stmt).unwrap(),
|
||||
};
|
||||
// The tree names the destination its selector compiled to, which this test reads off the
|
||||
// tree rather than assuming.
|
||||
let mut paths = Vec::new();
|
||||
promql::native::metrics::walk(tree.root(), &mut |node, path| {
|
||||
if matches!(node.expr, NativeExpr::Input(_)) {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
});
|
||||
let inputs = vec![FusedSeriesInput {
|
||||
series_schema,
|
||||
metric_name: metric_name.map(Arc::from),
|
||||
time_index: "ts".to_string(),
|
||||
tags: Vec::new(),
|
||||
input,
|
||||
paths,
|
||||
}];
|
||||
metric_name: metric_name.map(Arc::from),
|
||||
};
|
||||
let output_schema: DFSchemaRef = Arc::new(
|
||||
DFSchema::new_with_metadata(
|
||||
vec![
|
||||
@@ -572,7 +534,7 @@ mod tests {
|
||||
Arc::from("some_metric"),
|
||||
tree,
|
||||
binding,
|
||||
inputs,
|
||||
vec![input],
|
||||
output_schema,
|
||||
)
|
||||
.unwrap(),
|
||||
@@ -768,13 +730,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
) {
|
||||
fn query_tree(query: &str) -> (NativeTree, promql_parser::parser::EvalStmt) {
|
||||
let stmt = eval_statement(query);
|
||||
let series_schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
@@ -790,39 +746,38 @@ mod tests {
|
||||
.unwrap()
|
||||
.tree
|
||||
};
|
||||
(tree, series_schema, stmt)
|
||||
(tree, stmt)
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
/// The number of raw inputs a tree reads, in walk order.
|
||||
fn tree_input_count(tree: &NativeTree) -> usize {
|
||||
let mut inputs = 0;
|
||||
promql::native::metrics::walk(tree.root(), &mut |node, _| {
|
||||
if matches!(node.expr, NativeExpr::Input(_)) {
|
||||
paths.push(path.clone());
|
||||
inputs += 1;
|
||||
}
|
||||
});
|
||||
paths
|
||||
inputs
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// `one_source` binds both occurrences of a two-occurrence statement to one plan - the shape
|
||||
/// the planner collapses to, with both tree inputs numbered after that child - and otherwise
|
||||
/// gives every occurrence its own plan.
|
||||
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 (tree, stmt) = query_tree(query);
|
||||
let input_count = tree_input_count(&tree);
|
||||
let (tree, children) = match (one_source, input_count) {
|
||||
// A statement that names its selector once reads one child already.
|
||||
(_, 1) => (tree, vec![table_scan_plan()]),
|
||||
// Both occurrences read the one plan the planner collapsed them onto.
|
||||
(true, _) => (
|
||||
collapsed_pair_tree(&tree).expect("the fixture is a two-occurrence pair"),
|
||||
vec![table_scan_plan()],
|
||||
),
|
||||
// Every occurrence reads a plan of its own.
|
||||
(false, _) => (tree, (0..input_count).map(|_| table_scan_plan()).collect()),
|
||||
};
|
||||
let output_schema: DFSchemaRef = Arc::new(
|
||||
DFSchema::new_with_metadata(
|
||||
@@ -851,8 +806,11 @@ mod tests {
|
||||
tree,
|
||||
FusedSeriesBinding {
|
||||
grid: statement_grid(&stmt).unwrap(),
|
||||
time_index: "ts".to_string(),
|
||||
tags: tags.iter().map(|tag| (*tag).to_string()).collect(),
|
||||
metric_name: Some(Arc::from("some_metric")),
|
||||
},
|
||||
inputs,
|
||||
children,
|
||||
output_schema,
|
||||
)
|
||||
.unwrap(),
|
||||
@@ -900,8 +858,9 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node that lists its raw inputs as two bindings reads two plans, and a region has nothing
|
||||
/// to build for it.
|
||||
/// A node over two children reads two plans, and a region has nothing to build for it: the
|
||||
/// planner collapses a pair onto one child, so this is the shape that keeps the node where it
|
||||
/// was planned rather than a match one region cannot answer.
|
||||
#[test]
|
||||
fn fused_series_over_two_actual_scans_is_not_commutative() {
|
||||
let plan = occurrence_plan("some_metric + on(host) some_metric", &["host"], false);
|
||||
@@ -930,16 +889,21 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// root or sits below a map.
|
||||
///
|
||||
/// Each case below reads one scan, which is the only shape such a tree can have here: a
|
||||
/// two-occurrence statement is collapsed onto one child only when both of its operands are
|
||||
/// point-wise, and the planner refuses the pair otherwise. The categorizer reads the same
|
||||
/// predicate ([`two_occurrences_pair_one_source`]) the planner admits with, so it cannot place
|
||||
/// a pair the planner declined — that case is covered where the query falls back.
|
||||
#[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),
|
||||
for query in [
|
||||
"sort(some_metric)",
|
||||
"sum(some_metric)",
|
||||
"abs(sort(some_metric)) * 2",
|
||||
] {
|
||||
let plan = occurrence_plan(query, &["host"], one_source);
|
||||
let plan = occurrence_plan(query, &["host"], true);
|
||||
assert!(
|
||||
matches!(commutativity_of(&plan), Commutativity::NonCommutative),
|
||||
"{query}"
|
||||
|
||||
@@ -497,9 +497,7 @@ mod test {
|
||||
use datatypes::schema::ColumnSchema;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::extension_plan::{
|
||||
FusedSeries, FusedSeriesBinding, FusedSeriesInput, RangeManipulate,
|
||||
};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, RangeManipulate};
|
||||
use promql_parser::parser;
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
|
||||
@@ -1585,23 +1583,10 @@ mod test {
|
||||
.unwrap();
|
||||
let binding = FusedSeriesBinding {
|
||||
grid: statement_grid(&stmt).unwrap(),
|
||||
};
|
||||
// The tree names the destination its selector compiled to, which this test reads off the
|
||||
// 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(_)) {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
});
|
||||
let inputs = vec![FusedSeriesInput {
|
||||
series_schema,
|
||||
metric_name: Some("some_metric".into()),
|
||||
time_index: "ts".to_string(),
|
||||
tags: Vec::new(),
|
||||
input,
|
||||
paths,
|
||||
}];
|
||||
metric_name: Some(Arc::from("some_metric")),
|
||||
};
|
||||
let output_schema: DFSchemaRef = Arc::new(
|
||||
DFSchema::new_with_metadata(
|
||||
vec![
|
||||
@@ -1626,7 +1611,7 @@ mod test {
|
||||
Arc::from("some_metric"),
|
||||
tree,
|
||||
binding,
|
||||
inputs,
|
||||
vec![input],
|
||||
output_schema,
|
||||
)
|
||||
.unwrap(),
|
||||
|
||||
@@ -226,6 +226,13 @@ impl SelectorRequirement {
|
||||
}
|
||||
|
||||
/// One input a compiled tree reads, and the selector it was bound to.
|
||||
///
|
||||
/// The record describes the scan side of one occurrence: what the selector asked a scan for and
|
||||
/// which layout it was bound to. The tree side is the input node at [`path`](Self::path), whose
|
||||
/// `source_index` names the input source its chunks come from — an index local to one execution of
|
||||
/// the tree, not an identity any enclosing plan assigns. That index is not mirrored here: an
|
||||
/// occurrence's position in this list is the index the compiler gave its node, and a caller that
|
||||
/// collapses two occurrences onto one source rewrites the node rather than another record.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CompiledInput {
|
||||
/// Where the executor reads this input in the compiled tree.
|
||||
@@ -331,6 +338,13 @@ pub fn compile(
|
||||
/// Each selector's path is recorded as its recursive node is compiled, so its requirement and
|
||||
/// schema stay structurally paired with the input the executor names at that position; the finished
|
||||
/// tree is then walked once to check that pairing ([`validate_inputs`]).
|
||||
///
|
||||
/// Each input node also carries a `source_index`, naming which input source of one execution its
|
||||
/// chunks come from. The compiler numbers occurrences in binding order from zero, so the i-th
|
||||
/// selector compiled reads input source i, and `x + x` binds two indices even when both occurrences
|
||||
/// are fed one schema. How those indices map onto a caller's actual sources is the caller's to
|
||||
/// say — the fused planner, for one, proves that two occurrences read one scan and rebinds them to
|
||||
/// the single child position it prepared.
|
||||
pub fn compile_selectors(
|
||||
stmt: &EvalStmt,
|
||||
bindings: &dyn Fn(&SelectorRequirement) -> Result<Arc<SeriesSchema>>,
|
||||
@@ -1166,7 +1180,7 @@ fn window_selection(
|
||||
|
||||
// A range function reports one value per input field, so the layout is the input's.
|
||||
let (start_ms, end_ms) = grid_endpoints(&output_grid)?;
|
||||
let raw_schema = bind_selector(
|
||||
let (source_index, raw_schema) = bind_selector(
|
||||
context,
|
||||
SelectorRequirement {
|
||||
metric: vs.name.clone(),
|
||||
@@ -1192,6 +1206,7 @@ fn window_selection(
|
||||
expr: NativeExpr::Window {
|
||||
input: Box::new(NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: raw.clone(),
|
||||
ordering: context.ordering,
|
||||
}),
|
||||
@@ -1351,7 +1366,7 @@ fn instant_selection(context: &Context, selector: &VectorSelector) -> Result<Nat
|
||||
|
||||
// An instant selection reports one value per input field, so the layout is the input's.
|
||||
let (start_ms, end_ms) = grid_endpoints(&output_grid)?;
|
||||
let raw_schema = bind_selector(
|
||||
let (source_index, raw_schema) = bind_selector(
|
||||
context,
|
||||
SelectorRequirement {
|
||||
metric: selector.name.clone(),
|
||||
@@ -1376,6 +1391,7 @@ fn instant_selection(context: &Context, selector: &VectorSelector) -> Result<Nat
|
||||
expr: NativeExpr::Instant {
|
||||
input: Box::new(NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: raw.clone(),
|
||||
ordering: context.ordering,
|
||||
}),
|
||||
@@ -1396,15 +1412,27 @@ fn instant_selection(context: &Context, selector: &VectorSelector) -> Result<Nat
|
||||
/// The callback decides one thing — what a scan of this selector produces — while the requirement
|
||||
/// records what the selector named, how it shifts time and which points it is read at. The input
|
||||
/// path is carried through recursive compilation, so the binding is paired with its tree node here.
|
||||
fn bind_selector(context: &Context, requirement: SelectorRequirement) -> Result<Arc<SeriesSchema>> {
|
||||
///
|
||||
/// The returned index is the occurrence's position in binding order, which its input node carries
|
||||
/// as [`BoundInput::source_index`]: the input source that node's chunks come from, local to one
|
||||
/// execution of the tree. It is read off the record list rather than kept in a counter, so the
|
||||
/// record a selector appends and the index its node names cannot drift apart. Two occurrences of one
|
||||
/// selector are numbered separately here — a compiler describes occurrences — and a caller that
|
||||
/// proves two of them read one source rebinds their nodes to that source.
|
||||
fn bind_selector(
|
||||
context: &Context,
|
||||
requirement: SelectorRequirement,
|
||||
) -> Result<(usize, Arc<SeriesSchema>)> {
|
||||
let schema = (context.bindings)(&requirement)?;
|
||||
context.inputs.borrow_mut().push(CompiledInput {
|
||||
let mut inputs = context.inputs.borrow_mut();
|
||||
let source_index = inputs.len();
|
||||
inputs.push(CompiledInput {
|
||||
path: context.path.input(),
|
||||
requirement,
|
||||
schema: Arc::clone(&schema),
|
||||
ordering: context.ordering,
|
||||
});
|
||||
Ok(schema)
|
||||
Ok((source_index, schema))
|
||||
}
|
||||
|
||||
/// The first and last point of `grid`, as milliseconds since the Unix epoch.
|
||||
|
||||
@@ -1050,7 +1050,7 @@ fn the_display_of_a_compiled_tree_is_the_tree() {
|
||||
[
|
||||
"NativeTree",
|
||||
" root Window rate [300000ms] offset 0 anchor - on grid 0/5000x21",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
]
|
||||
.join("\n")
|
||||
);
|
||||
@@ -1069,7 +1069,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() {
|
||||
" root Aggregate sum by [job] complete",
|
||||
" input Binary * ignoring [] one-to-one",
|
||||
" left Window rate [300000ms] offset 0 anchor - on grid 0/5000x21",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
" right Scalar 100",
|
||||
],
|
||||
),
|
||||
@@ -1080,7 +1080,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() {
|
||||
" root Binary * ignoring [] one-to-one",
|
||||
" left Scalar -1",
|
||||
" right Instant lookback 5000ms offset 0 on grid 0/5000x21",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
],
|
||||
),
|
||||
(
|
||||
@@ -1090,7 +1090,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() {
|
||||
" root Binary < ignoring [] one-to-one",
|
||||
" left Scalar 0",
|
||||
" right Instant lookback 5000ms offset 0 on grid 0/5000x21",
|
||||
" input Input raw samples",
|
||||
" input Input source=0 raw samples",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -4507,6 +4507,7 @@ fn selector_binding_returns_requirement_and_input_path() {
|
||||
panic!("inner expression is not a window");
|
||||
};
|
||||
let NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: NativeType::Samples(bound_schema),
|
||||
ordering,
|
||||
}) = &window_input.expr
|
||||
@@ -4518,6 +4519,8 @@ fn selector_binding_returns_requirement_and_input_path() {
|
||||
};
|
||||
assert!(Arc::ptr_eq(bound_schema, &schema));
|
||||
assert_eq!(*ordering, SeriesOrdering::KeyThenTime);
|
||||
// The only selector of the statement read the first child of the final tree.
|
||||
assert_eq!(*source_index, 0);
|
||||
}
|
||||
|
||||
/// Scan bounds follow the grid the selector is actually evaluated on, open a window's lower edge, and
|
||||
@@ -4776,11 +4779,12 @@ fn vector_binary_inputs_follow_structural_paths() {
|
||||
let mut tree_inputs = Vec::new();
|
||||
walk(compiled.tree.root(), &mut |node, path| {
|
||||
if let NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: NativeType::Samples(schema),
|
||||
ordering,
|
||||
}) = &node.expr
|
||||
{
|
||||
tree_inputs.push((path.clone(), Arc::clone(schema), *ordering));
|
||||
tree_inputs.push((path.clone(), Arc::clone(schema), *ordering, *source_index));
|
||||
}
|
||||
});
|
||||
assert_eq!(tree_inputs.len(), expected.len());
|
||||
@@ -4791,10 +4795,13 @@ fn vector_binary_inputs_follow_structural_paths() {
|
||||
assert_eq!(bound.requirement.metric.as_deref(), Some(*metric));
|
||||
assert!(Arc::ptr_eq(&bound.schema, &schemas[*schema_index]));
|
||||
assert_eq!(bound.ordering, SeriesOrdering::KeyThenTime);
|
||||
let (tree_path, tree_schema, tree_ordering) = &tree_inputs[index];
|
||||
let (tree_path, tree_schema, tree_ordering, source_index) = &tree_inputs[index];
|
||||
assert_eq!(tree_path.as_str(), *expected_path);
|
||||
assert!(Arc::ptr_eq(tree_schema, &bound.schema));
|
||||
assert_eq!(*tree_ordering, bound.ordering);
|
||||
// The selectors are numbered in the order they were bound, which is the order this test
|
||||
// lists them in: `x + y`, then `z`.
|
||||
assert_eq!(*source_index, *schema_index);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4850,20 +4857,28 @@ fn selector_bindings_follow_structural_input_paths() {
|
||||
let mut tree_inputs = Vec::new();
|
||||
walk(compiled.tree.root(), &mut |node, path| {
|
||||
if let NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
output: NativeType::Samples(bound_schema),
|
||||
ordering,
|
||||
}) = &node.expr
|
||||
{
|
||||
tree_inputs.push((path.clone(), Arc::clone(bound_schema), *ordering));
|
||||
tree_inputs.push((
|
||||
path.clone(),
|
||||
Arc::clone(bound_schema),
|
||||
*ordering,
|
||||
*source_index,
|
||||
));
|
||||
}
|
||||
});
|
||||
assert_eq!(tree_inputs.len(), compiled.inputs.len(), "query: {query}");
|
||||
for ((path, tree_schema, tree_ordering), bound) in
|
||||
for ((path, tree_schema, tree_ordering, source_index), bound) in
|
||||
tree_inputs.iter().zip(compiled.inputs.iter())
|
||||
{
|
||||
assert_eq!(path, &bound.path, "query: {query}");
|
||||
assert!(Arc::ptr_eq(tree_schema, &bound.schema), "query: {query}");
|
||||
assert_eq!(*tree_ordering, bound.ordering, "query: {query}");
|
||||
// One selector: the statement's only occurrence reads the first child.
|
||||
assert_eq!(*source_index, 0, "query: {query}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4926,3 +4941,35 @@ fn recorded_inputs_are_exactly_the_trees_input_nodes() {
|
||||
assert!(matches!(error, DataFusionError::Internal(_)), "{error}");
|
||||
assert!(error.to_string().contains("not its input nodes"), "{error}");
|
||||
}
|
||||
|
||||
/// The compiler numbers each input node by the occurrence it was bound for, from zero.
|
||||
///
|
||||
/// The number is what the executor reads a chunk from, so it describes occurrences rather than
|
||||
/// scans: `x + x` names one selector twice and binds two children, which is why a caller that
|
||||
/// proves both occurrences read one scan rebinds their nodes rather than trusting the numbering.
|
||||
#[test]
|
||||
fn input_nodes_are_numbered_by_binding_order_from_zero() {
|
||||
for (query, expected) in [
|
||||
("x", vec![0]),
|
||||
("rate(x[5m])", vec![0]),
|
||||
("abs(x) * 2", vec![0]),
|
||||
("x + y", vec![0, 1]),
|
||||
("x + x", vec![0, 1]),
|
||||
("(x + y) / z", vec![0, 1, 2]),
|
||||
("x + y * z", vec![0, 1, 2]),
|
||||
] {
|
||||
let compiled = compile_selectors(
|
||||
&eval_stmt(query),
|
||||
&|_| Ok(raw_schema()),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
.unwrap_or_else(|error| panic!("`{query}` was refused: {error}"));
|
||||
let mut indices = Vec::new();
|
||||
walk(compiled.tree.root(), &mut |node, _| {
|
||||
if let NativeExpr::Input(BoundInput { source_index, .. }) = &node.expr {
|
||||
indices.push(*source_index);
|
||||
}
|
||||
});
|
||||
assert_eq!(indices, expected, "query: {query}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,14 @@
|
||||
//! the normal answer: every shape the compiler does not accept, and every query this route cannot
|
||||
//! bind to a scan faithfully, keeps the plan the existing planner builds.
|
||||
//!
|
||||
//! What the node needs from here is three things the existing planner already resolves: the raw
|
||||
//! series schema the tree's input was compiled against (the selector's selected field columns), the
|
||||
//! statement's evaluation grid, and the logical tag names the output carries. The output schema is
|
||||
//! built to the shape the existing unary pipeline produces — the time index, then the series
|
||||
//! fields, then the tags — so a node planned here can be consumed by the same code that consumes a
|
||||
//! `SeriesNormalize` output.
|
||||
//! What the node needs from here is what the existing planner already resolves: the selector's own
|
||||
//! table scan with its matchers and compiled time bounds pushed down, the statement's evaluation
|
||||
//! grid, and the columns a series is reported under — the time index, the tags and the metric name.
|
||||
//! The tree's inputs are numbered, and each number is the position of the child whose chunks that
|
||||
//! input reads; a statement whose two occurrences were proven to read one scan is planned with that
|
||||
//! one child and both inputs rebound to it. The output schema is built to the shape the existing
|
||||
//! unary pipeline produces — the time index, then the series fields, then the tags — so a node
|
||||
//! planned here can be consumed by the same code that consumes a `SeriesNormalize` output.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
@@ -39,7 +41,7 @@ use datafusion::prelude::Expr as DfExpr;
|
||||
use datafusion_expr::Expr;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput};
|
||||
use promql::extension_plan::{FusedSeries, FusedSeriesBinding};
|
||||
use promql::native::plan::{NativeExpr, NativeNode, NativeTree, reads_across_series};
|
||||
use promql::vector_match::{Cardinality, MatchingLabels};
|
||||
use promql_parser::label::Matchers;
|
||||
@@ -102,6 +104,21 @@ const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous;
|
||||
/// longer names the series the partition holds.
|
||||
const METADATA_KEY_TAGS: [&str; 3] = ["__name__", "__type__", "__unit__"];
|
||||
|
||||
/// One prepared occurrence of a selector: the scan that reads it, the raw-series layout it was
|
||||
/// prepared against, and the columns its series are reported under.
|
||||
///
|
||||
/// The last three are the node's rather than one scan's — the binding names a time index, a tag list
|
||||
/// and a metric name once — so they are compared across the occurrences and then travel to the
|
||||
/// binding together. The first two are what [`same_source`] compares, which is the check that two
|
||||
/// occurrences of one selector are one scan.
|
||||
type PreparedInput = (
|
||||
LogicalPlan,
|
||||
Arc<SeriesSchema>,
|
||||
Option<Arc<str>>,
|
||||
String,
|
||||
Vec<String>,
|
||||
);
|
||||
|
||||
impl PromPlanner {
|
||||
/// Plans `prom_expr` as one [`FusedSeries`] node, or returns `None` to keep the existing plan.
|
||||
///
|
||||
@@ -120,11 +137,15 @@ impl PromPlanner {
|
||||
/// native histogram field, or an unusable grid.
|
||||
///
|
||||
/// A statement with two occurrences of one selector is admitted only when both read one scan
|
||||
/// point-wise. That is the only shape this node can run over every partition of one input
|
||||
/// point-wise. That is the only shape this node can run over every partition of one child
|
||||
/// independently: both sides then see the same series in the same partition, so the series a
|
||||
/// partition holds is whole. Everything else — a different scan, different bounds, a match key
|
||||
/// that is not the whole series identity, a shape that reads a whole series as a group —
|
||||
/// keeps the existing plan rather than gathering every partition into one execution.
|
||||
/// partition holds is whole. Such a statement is planned over that one child, with both of its
|
||||
/// tree inputs bound to it; the node's binding names the columns a series is reported under —
|
||||
/// the time index, the tags and the metric name — once for all of them. Everything else — a
|
||||
/// different scan, different bounds, a match key that is not the whole series identity, a shape
|
||||
/// that reads a whole series as a group — keeps the existing plan rather than gathering every
|
||||
/// partition into one execution, because a match over two actual sources cannot be answered one
|
||||
/// region at a time.
|
||||
pub(super) async fn try_plan_native_fused(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
@@ -164,7 +185,7 @@ impl PromPlanner {
|
||||
};
|
||||
let original_context = self.ctx.clone();
|
||||
let preparation = async {
|
||||
let mut prepared: Vec<FusedSeriesInput> = Vec::new();
|
||||
let mut prepared: Vec<PreparedInput> = Vec::new();
|
||||
for selector in &selectors {
|
||||
self.ctx = original_context.clone();
|
||||
let matchers =
|
||||
@@ -317,26 +338,34 @@ impl PromPlanner {
|
||||
} else {
|
||||
return Ok(None);
|
||||
}
|
||||
prepared.push(FusedSeriesInput {
|
||||
series_schema,
|
||||
metric_name: Some(Arc::from(metric)),
|
||||
time_index: time,
|
||||
tags,
|
||||
input,
|
||||
// Filled from the compiled tree, which is what names an input.
|
||||
paths: Vec::new(),
|
||||
});
|
||||
prepared.push((input, series_schema, Some(Arc::from(metric)), time, tags));
|
||||
}
|
||||
Ok(Some(prepared))
|
||||
}
|
||||
.await;
|
||||
self.ctx = original_context;
|
||||
let Some(prepared) = preparation? else {
|
||||
let Some(mut prepared) = preparation? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// The time index, the tag list and the metric name are the node's, not one scan's: the
|
||||
// output schema and the binding name them once, and every occurrence reports its series
|
||||
// under them. Two occurrences that disagree are two different reportings, which one node
|
||||
// cannot be built for. Both occurrences of an admitted pair share the layout, so the first
|
||||
// one's schema also speaks for the node below.
|
||||
let Some((_, series_schema, metric, time, tags)) = prepared.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (series_schema, metric, time, tags) = (
|
||||
Arc::clone(series_schema),
|
||||
metric.clone(),
|
||||
time.clone(),
|
||||
tags.clone(),
|
||||
);
|
||||
if prepared
|
||||
.windows(2)
|
||||
.any(|w| w[0].time_index != w[1].time_index || w[0].tags != w[1].tags)
|
||||
.iter()
|
||||
.any(|(_, _, other_metric, other_time, other_tags)| {
|
||||
*other_metric != metric || *other_time != time || *other_tags != tags
|
||||
})
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -370,7 +399,7 @@ impl PromPlanner {
|
||||
&|req| {
|
||||
let i = bind_index.get();
|
||||
bind_index.set(i + 1);
|
||||
let (Some(prepared_input), Some(identity)) = (prepared.get(i), identities.get(i))
|
||||
let (Some((_, schema, ..)), Some(identity)) = (prepared.get(i), identities.get(i))
|
||||
else {
|
||||
return Err(DataFusionError::Internal(
|
||||
"a selector was bound that the planner did not prepare".into(),
|
||||
@@ -388,7 +417,7 @@ impl PromPlanner {
|
||||
"the compiler and the planner walk the selectors differently".into(),
|
||||
));
|
||||
}
|
||||
Ok(Arc::clone(&prepared_input.series_schema))
|
||||
Ok(Arc::clone(schema))
|
||||
},
|
||||
NATIVE_ORDERING,
|
||||
) {
|
||||
@@ -404,33 +433,41 @@ impl PromPlanner {
|
||||
))
|
||||
.context(DataFusionPlanningSnafu);
|
||||
}
|
||||
let mut inputs = Vec::with_capacity(prepared.len());
|
||||
for (index, (compiled_input, mut input)) in compiled.inputs.iter().zip(prepared).enumerate()
|
||||
for (index, (compiled_input, (scan, _, _, _, _))) in
|
||||
compiled.inputs.iter().zip(prepared.iter_mut()).enumerate()
|
||||
{
|
||||
// The range this selector reads is the compiler's own: a window and an instant differ
|
||||
// in which side of the lookback or range their scan starts on, and an anchor can move
|
||||
// the whole range outside the statement's.
|
||||
// the whole range outside the statement's. The bound belongs to the scan, so it is
|
||||
// pushed down before two occurrences are compared: two selectors over different windows
|
||||
// or offsets read different rows even when nothing else about them differs.
|
||||
let (start, end, inclusive) = compiled_input
|
||||
.requirement
|
||||
.raw_scan_bounds()
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
let time = input.time_index.clone();
|
||||
let mut scan = input.input;
|
||||
let filter = scan_time_filter(start, end, inclusive, scan.schema(), &time)?;
|
||||
if let (LogicalPlan::TableScan(table_scan), Some(filter)) = (&mut scan, filter) {
|
||||
if let (LogicalPlan::TableScan(table_scan), Some(filter)) = (&mut *scan, filter) {
|
||||
table_scan.filters.push(filter);
|
||||
} else if !matches!(scan, LogicalPlan::TableScan(_)) {
|
||||
return Err(DataFusionError::Internal(format!(
|
||||
"the input at {index} is not the table scan this route prepared"
|
||||
"the child at {index} is not the table scan this route prepared"
|
||||
)))
|
||||
.context(DataFusionPlanningSnafu);
|
||||
}
|
||||
input.input = scan;
|
||||
// The tree names the input this occurrence compiled to, and the collapse below joins
|
||||
// two of them onto one plan.
|
||||
input.paths = vec![compiled_input.path.clone()];
|
||||
inputs.push(input);
|
||||
}
|
||||
// Two occurrences are admitted only when both read one scan plan: the node then runs one
|
||||
// execution per partition of that one child, and both sides of the match see the same series
|
||||
// in the same partition. Two actual scans — a different table, different matchers, different
|
||||
// bounds — stay with the existing planner, which is where a match over more than one source
|
||||
// is answered rather than in a region that holds part of it.
|
||||
if selectors.len() == 2 && !(prepared.len() == 2 && same_source(&prepared[0], &prepared[1]))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut children = prepared
|
||||
.into_iter()
|
||||
.map(|(scan, _, _, _, _)| scan)
|
||||
.collect::<Vec<_>>();
|
||||
// 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
|
||||
@@ -439,35 +476,36 @@ impl PromPlanner {
|
||||
// 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)))
|
||||
// twice, a one-to-one match whose key holds the whole identity over one scan, which the
|
||||
// collapse below reads as that scan.
|
||||
let root = compiled.tree.root();
|
||||
if reads_across_series(root)
|
||||
&& !(pointwise_operand(root)
|
||||
|| (selectors.len() == 2 && two_occurrences_pair_one_source(root, &tags)))
|
||||
{
|
||||
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, 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 {
|
||||
// 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.
|
||||
let prepared_inputs = inputs.len();
|
||||
let [first, second] = &mut inputs[..] else {
|
||||
return Err(DataFusionError::Internal(format!(
|
||||
"two occurrences prepared {prepared_inputs} input(s) rather than a pair"
|
||||
)))
|
||||
.context(DataFusionPlanningSnafu);
|
||||
};
|
||||
first.paths.append(&mut second.paths);
|
||||
inputs.remove(1);
|
||||
}
|
||||
let root_fields = compiled
|
||||
.tree
|
||||
// point-wise, both scans are the same scan, and the match key holds the whole identity,
|
||||
// which the checks above have just admitted. Both occurrences are then one child, so the
|
||||
// tree is rebuilt with both inputs bound to it. A tree this route admits but cannot rebind
|
||||
// is a compiler defect it declines (`NotImplemented`) rather than rewrites, and the existing
|
||||
// plan answers the query; an error of any other kind is a defect to report.
|
||||
let tree = if selectors.len() == 2 {
|
||||
match collapsed_pair_tree(&compiled.tree) {
|
||||
Ok(tree) => {
|
||||
// Both occurrences read the one plan, so the two prepared children are that
|
||||
// same plan and only one of them is kept.
|
||||
children.truncate(1);
|
||||
tree
|
||||
}
|
||||
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
|
||||
Err(e) => return Err(e).context(DataFusionPlanningSnafu),
|
||||
}
|
||||
} else {
|
||||
compiled.tree
|
||||
};
|
||||
let root_fields = tree
|
||||
.root()
|
||||
.output
|
||||
.samples()
|
||||
@@ -478,24 +516,24 @@ impl PromPlanner {
|
||||
.map(|f| f.name.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
if root_fields.iter().any(|field| {
|
||||
!inputs.iter().any(|input| {
|
||||
input
|
||||
.series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.any(|f| f.name.as_ref() == field)
|
||||
})
|
||||
!series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.any(|f| f.name.as_ref() == field)
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
let time = inputs[0].time_index.clone();
|
||||
let tags = inputs[0].tags.clone();
|
||||
let output_schema = fused_output_schema(&root_fields, &tags, &time)?;
|
||||
let node = FusedSeries::try_new(
|
||||
Arc::from(prom_expr.to_string()),
|
||||
compiled.tree,
|
||||
FusedSeriesBinding { grid },
|
||||
inputs,
|
||||
tree,
|
||||
FusedSeriesBinding {
|
||||
grid,
|
||||
time_index: time,
|
||||
tags,
|
||||
metric_name: metric,
|
||||
},
|
||||
children,
|
||||
output_schema,
|
||||
)
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
@@ -642,7 +680,7 @@ fn literal_or_next(start: i64) -> Option<DfExpr> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether a tree's two occurrences may be read as one source.
|
||||
/// Whether a tree is two occurrences of one selector matched point-wise over the whole identity.
|
||||
///
|
||||
/// The claim is about one series: it is whole in the partition it was scanned in, so a tree whose
|
||||
/// nodes each read one series separately can run one execution per partition. What breaks that is a
|
||||
@@ -656,35 +694,35 @@ fn literal_or_next(start: i64) -> Option<DfExpr> {
|
||||
/// `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 pair's scans are the caller's claim: this function reads the tree and the tags, and a caller
|
||||
/// that admits a pair on two actual scans would still be admitting a match over two sources. Both
|
||||
/// the planner that collapses a pair onto one scan and the categorizer that places the node
|
||||
/// region-side ask this, so the two cannot disagree about which pairs read one series: a pair
|
||||
/// admitted here but refused there becomes a node the physical layer cannot build.
|
||||
///
|
||||
/// 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 {
|
||||
pub(crate) fn two_occurrences_pair_one_source(root: &NativeNode, tags: &[String]) -> bool {
|
||||
let NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
matching,
|
||||
} = &tree.root().expr
|
||||
} = &root.expr
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// A root with a constant on one side is a broadcast of that constant, not two occurrences
|
||||
// matched, and `group_left`/`group_right` pair a group against one series.
|
||||
if matching.cardinality != Cardinality::OneToOne
|
||||
|| !pointwise_operand(left)
|
||||
|| !pointwise_operand(right)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let [first, second] = inputs else {
|
||||
return false;
|
||||
};
|
||||
// A key that does not hold the whole identity pairs series Prometheus keeps apart, and a
|
||||
// partition that holds one of them cannot tell that the other is missing.
|
||||
matching_keys_on_identity(&matching.labels, &first.tags) && same_source(first, second)
|
||||
matching.cardinality == Cardinality::OneToOne
|
||||
&& pointwise_operand(left)
|
||||
&& pointwise_operand(right)
|
||||
// A key that does not hold the whole identity pairs series Prometheus keeps apart, and a
|
||||
// partition that holds one of them cannot tell that the other is missing.
|
||||
&& matching_keys_on_identity(&matching.labels, tags)
|
||||
}
|
||||
|
||||
/// Whether `node` reads samples point-wise, so that one partitioned execution is one answer.
|
||||
@@ -781,31 +819,90 @@ fn identity_keys_are_injective(matchers: &Matchers, meta: &TableMeta, tags: &[St
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether two prepared inputs read the same scan, and so produce the same series.
|
||||
/// Whether two prepared occurrences read the same scan, and so produce the same series.
|
||||
///
|
||||
/// Everything below the node is compared, not only the table name: two selectors over one table
|
||||
/// with different matchers or different bounds read different rows, and a partition that holds one
|
||||
/// of them is not the partition that holds the other. DataFusion's own scan comparison covers the
|
||||
/// table name, the projection, the schema, the filters and the fetch; the source is compared by
|
||||
/// identity, because it is what resolves those rows in the first place. The time index and the tag
|
||||
/// list are not compared here: both are checked once for every prepared input, above.
|
||||
fn same_source(left: &FusedSeriesInput, right: &FusedSeriesInput) -> bool {
|
||||
/// identity, because it is what resolves those rows in the first place. The reporting columns — the
|
||||
/// metric name, the time index and the tags — are not compared here: they are checked once for
|
||||
/// every prepared occurrence, before this runs.
|
||||
fn same_source(left: &PreparedInput, right: &PreparedInput) -> bool {
|
||||
let (left_input, left_schema, ..) = left;
|
||||
let (right_input, right_schema, ..) = right;
|
||||
let (LogicalPlan::TableScan(left_scan), LogicalPlan::TableScan(right_scan)) =
|
||||
(&left.input, &right.input)
|
||||
(left_input, right_input)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// Both schemas are raw series schemas, so the fields are what the tree's input was compiled
|
||||
// against, in the order it reads them.
|
||||
left.metric_name == right.metric_name
|
||||
&& left
|
||||
.series_schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| &field.name)
|
||||
.eq(right.series_schema.fields.iter().map(|field| &field.name))
|
||||
&& left_scan == right_scan
|
||||
&& Arc::ptr_eq(&left_scan.source, &right_scan.source)
|
||||
let same_fields = left_schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| &field.name)
|
||||
.eq(right_schema.fields.iter().map(|field| &field.name));
|
||||
same_fields && left_scan == right_scan && Arc::ptr_eq(&left_scan.source, &right_scan.source)
|
||||
}
|
||||
|
||||
/// Rebuilds an admitted pair's tree so both of its occurrences read the one child prepared for them.
|
||||
///
|
||||
/// The compiler numbers occurrences in binding order, so an admitted pair's two input nodes are
|
||||
/// numbered `0` and `1`; the planner prepared one plan for them, which is child `0`. Giving every
|
||||
/// input node that index is what makes the executor hand each chunk of that child to both of them,
|
||||
/// and what makes the node report one child for the whole match.
|
||||
///
|
||||
/// The tree is rebuilt rather than patched in place because a node's inputs are shared: the rebuilt
|
||||
/// tree is validated again by [`NativeTree::try_new`], so a rebind can never produce a tree the
|
||||
/// runtime would refuse. A tree whose inputs are not exactly those two occurrences is a compiler
|
||||
/// defect this route declines with `NotImplemented` — the caller keeps the existing plan rather than
|
||||
/// running a tree whose inputs it cannot name.
|
||||
///
|
||||
/// It is `pub(crate)` for the categorizer's own tests, which build the node the planner would have
|
||||
/// built: the region-side placement has to accept exactly the shape this collapse produces, so a
|
||||
/// fixture that bound the pair by hand could agree with the categorizer while disagreeing with the
|
||||
/// planner.
|
||||
pub(crate) fn collapsed_pair_tree(tree: &NativeTree) -> datafusion::error::Result<NativeTree> {
|
||||
let mut root = tree.root().clone();
|
||||
let mut occurrences = 0;
|
||||
let numbered = rebind_pair_inputs(&mut root, &mut occurrences);
|
||||
if !numbered || occurrences != 2 {
|
||||
return Err(DataFusionError::NotImplemented(format!(
|
||||
"a two-occurrence tree whose {occurrences} input(s) are not the two occurrences \
|
||||
numbered from zero, which this route cannot bind to one child"
|
||||
)));
|
||||
}
|
||||
NativeTree::try_new(root)
|
||||
}
|
||||
|
||||
/// Rebinds every input below `node` to child `0`, counting them and checking their numbering.
|
||||
///
|
||||
/// The walk visits inputs in the order the compiler bound them — an operand before the next one, the
|
||||
/// left operand before the right — so occurrence `i` of the walk is the input the compiler numbered
|
||||
/// `i`. `false` means the tree is not the pair this route admitted: a node carried a number the walk
|
||||
/// did not expect, or a shape the admission does not cover. An `Aggregate` or a `Vector` below the
|
||||
/// root is one of those shapes — neither is point-wise, so the pair was never admitted — and the
|
||||
/// walk refuses it rather than rebinding a tree this route does not run.
|
||||
fn rebind_pair_inputs(node: &mut NativeNode, next: &mut usize) -> bool {
|
||||
match &mut node.expr {
|
||||
NativeExpr::Input(bound) => {
|
||||
let numbered = bound.source_index == *next;
|
||||
bound.source_index = 0;
|
||||
*next += 1;
|
||||
numbered
|
||||
}
|
||||
NativeExpr::Scalar(_) => true,
|
||||
NativeExpr::Instant { input, .. }
|
||||
| NativeExpr::Window { input, .. }
|
||||
| NativeExpr::Map { input, .. } => rebind_pair_inputs(input, next),
|
||||
NativeExpr::Binary { left, right, .. } => {
|
||||
let left_numbered = rebind_pair_inputs(left, next);
|
||||
let right_numbered = rebind_pair_inputs(right, next);
|
||||
left_numbered && right_numbered
|
||||
}
|
||||
NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns a [`FusedSeries`] node produces.
|
||||
@@ -935,10 +1032,14 @@ fn metric_scan_and_table_id(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use promql::native::plan::{NativeExpr, NativeNode};
|
||||
use session::context::QueryContextBuilder;
|
||||
|
||||
use super::{NATIVE_PROMQL_EXTENSION_KEY, native_promql_requested};
|
||||
use super::{NATIVE_PROMQL_EXTENSION_KEY, collapsed_pair_tree, native_promql_requested};
|
||||
|
||||
#[test]
|
||||
fn native_promql_requested_is_false_when_extension_is_absent() {
|
||||
@@ -960,6 +1061,85 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement `query` is compiled against: one selector over five seconds of grid.
|
||||
fn native_test_statement(query: &str) -> promql_parser::parser::EvalStmt {
|
||||
promql_parser::parser::EvalStmt {
|
||||
expr: promql_parser::parser::parse(query).unwrap(),
|
||||
start: UNIX_EPOCH,
|
||||
end: UNIX_EPOCH + Duration::from_secs(10),
|
||||
interval: Duration::from_secs(5),
|
||||
lookback_delta: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
/// `query` compiled against one raw-series layout, every selector bound to it.
|
||||
///
|
||||
/// The entry is `compile_selectors` rather than the compatibility `compile`, because the pair
|
||||
/// these tests are about names one selector twice and `compile` refuses a statement whose two
|
||||
/// occurrences it cannot tell apart. Binding both occurrences to one layout is the test's
|
||||
/// choice of scan, not a claim the compiler makes.
|
||||
fn native_test_tree(query: &str) -> promql::native::plan::NativeTree {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
eval_grid: None,
|
||||
});
|
||||
let stmt = native_test_statement(query);
|
||||
crate::promql::native_compile::compile_selectors(
|
||||
&stmt,
|
||||
&|_| Ok(Arc::clone(&schema)),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
.unwrap()
|
||||
.tree
|
||||
}
|
||||
|
||||
/// The child each raw input below `root` reads, in the order the compiler bound them.
|
||||
fn native_test_input_sources(root: &NativeNode) -> Vec<usize> {
|
||||
let mut sources = Vec::new();
|
||||
promql::native::metrics::walk(root, &mut |node, _| {
|
||||
if let NativeExpr::Input(bound) = &node.expr {
|
||||
sources.push(bound.source_index);
|
||||
}
|
||||
});
|
||||
sources
|
||||
}
|
||||
|
||||
/// Collapsing a pair binds both occurrences to the one child the planner prepared for them.
|
||||
#[test]
|
||||
fn a_pair_tree_is_rebound_to_its_one_child() {
|
||||
let tree = native_test_tree("x + x");
|
||||
assert_eq!(
|
||||
native_test_input_sources(tree.root()),
|
||||
vec![0, 1],
|
||||
"the compiler numbers occurrences"
|
||||
);
|
||||
|
||||
let collapsed = collapsed_pair_tree(&tree).unwrap();
|
||||
assert_eq!(native_test_input_sources(collapsed.root()), vec![0, 0]);
|
||||
// The rest of the tree is the one that was compiled: only the bindings moved.
|
||||
assert!(matches!(collapsed.root().expr, NativeExpr::Binary { .. }));
|
||||
assert_eq!(
|
||||
tree.to_string().replace("source=1", "source=0"),
|
||||
collapsed.to_string(),
|
||||
"the collapse changed something other than the child each input reads"
|
||||
);
|
||||
}
|
||||
|
||||
/// A tree whose inputs are not the two occurrences is declined, and the refusal is the one the
|
||||
/// route answers with the existing plan — not an internal error to report.
|
||||
#[test]
|
||||
fn a_tree_that_is_not_a_pair_is_declined_by_the_collapse() {
|
||||
let error = collapsed_pair_tree(&native_test_tree("x")).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, datafusion::error::DataFusionError::NotImplemented(_)),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
error.to_string().contains("cannot bind to one child"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_promql_requested_rejects_false_and_unrecognized_values() {
|
||||
for value in ["false", "FALSE", "yes", "1", " true ", ""] {
|
||||
|
||||
@@ -38,7 +38,7 @@ use datafusion::datasource::memory::MemorySourceConfig;
|
||||
use datafusion::datasource::source::DataSourceExec;
|
||||
use datafusion::datasource::{MemTable, provider_as_source};
|
||||
use datafusion::execution::context::SessionContext;
|
||||
use datafusion::logical_expr::{Extension, UserDefinedLogicalNodeCore, col};
|
||||
use datafusion::logical_expr::{Extension, col};
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
@@ -1841,7 +1841,7 @@ fn find_metric_physical_scan(plan: &LogicalPlan) -> Option<datafusion::logical_e
|
||||
LogicalPlan::Extension(Extension { node }) => node
|
||||
.as_any()
|
||||
.downcast_ref::<FusedSeries>()
|
||||
.and_then(|fused| match fused.inputs().first() {
|
||||
.and_then(|fused| match fused.children().first() {
|
||||
Some(LogicalPlan::TableScan(scan)) => Some(scan.clone()),
|
||||
_ => None,
|
||||
}),
|
||||
@@ -1862,29 +1862,60 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> {
|
||||
plan.inputs().into_iter().find_map(find_fused_series)
|
||||
}
|
||||
|
||||
/// Two occurrences of one selector over one scan plan as one input carrying both occurrences.
|
||||
/// Two occurrences of one selector over one scan plan as one child both occurrences read.
|
||||
#[tokio::test]
|
||||
async fn native_fused_binary_collapses_two_occurrences_onto_one_scan() {
|
||||
let plan = build_native_fused_plan("some_metric + some_metric", true).await;
|
||||
let fused = find_fused_series(&plan).expect("binary query uses native route");
|
||||
assert_eq!(1, fused.fused_inputs().len());
|
||||
let input = &fused.fused_inputs()[0];
|
||||
assert_eq!(1, fused.children().len());
|
||||
assert!(
|
||||
matches!(input.input, LogicalPlan::TableScan(_)),
|
||||
"the input should be the selector's own scan: {:?}",
|
||||
input.input
|
||||
matches!(fused.children()[0], LogicalPlan::TableScan(_)),
|
||||
"the child should be the selector's own scan: {:?}",
|
||||
fused.children()[0]
|
||||
);
|
||||
// Both occurrences are recorded on the one source, because the tree reads two inputs and both
|
||||
// of them read these rows.
|
||||
let paths = input
|
||||
.paths
|
||||
.iter()
|
||||
.map(|path| path.as_str().to_string())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(2, paths.len(), "{paths:?}");
|
||||
assert_ne!(paths[0], paths[1], "{paths:?}");
|
||||
assert!(paths[0].starts_with("root.left"), "{paths:?}");
|
||||
assert!(paths[1].starts_with("root.right"), "{paths:?}");
|
||||
// Both occurrences name the one child, because the tree reads two inputs and both of them read
|
||||
// these rows.
|
||||
let inputs = tree_inputs(fused);
|
||||
assert_eq!(
|
||||
inputs,
|
||||
vec![
|
||||
("root.left.input".to_string(), 0),
|
||||
("root.right.input".to_string(), 0)
|
||||
],
|
||||
"the occurrences were not rebound to the one child"
|
||||
);
|
||||
// The columns a series is reported under are the node's: one binding names them for both
|
||||
// occurrences, rather than each occurrence carrying its own copy.
|
||||
let binding = fused.binding();
|
||||
assert_eq!(binding.metric_name.as_deref(), Some("some_metric"));
|
||||
assert_eq!(binding.time_index, "timestamp");
|
||||
assert_eq!(binding.tags, vec!["tag_0".to_string()]);
|
||||
}
|
||||
|
||||
/// Two occurrences that read one table over different bounds read different rows, so they are two
|
||||
/// actual sources and keep the existing plan.
|
||||
#[tokio::test]
|
||||
async fn native_fused_two_occurrences_decline_different_bounds() {
|
||||
let tags = [("host", false), ("zone", false)];
|
||||
for query in [
|
||||
// One side reads a window ten seconds earlier than the other.
|
||||
"some_metric{host!=\"\"} + some_metric{host!=\"\"} offset 10s",
|
||||
// One side folds the same window around a fixed anchor, the other around every grid point.
|
||||
"rate(some_metric{host!=\"\"}[5m]) + rate(some_metric{host!=\"\"}[5m] @ 300)",
|
||||
] {
|
||||
assert_two_occurrences_fall_back(&tags, query).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw input nodes of `fused`'s tree, as their structural path and the child each reads.
|
||||
fn tree_inputs(fused: &FusedSeries) -> Vec<(String, usize)> {
|
||||
let mut inputs = Vec::new();
|
||||
promql::native::metrics::walk(fused.tree().root(), &mut |node, path| {
|
||||
if let NativeExpr::Input(bound) = &node.expr {
|
||||
inputs.push((path.as_str().to_string(), bound.source_index));
|
||||
}
|
||||
});
|
||||
inputs
|
||||
}
|
||||
|
||||
/// Two occurrences whose matchers differ read different rows, so they keep the existing plan.
|
||||
@@ -1923,28 +1954,28 @@ async fn build_identity_fused_plan(
|
||||
build_native_fused_plan_with_provider(query, native_fused, table_provider).await
|
||||
}
|
||||
|
||||
/// The paths an admitted two-occurrence statement records on its one input.
|
||||
/// The input nodes an admitted two-occurrence statement binds, as their paths.
|
||||
///
|
||||
/// Both occurrences read the one child the statement was collapsed onto, so both are numbered after
|
||||
/// it: a plan that left the two occurrences on two children would hand each side of the match half
|
||||
/// the partitions, which is the shape this route declines.
|
||||
fn admitted_two_occurrence_paths(plan: &LogicalPlan) -> Vec<String> {
|
||||
let fused = find_fused_series(plan).expect("the statement should plan to one native node");
|
||||
assert_eq!(
|
||||
1,
|
||||
fused.fused_inputs().len(),
|
||||
"two occurrences over one scan are one input"
|
||||
fused.children().len(),
|
||||
"two occurrences over one scan are one child"
|
||||
);
|
||||
let input = &fused.fused_inputs()[0];
|
||||
assert!(
|
||||
matches!(input.input, LogicalPlan::TableScan(_)),
|
||||
"the input should be the selector's own scan: {:?}",
|
||||
input.input
|
||||
matches!(fused.children()[0], LogicalPlan::TableScan(_)),
|
||||
"the child should be the selector's own scan: {:?}",
|
||||
fused.children()[0]
|
||||
);
|
||||
let paths = input
|
||||
.paths
|
||||
.iter()
|
||||
.map(|path| path.as_str().to_string())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(2, paths.len(), "{paths:?}");
|
||||
assert_ne!(paths[0], paths[1], "{paths:?}");
|
||||
paths
|
||||
let inputs = tree_inputs(fused);
|
||||
assert_eq!(2, inputs.len(), "{inputs:?}");
|
||||
assert_ne!(inputs[0].0, inputs[1].0, "{inputs:?}");
|
||||
assert_eq!((0, 0), (inputs[0].1, inputs[1].1), "{inputs:?}");
|
||||
inputs.into_iter().map(|(path, _)| path).collect()
|
||||
}
|
||||
|
||||
/// Asserts `query` plans exactly as it does with the native route off.
|
||||
@@ -2087,8 +2118,8 @@ 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.
|
||||
/// A statement that names its selector once reads one scan, so it binds one child and one input,
|
||||
/// however many positional operands its tree has.
|
||||
#[tokio::test]
|
||||
async fn native_fused_one_occurrence_records_one_path() {
|
||||
for query in [
|
||||
@@ -2103,14 +2134,15 @@ async fn native_fused_one_occurrence_records_one_path() {
|
||||
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_eq!(1, fused.children().len(), "{query}");
|
||||
assert!(
|
||||
matches!(input.input, LogicalPlan::TableScan(_)),
|
||||
matches!(fused.children()[0], LogicalPlan::TableScan(_)),
|
||||
"{query}: {:?}",
|
||||
input.input
|
||||
fused.children()[0]
|
||||
);
|
||||
assert_eq!(1, input.paths.len(), "{query}: {:?}", input.paths);
|
||||
let inputs = tree_inputs(fused);
|
||||
assert_eq!(1, inputs.len(), "{query}: {inputs:?}");
|
||||
assert_eq!(0, inputs[0].1, "{query}: {inputs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ use datatypes::series::samples::{FieldSpec, SampleRef, Samples, SeriesFields, Se
|
||||
use datatypes::series::{Label, MetricName, SeriesOrdering};
|
||||
use promql::evaluated::EvaluatedChunk;
|
||||
use promql::native::execute::{NativeExecutionState, NativeExecutor};
|
||||
use promql::native::plan::NativeExpr;
|
||||
use promql::native::plan::{BoundInput, NativeExpr};
|
||||
use query::promql::native_compile::SelectorRequirement;
|
||||
use query::promql::native_compile::{CompiledTree, compile_selectors};
|
||||
|
||||
@@ -244,6 +244,32 @@ fn every_point(value: f64) -> Vec<(usize, f64)> {
|
||||
(0..5).map(|position| (position, value)).collect()
|
||||
}
|
||||
|
||||
/// Each compiled input's tree node names the child of the final tree it reads: occurrence `i` reads
|
||||
/// child `i`, which is what makes the handful of sources a caller holds a tree it can feed.
|
||||
///
|
||||
/// The compiler numbers occurrences, so `a + a` binds two children even though both reads see the
|
||||
/// same series; a caller that knows they are one scan rebinds them, which is a decision made above
|
||||
/// this compiler.
|
||||
#[test]
|
||||
fn compiled_inputs_are_numbered_by_binding_occurrence() {
|
||||
for (query, expected) in [
|
||||
("a", vec![0]),
|
||||
("a + b", vec![0, 1]),
|
||||
("a + a", vec![0, 1]),
|
||||
("(a + b) / a", vec![0, 1, 2]),
|
||||
] {
|
||||
let compiled = compile(query);
|
||||
let mut indices = Vec::new();
|
||||
promql::native::metrics::walk(compiled.tree.root(), &mut |node, _| {
|
||||
if let NativeExpr::Input(BoundInput { source_index, .. }) = &node.expr {
|
||||
indices.push(*source_index);
|
||||
}
|
||||
});
|
||||
assert_eq!(indices, expected, "query: {query}");
|
||||
assert_eq!(compiled.inputs.len(), expected.len(), "query: {query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `a + b` over two genuinely different inputs: different metric names, different matcher sets and
|
||||
/// different samples. Each input is fed at the position its own selector was bound to, and the sum
|
||||
/// is asserted point by point.
|
||||
|
||||
Reference in New Issue
Block a user