feat(promql): run a native tree over one independent scan per selector

A PromQL vector–vector binary operation now runs on the native fused-series path. Each selector of
the statement is bound to its own scan, and the compiled tree reads them as separate inputs:

- `compile_selectors` answers one `CompiledInput` per selector — where the executor reads it
  (`NodePath`), what the selector asked a scan for (`SelectorRequirement`: metric, matchers, offset,
  `@` anchor, the grid it is evaluated on, and whether it reads an instant or a window, from which
  `raw_scan_bounds()` derives the raw scan interval), the layout it was bound to and the ordering the
  scan guarantees.
- The planner prepares one `TableScan` per selector from that selector's own context — its metric,
  its own matchers as row filters, its own fields and tags — then adds the time filter from the
  requirement the compiler produced for that selector. A window and an instant differ in which edge
  they start from, and an `@` anchor moves the whole interval, so deriving the interval from the
  statement's endpoints would scan the wrong range.
- `FusedSeries` carries one `FusedSeriesInput` per selector, and `FusedSeriesExec` decodes each
  child against that input's own schema, materialises its labels, and pushes its chunks at that
  input's `NodePath`. The tree settles once, when every input has ended.
- Vector arithmetic and comparisons compile with `on` / `ignoring`, `group_left` / `group_right` and
  the `fill`, `fill_left`, `fill_right` values, and `bool` comparisons.

Scan parallelism is kept: every input is prepared with `execution.target_partitions` ranges, so one
region still scans as several partitions.

One input keeps the old behaviour — one tree execution per scan partition — because the series
producer keeps a whole series in one partition.

Several inputs do **not** run per partition. Two independent scans balance their ranges by row count,
so the same series can land in partition 0 of one and partition 1 of the other; matching per
partition index would then silently drop that match. Until there is an exchange that pairs the
matching series of each input, a node with several inputs runs as **one** execution that reads every
partition of every input (`gather_partitions`). It reports `UnknownPartitioning(1)` so nothing
downstream assumes the children's layout, and each child is executed when the gathered stream reaches
it, so the plan below stays a plan until it is read.

The tree evaluation of a multi-input query is therefore serial across scan partitions. The scan
itself is not: each partition still builds its range streams concurrently, and a partition's ranges
are still read in parallel.

- Output columns are classified against the **tree's** root schema, not the first input's: `a=[x,y] +
  b=[z]` reports `x`, and reading that off the input would accept an output schema naming a field no
  input produced.
- A `__field__` matcher makes the route decline (`Ok(None)` → legacy planner). The raw series scan
  reports every field it carries, so binding all of them would fold fields the query excluded.
  Accepting the matcher and ignoring it silently scanned the wrong field set.
- The split-logical-series guard now checks **ancestry** rather than walk order: a window is only
  endangered by a rewriter below it, and `rate(a[5m]) + rate(b[5m])` — two sibling windows — is two
  subtrees, not an ancestor pair.
- `POLL_BUDGET` is charged per child poll, so a node with several inputs cannot multiply the work one
  poll does by its child count.
- The planner and the compiler now agree on which selector is which: `collect_selectors` walks
  `Binary` operands left-then-right (it did not walk them at all before, so a binary query silently
  fell back to the legacy planner), and the binding callback checks each requirement against the
  selector at the same position before accepting it. The walk now also descends unary, aggregate and
  subquery nodes, which the compiler recurses into.
- `EnforceDistRequirementRewriter` stops at a fused node's branch instead of refusing every node with
  more than one input. Its column requirements are scoped by a level of one child chain, and the only
  projections it amends sit above the branch; each child here is a region scan, which has none.
- `TQL EXPLAIN` and `TQL EXPLAIN VERBOSE` offer their body to the native compiler and wrap the plan it
  makes, so an explanation shows the plan that query actually runs. `ANALYZE` is left to the existing
  path.

`cargo nextest run -p promql`: 838 passed, 0 skipped.
`cargo nextest run -p query`: 981 passed, 2 skipped (one earlier run hit a deferred-grid test that
materialises a `usize::MAX`-sized axis; it passes in the suite and on its own).
`cargo nextest run -p query --test native_multi_selector`: 10 passed — real compiler → real executor,
covering `on`, `ignoring`, `group_left`, `group_right`, fills, comparisons, nested trees, repeated
metrics with different windows, per-selector time ranges, and two scans that place the same series in
opposite partitions.

Standalone `/v1/promql` with `[query] experimental_native_promql = true` and `parallelism = 4`, on a
table whose four series sit in three flushed ranges (so one region holds several scan ranges), all
nine queries compared against the legacy planner row by row (labels, values, timestamps):

| query | native plan | same as legacy |
| --- | --- | --- |
| `bf{kind="a"} + on(host) bf{kind="b"}` | `Binary + on [host] one-to-one`, 2 scans × 4 partitions | 2 series × 6 points |
| `bf{kind="a"} / ignoring(kind) bf{kind="b"}` | `Binary / ignoring [kind] one-to-one`, 2 × 4 | 2 × 6 |
| `bf{kind="a"} + on(host) group_left(kind) bf{kind="b"}` | `Binary + on [host] many-to-one [kind]`, 2 × 4 | 2 × 6, labels `{host, kind="b"}` |
| `bf{kind="a"} > bool on(host) bf{kind="b"}` | `Binary > bool on [host] one-to-one`, 2 × 4 | 2 × 6 |
| `rate(bf{kind="a"}[3s]) + on(host) rate(bf{kind="b"}[3s])` | `Binary + on [host]` over two `Window rate [3000ms]`, 2 × 4 | 2 × 6 |
| `bf{host="h1",kind="a"} + on(host) bf{host="h2",kind="b"}` | 2 × 4 | empty in both |
| `bf2 + bf2` (two fields) | `Binary + ignoring []`, 2 × 4, `fields=2` | 2 × 6 |
| `rate(bf2[3s]) + rate(bf2[3s])` | two windows, 2 × 4, `fields=2` | 2 × 6 |
| `bf2{__field__="v1"} + bf2` | no native node — declined for the `__field__` matcher | 2 × 6 |

Evidence the native plan ran, from the physical planner's own debug log (an `EXPLAIN` stops at the
logical plan; this is the plan the region built):

```
FusedSeriesExec: bf{kind="a"} + on (host) bf{kind="b"}
NativeTree
  root Binary + on [host] one-to-one
    left Instant lookback 300000ms offset 0 on grid 1700000001000/1000x6
      input Input raw samples
    right Instant lookback 300000ms offset 0 on grid 1700000001000/1000x6
      input Input raw samples
  SeriesScanExec: source=primary_key, fields=1, partitions=4
  SeriesScanExec: source=primary_key, fields=1, partitions=4
```

Both scans keep four partitions, which is the configured `parallelism`: the node's output is one
partition, but the scanning is not serialised into one.

- An exchange that pairs the matching series of two inputs, which would let a multi-input tree run one
  execution per partition again.
- `info()`'s second input, scalar–vector operations, set operators, subquery execution and the
  distributed path.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-10-24 19:03:59 +08:00
committed by discord9
parent 9a01dd9780
commit b7ad637f1f
10 changed files with 1399 additions and 694 deletions
+3 -1
View File
@@ -38,7 +38,9 @@ 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, FusedSeriesStream};
pub use fused_series::{
FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, FusedSeriesStream,
};
pub use histogram_fold::{
HistogramFold, HistogramFoldExec, HistogramFoldOperation, HistogramFoldStream,
};
File diff suppressed because it is too large Load Diff
@@ -69,17 +69,19 @@ use futures::{Stream, StreamExt, TryStreamExt};
use store_api::region_engine::RawLabelSource;
use super::{
FusedSeries, FusedSeriesBinding, LabelSets, OutputColumn, POLL_BUDGET, label_set,
occupied_runs, series_to_record_batch,
FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, LabelSets, OutputColumn,
POLL_BUDGET, label_set, occupied_runs, series_to_record_batch,
};
use crate::evaluated::EvaluatedChunk;
use crate::native::execute::{NativeExecutionState, NativeExecutor};
use crate::native::metrics::NodePath;
use crate::native::plan::{
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundWindow, Grouping,
NativeExpr, NativeNode, NativeTree, NativeType,
};
use crate::native::runs::absorb_rebuilds;
use crate::range_eval::{RangeFunction, RangeWindow};
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
/// The query every tree here is compiled from.
const PROMQL: &str = "rate(x[5m])";
@@ -181,6 +183,70 @@ fn rate_tree() -> NativeTree {
rate_tree_of(raw_schema())
}
fn binary_tree(left_schema: Arc<SeriesSchema>, right_schema: Arc<SeriesSchema>) -> NativeTree {
let grid = grid();
let left_eval = Arc::new(SeriesSchema {
fields: left_schema.fields.clone(),
eval_grid: Some(Arc::clone(&grid)),
});
let right_eval = Arc::new(SeriesSchema {
fields: right_schema.fields.clone(),
eval_grid: Some(Arc::clone(&grid)),
});
let output = crate::vector_match::binary_output_schema(&left_eval, &right_eval).unwrap();
let raw_left = Arc::clone(&left_schema);
let raw_right = Arc::clone(&right_schema);
let left = NativeNode {
expr: NativeExpr::Instant {
input: Box::new(NativeNode {
expr: NativeExpr::Input(BoundInput {
output: NativeType::Samples(Arc::clone(&raw_left)),
ordering: SeriesOrdering::KeyThenTime,
}),
output: NativeType::Samples(raw_left),
}),
op: BoundInstant {
lookback_ms: 0,
offset_ms: 0,
output_grid: Arc::clone(&grid),
},
},
output: NativeType::Samples(left_eval),
};
let right = NativeNode {
expr: NativeExpr::Instant {
input: Box::new(NativeNode {
expr: NativeExpr::Input(BoundInput {
output: NativeType::Samples(Arc::clone(&raw_right)),
ordering: SeriesOrdering::KeyThenTime,
}),
output: NativeType::Samples(raw_right),
}),
op: BoundInstant {
lookback_ms: 0,
offset_ms: 0,
output_grid: Arc::clone(&grid),
},
},
output: NativeType::Samples(right_eval),
};
NativeTree::try_new(NativeNode {
expr: NativeExpr::Binary {
left: Box::new(left),
right: Box::new(right),
matching: BinaryMatching {
op: BinaryOp::Add,
return_bool: false,
labels: MatchingLabels::On(vec![Arc::from(HOST)]),
cardinality: Cardinality::OneToOne,
fill: FillValues::default(),
},
},
output: NativeType::Samples(output),
})
.unwrap()
}
/// An instant selection feeding a range window.
fn instant_window_tree() -> NativeTree {
let instant = instant_tree().root().clone();
@@ -359,23 +425,41 @@ fn instant_tree() -> NativeTree {
/// What the tree's input was compiled against, for the input schema and output tags given.
fn binding_of(
tree: &NativeTree,
series_schema: Arc<SeriesSchema>,
tags: Vec<String>,
_series_schema: Arc<SeriesSchema>,
_tags: Vec<String>,
) -> FusedSeriesBinding {
FusedSeriesBinding {
series_schema,
grid: tree
.root()
.output
.samples()
.expect("this tree produces samples")
.unwrap()
.eval_grid
.clone()
.expect("this tree's output is evaluated on a grid"),
.unwrap(),
}
}
fn one_input(tree: &NativeTree, plan: LogicalPlan) -> Vec<FusedSeriesInput> {
one_input_tags(tree, plan, vec![HOST.to_string(), NAME.to_string()])
}
fn one_input_tags(
tree: &NativeTree,
plan: LogicalPlan,
tags: Vec<String>,
) -> Vec<FusedSeriesInput> {
let mut found = Vec::new();
crate::native::metrics::walk(tree.root(), &mut |node, _| {
if let NativeExpr::Input(input) = &node.expr {
found.push(Arc::clone(input.output.samples().unwrap()));
}
});
vec![FusedSeriesInput {
series_schema: found.remove(0),
metric_name: Some(Arc::from(METRIC)),
time_index: TIME.to_string(),
tags,
}
input: plan,
}]
}
/// What the tree's input was compiled against, read off the tree itself.
@@ -626,9 +710,9 @@ fn fused(tree: NativeTree) -> FusedSeries {
let binding = binding(&tree);
FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema()),
one_input(&tree, input_plan(frame_schema())),
output_schema().to_dfschema_ref().unwrap(),
)
.expect("the binding matches the tree")
@@ -639,7 +723,11 @@ fn plan_of(
node: FusedSeries,
input: Arc<dyn ExecutionPlan>,
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
node.to_execution_plan(input, RawLabelSource::Explicit, SeriesOrdering::Contiguous)
node.to_execution_plan(vec![(
input,
RawLabelSource::Explicit,
SeriesOrdering::Contiguous,
)])
}
/// The physical node of `tree` over `input`.
@@ -850,9 +938,13 @@ fn zone_node() -> FusedSeries {
);
FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema()),
one_input_tags(
&tree,
input_plan(frame_schema()),
vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()],
),
zone_output_schema().to_dfschema_ref().unwrap(),
)
.expect("the binding matches the tree")
@@ -871,9 +963,13 @@ fn instant_node() -> FusedSeries {
);
FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema()),
one_input_tags(
&tree,
input_plan(frame_schema()),
vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()],
),
zone_output_schema().to_dfschema_ref().unwrap(),
)
.expect("the binding matches the tree")
@@ -1216,6 +1312,166 @@ async fn a_series_spanning_chunks_keeps_absolute_positions_and_closes_once() {
assert_eq!(1, count(&metrics, "native.root.completed_series"));
}
#[tokio::test]
async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() {
let left_schema = raw_schema();
let right_schema = raw_schema();
let tree = binary_tree(Arc::clone(&left_schema), Arc::clone(&right_schema));
let output = Arc::new(Schema::new(vec![
Field::new(VALUE, DataType::Float64, true),
Field::new(HOST, DataType::Utf8, true),
Field::new(NAME, DataType::Utf8, true),
Field::new(
TIME,
DataType::Timestamp(TimeUnit::Millisecond, None),
false,
),
]));
let _node = FusedSeries::try_new(
Arc::from("a + on(host) b"),
tree.clone(),
FusedSeriesBinding { grid: grid() },
vec![
FusedSeriesInput {
series_schema: left_schema.clone(),
metric_name: Some(Arc::from("a")),
time_index: TIME.into(),
tags: vec![HOST.into(), NAME.into()],
input: input_plan(frame_schema()),
},
FusedSeriesInput {
series_schema: right_schema.clone(),
metric_name: Some(Arc::from("b")),
time_index: TIME.into(),
tags: vec![HOST.into(), NAME.into()],
input: input_plan(frame_schema()),
},
],
output.clone().to_dfschema_ref().unwrap(),
)
.unwrap();
let physical = FusedSeriesExec::try_new(
Arc::from("a + on(host) b"),
vec![
(
memory_exec(frames(&[series_chunk("job", &[(GRID_START, 10.0)], true)])),
RawLabelSource::Explicit,
SeriesOrdering::Contiguous,
NodePath::root().left().input(),
left_schema,
),
(
memory_exec(frames(&[series_chunk("job", &[(GRID_START, 7.0)], true)])),
RawLabelSource::Explicit,
SeriesOrdering::Contiguous,
NodePath::root().right().input(),
right_schema,
),
],
Arc::new(tree),
output,
TIME.into(),
vec![HOST.into(), NAME.into()],
)
.unwrap();
let batches = collect(Arc::new(physical), SessionContext::default().task_ctx())
.await
.unwrap();
let rows = rows(&batches);
assert_eq!(1, rows.len());
assert_eq!(GRID_START, rows[0].0);
assert_eq!(Some(17.0), rows[0].1);
assert_eq!(Some("job".to_string()), rows[0].2);
}
#[tokio::test]
async fn two_inputs_match_across_every_partition_of_each_scan() {
let left_schema = raw_schema();
let right_schema = raw_schema();
let tree = binary_tree(Arc::clone(&left_schema), Arc::clone(&right_schema));
let output = output_schema();
let node = FusedSeries::try_new(
Arc::from("a + on(host) b"),
tree.clone(),
FusedSeriesBinding { grid: grid() },
vec![
FusedSeriesInput {
series_schema: left_schema.clone(),
metric_name: Some(Arc::from("a")),
time_index: TIME.into(),
tags: vec![HOST.into(), NAME.into()],
input: input_plan(frame_schema()),
},
FusedSeriesInput {
series_schema: right_schema.clone(),
metric_name: Some(Arc::from("b")),
time_index: TIME.into(),
tags: vec![HOST.into(), NAME.into()],
input: input_plan(frame_schema()),
},
],
output
.to_dfschema_ref()
.expect("the output schema is valid"),
)
.expect("the two-input binding matches the tree");
// The two scans need not even agree on how many partitions they have: what pairs their series is
// the label, not the partition index, so the counts only decide how much each scan reads at once.
let left_rows = series_samples(1.0);
let right_rows = series_samples(2.0);
let left = memory_exec_partitioned(vec![
frames(&[series_chunk("h1", &left_rows, true)]),
frames(&[series_chunk("h2", &left_rows, true)]),
]);
let right = memory_exec_partitioned(vec![
frames(&[series_chunk("h2", &right_rows, true)]),
frames(&[series_chunk("h1", &right_rows, true)]),
Vec::new(),
]);
let physical = node
.to_execution_plan(vec![
(left, RawLabelSource::Explicit, SeriesOrdering::Contiguous),
(right, RawLabelSource::Explicit, SeriesOrdering::Contiguous),
])
.expect("the two-input physical plan builds");
assert_eq!(
1,
physical
.properties()
.output_partitioning()
.partition_count()
);
let batches = collect(Arc::clone(&physical), SessionContext::default().task_ctx())
.await
.expect("the sole output partition executes");
let actual = rows(&batches);
// A grid of its own, and the sample of each side that sits exactly on each of its points.
let grid_stamps = grid_timestamps();
let expected = grid_stamps
.iter()
.map(|&stamp| {
let left = left_rows
.iter()
.find_map(|(time, value)| (*time == stamp).then_some(*value))
.expect("the left samples cover every grid point");
let right = right_rows
.iter()
.find_map(|(time, value)| (*time == stamp).then_some(*value))
.expect("the right samples cover every grid point");
(stamp, Some(left + right))
})
.collect::<Vec<_>>();
for host in ["h1", "h2"] {
let series = actual
.iter()
.filter(|row| row.2.as_deref() == Some(host))
.map(|row| (row.0, row.1))
.collect::<Vec<_>>();
assert_eq!(expected, series, "the complete summed series for {host}");
}
assert_eq!(2 * GRID_LEN as usize, actual.len());
}
/// A tree the runtime does not execute is refused when the execution plan is built.
///
/// The runtime folds the supported `Complete` kinds now, so the tree below asks for one it still
@@ -1240,15 +1496,12 @@ fn a_tree_bound_to_another_grid_is_rejected() {
let tree = rate_tree();
let other_grid =
Arc::new(EvalGrid::try_new(GridSpec::try_new(0, GRID_STEP, GRID_LEN).unwrap()).unwrap());
let binding = FusedSeriesBinding {
grid: other_grid,
..binding(&tree)
};
let binding = FusedSeriesBinding { grid: other_grid };
let error = FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema()),
one_input(&tree, input_plan(frame_schema())),
output_schema().to_dfschema_ref().unwrap(),
)
.expect_err("the tree is not evaluated on the declared grid");
@@ -1271,15 +1524,12 @@ fn a_separately_allocated_grid_with_an_equal_spec_is_accepted() {
!Arc::ptr_eq(&equal, &binding(&tree).grid),
"the two grids are separate allocations"
);
let binding = FusedSeriesBinding {
grid: equal,
..binding(&tree)
};
FusedSeries::try_new(
let binding = FusedSeriesBinding { grid: equal };
let _node = FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema()),
one_input(&tree, input_plan(frame_schema())),
output_schema().to_dfschema_ref().unwrap(),
)
.expect("an equal grid spec is the same grid");
@@ -1471,7 +1721,7 @@ fn an_input_with_no_partitions_is_rejected_when_the_plan_is_built() {
)));
let error = plan(rate_tree(), empty).expect_err("there is no partition to run");
assert!(
error.to_string().contains("input has no partitions"),
error.to_string().contains("has no partitions"),
"refused for another reason: {error}"
);
// The only count refused is zero: two partitions build and answer, which is what the
@@ -2124,9 +2374,9 @@ fn two_field_node() -> FusedSeries {
);
FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding,
input_plan(frame_schema_of(&two_field_schema())),
one_input(&tree, input_plan(frame_schema_of(&two_field_schema()))),
two_field_output_schema().to_dfschema_ref().unwrap(),
)
.expect("the binding matches the tree")
@@ -2773,9 +3023,13 @@ fn unequal_binding_and_output_schema_are_not_ordered_equal() {
}]),
eval_grid: None,
});
let right = binding_of(&tree, other_schema, left.tags.clone());
assert_ne!(left, right);
assert_ne!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right));
let right = binding_of(
&tree,
other_schema,
vec![HOST.to_string(), NAME.to_string()],
);
assert_eq!(left, right);
assert_eq!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right));
let left_node = fused(tree.clone());
let nullability_changed = Arc::new(Schema::new(vec![
@@ -2790,9 +3044,9 @@ fn unequal_binding_and_output_schema_are_not_ordered_equal() {
]));
let right_node = FusedSeries::try_new(
Arc::from(PROMQL),
tree,
tree.clone(),
binding(&rate_tree()),
input_plan(frame_schema()),
one_input(&tree, input_plan(frame_schema())),
nullability_changed.to_dfschema_ref().unwrap(),
)
.unwrap();
+47 -60
View File
@@ -102,66 +102,53 @@ fn plan_fused_series(
physical_inputs: &[Arc<dyn ExecutionPlan>],
target_partitions: usize,
) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
let Some(input) = physical_inputs.first() else {
if physical_inputs.is_empty() {
return Ok(None);
};
let Some(scan) = input.downcast_ref::<RegionScanExec>() else {
return Ok(None);
};
let binding = fused.binding();
let Some(metric_name) = binding.metric_name.as_deref() else {
return Err(DataFusionError::Plan(
"the FusedSeries node binds no metric name, so the region scan below it cannot be \
asked for the series of one metric"
.to_string(),
}
let mut prepared = Vec::new();
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(),
));
};
let tags = binding
.tags
.iter()
.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 scan = if scan.is_partition_set() {
Arc::new(scan.clone())
} else {
let n = target_partitions.max(1);
let partitions =
table::table::scan::assign_partition_ranges(scan.get_partition_ranges(), n);
Arc::new(
scan.with_new_partitions(partitions, n)
.map_err(|e| DataFusionError::External(e.into_inner()))?,
)
};
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:?}"
)));
};
prepared.push((
series_scan.clone() as Arc<dyn ExecutionPlan>,
series_scan.label_source().clone(),
series_scan.raw_series_ordering(),
));
};
// `__name__` is the metric name rather than a column of the region, so it is not one of the
// logical tags the scan is asked to decode; the frame names each series' own metric.
let logical_tags = binding
.tags
.iter()
.filter(|tag| tag.as_str() != METRIC_NAME)
.cloned()
.collect::<Vec<_>>();
let field_names = binding
.series_schema
.fields
.iter()
.map(|field| field.name.to_string())
.collect::<Vec<_>>();
let scan = if scan.is_partition_set() {
Arc::new(scan.clone())
} else {
let partitions = table::table::scan::assign_partition_ranges(
scan.get_partition_ranges(),
target_partitions.max(1),
);
Arc::new(
scan.with_new_partitions(partitions, target_partitions.max(1))
.map_err(|error| DataFusionError::External(error.into_inner()))?,
)
};
// The scan resolves the label source and the ordering it will declare itself, against its own
// metadata snapshot, and hands both back through the leaf it builds. Naming them here instead
// would be a second copy of a binding only the scanner can make: the physical metadata and
// column ids a `RawLabelSource::PrimaryKey` carries are not reachable from a region scan's
// public surface, so the layer that resolves them is the scanner.
let Some(series_scan) =
scan.try_to_named_series_scan(metric_name, &logical_tags, &field_names)?
else {
return Err(DataFusionError::Plan(format!(
"the region scan under FusedSeries could not serve a raw series frame for metric \
{metric_name:?}: the scanner refused the raw series path for this scan, so this node \
has no input to read"
)));
};
let label_source = series_scan.label_source().clone();
let ordering = series_scan.raw_series_ordering();
fused
.to_execution_plan(series_scan, label_source, ordering)
.map(Some)
}
fused.to_execution_plan(prepared).map(Some)
}
+20 -1
View File
@@ -975,8 +975,27 @@ impl TreeNodeRewriter for EnforceDistRequirementRewriter {
type Node = LogicalPlan;
fn f_down(&mut self, node: Self::Node) -> DfResult<Transformed<Self::Node>> {
// check that node doesn't have multiple children, i.e. join/subquery
// 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.
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(),
+74 -21
View File
@@ -23,7 +23,7 @@ use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
use promql::extension_plan::{
EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize,
};
use promql::native::plan::reads_across_series;
use promql::native::plan::{NativeExpr, NativeNode};
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
use crate::dist_plan::MergeScanLogicalPlan;
@@ -243,23 +243,39 @@ impl Categorizer {
}
name if name == FusedSeries::name() => {
let fused = plan.as_any().downcast_ref::<FusedSeries>().unwrap();
// A region builds this node from the region scan itself: the conversion takes that
// A region builds this node from the region scans themselves: the conversion takes a
// scan's raw-series entrypoint and cannot look through anything in between, so a
// node whose input is not that scan has nothing to read where it would be placed
// and stays where it was planned.
if !matches!(fused.inputs().as_slice(), [LogicalPlan::TableScan(_)]) {
// node with an input that is not such a scan has nothing to read where it would be
// placed and stays where it was planned. Every input also has to read the same
// table: two tables need not share a region, and a region can only evaluate the tree
// over the scans it can build for itself.
let inputs = fused.inputs();
let mut table = None;
for input in &inputs {
let LogicalPlan::TableScan(scan) = input else {
return Commutativity::NonCommutative;
};
if table.is_some_and(|name| name != &scan.table_name) {
return Commutativity::NonCommutative;
}
table = Some(&scan.table_name);
}
// The region asks each scan for the series of one named metric, so a node with an
// input that binds no name cannot be built there at all.
if fused
.fused_inputs()
.iter()
.any(|input| input.metric_name.is_none())
{
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 fused.binding().metric_name.is_none() {
return Commutativity::NonCommutative;
}
// A region evaluates the tree over whatever series its own scan returns, so this
// is only answerable when every node of the tree reads one series at a time. An
// aggregate or a binary operation would fold or pair across series, and one region
// holds only part of them.
if reads_across_series(fused.tree().root()) {
// A region evaluates the tree over whatever series its own scans return. A window,
// a map and an instant read one series at a time, so one region's share of a series
// is everything they need of it. An aggregate folds a label set's series together
// and would fold one region's half of the group, so it stays where it was planned.
// A binary operation pairs series by label, which a region can answer for every
// pair whose two sides it holds; see the caveat below.
if folds_across_series(fused.tree().root()) {
return Commutativity::NonCommutative;
}
@@ -274,6 +290,13 @@ impl Categorizer {
// region deployment satisfies it; a partitioned table over several regions does not,
// and would return a wrong answer rather than an error.
//
// A binary operation adds one more way to be in this position: it pairs two series
// by their labels, and the two sides of one pair need not reach one region - a table
// partitioned by a column the match does not name puts `a{kind="a"}` and
// `a{kind="b"}` with the same `host` in different regions, and the region holding
// one of them finds no partner and drops the match. One region holds every series
// both scans can return, so the pair is there.
//
// What would make this unconditional is a partition key the label set determines,
// checked against the table's physical partition expressions. Until then the
// placement is a proof of concept over one region.
@@ -385,6 +408,33 @@ impl Categorizer {
}
}
/// Whether `tree` folds one label set's series into a single value.
///
/// An aggregate folds every series of a group together, so a region that holds part of the group
/// would answer the fold of its own half and the union of the parts would be a wrong query answered
/// silently. Everything else the native compiler emits reads one series at a time: an instant
/// selection, a window and a point-wise map each select, fold or map the samples of the series they
/// were handed. A binary operation pairs series rather than folding them, so it is not a fold here;
/// what a region can pair is the subject of the caveat at the placement decision. A vector operation
/// reads the whole vector at a grid point, so it folds across series the way an aggregate does.
fn folds_across_series(node: &NativeNode) -> bool {
match &node.expr {
NativeExpr::Input(_) | NativeExpr::Scalar(_) => false,
NativeExpr::Instant { input, .. }
| NativeExpr::Window { input, .. }
| NativeExpr::Map { input, .. } => folds_across_series(input),
// A binary operation pairs the two sides rather than folding either of them, so what
// decides is whether a side folds its own input.
NativeExpr::Binary { left, right, .. } => {
folds_across_series(left) || folds_across_series(right)
}
NativeExpr::Aggregate { .. } => true,
// `sort`, `absent`, `topk` and `histogram_quantile` reorder or read every series of the
// vector at a grid point, so one region's share of the series cannot answer them.
NativeExpr::Vector { .. } => true,
}
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
@@ -404,7 +454,7 @@ mod tests {
use datafusion_optimizer::analyzer::AnalyzerRule;
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::{FieldSpec, SeriesSchema};
use promql::extension_plan::{FusedSeries, FusedSeriesBinding};
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput};
use promql::functions::{
NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile,
};
@@ -491,12 +541,15 @@ mod tests {
)
.unwrap();
let binding = FusedSeriesBinding {
series_schema,
grid: statement_grid(&stmt).unwrap(),
};
let inputs = vec![FusedSeriesInput {
series_schema,
metric_name: metric_name.map(Arc::from),
time_index: "ts".to_string(),
tags: Vec::new(),
};
input,
}];
let output_schema: DFSchemaRef = Arc::new(
DFSchema::new_with_metadata(
vec![
@@ -524,7 +577,7 @@ mod tests {
Arc::from("some_metric"),
tree,
binding,
input,
inputs,
output_schema,
)
.unwrap(),
@@ -744,7 +797,7 @@ mod tests {
grid: statement_grid(&native_statement()).unwrap(),
})),
};
assert!(reads_across_series(&aggregate));
assert!(folds_across_series(&aggregate));
// The same walk over what the compiler emits stays per-series.
let single_selector = compile(
@@ -756,7 +809,7 @@ mod tests {
SeriesOrdering::KeyThenTime,
)
.unwrap();
assert!(!reads_across_series(single_selector.root()));
assert!(!folds_across_series(single_selector.root()));
}
/// The encoding gate is what kept the node on the frontend, and it only exists for a plan that
+9 -4
View File
@@ -497,7 +497,9 @@ mod test {
use datatypes::schema::ColumnSchema;
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::{FieldSpec, SeriesSchema};
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, RangeManipulate};
use promql::extension_plan::{
FusedSeries, FusedSeriesBinding, FusedSeriesInput, RangeManipulate,
};
use promql_parser::parser;
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
@@ -1582,12 +1584,15 @@ mod test {
)
.unwrap();
let binding = FusedSeriesBinding {
series_schema,
grid: statement_grid(&stmt).unwrap(),
};
let inputs = vec![FusedSeriesInput {
series_schema,
metric_name: Some("some_metric".into()),
time_index: "ts".to_string(),
tags: Vec::new(),
};
input,
}];
let output_schema: DFSchemaRef = Arc::new(
DFSchema::new_with_metadata(
vec![
@@ -1612,7 +1617,7 @@ mod test {
Arc::from("some_metric"),
tree,
binding,
input,
inputs,
output_schema,
)
.unwrap(),
+9
View File
@@ -345,6 +345,15 @@ impl PromPlanner {
if let Some(plan) = planner.try_plan_native_fused(&stmt.expr).await? {
return planner.strip_tsid_column(plan);
}
// `TQL EXPLAIN` wraps the query it explains in an extension node, and a reader asks for that
// explanation to see the plan the query actually runs. Offering the wrapper itself would
// decline every time - it is not a shape a tree has a node for - and the answer would show
// the existing path's plan even where the native route is the one that runs. The two
// `EXPLAIN` forms are therefore offered their body, which is wrapped the same way the
// existing path wraps it.
if let Some(plan) = planner.try_plan_native_fused_explain(&stmt.expr).await? {
return planner.strip_tsid_column(plan);
}
let plan = planner
.prom_root_expr_to_plan(&stmt.expr, query_engine_state)
+450 -237
View File
@@ -34,12 +34,14 @@ use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE, MITO2_ENGINE};
use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit};
use datafusion::common::{DFSchema, DFSchemaRef};
use datafusion::error::DataFusionError;
use datafusion::logical_expr::{Extension, LogicalPlan, TableScanBuilder};
use datafusion::logical_expr::{Extension, LogicalPlan, LogicalPlanBuilder, TableScanBuilder};
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};
use promql::native::plan::reads_across_series;
use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput};
use promql::native::plan::{NativeExpr, reads_across_series};
use promql_parser::label::Matchers;
use promql_parser::parser::value::ValueType;
use promql_parser::parser::{
EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, VectorSelector,
@@ -48,8 +50,9 @@ use session::context::QueryContextRef;
use snafu::ResultExt;
use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME};
use crate::parser::{EXPLAIN_NODE_NAME, EXPLAIN_VERBOSE_NODE_NAME};
use crate::promql::error::{DataFusionPlanningSnafu, Result};
use crate::promql::native_compile::{compile, statement_grid};
use crate::promql::native_compile::{compile_selectors, statement_grid};
use crate::promql::planner::PromPlanner;
/// The query-context key that turns the native fused-series route on for one query.
@@ -119,218 +122,355 @@ impl PromPlanner {
return Ok(None);
}
// A tree reads exactly one raw input, and the scan below the node is that one selector's,
// so a shape that names no selector or more than one is not offered at all.
let Some(selector) = single_selector(prom_expr) else {
return Ok(None);
let selectors = {
let mut values = Vec::new();
collect_selectors(prom_expr, &mut values);
values
};
// Resolve the selector the way the existing planner does, and take what is left as the
// rows it selects. The scan below the node is the selector's own scan, unfiltered, so a
// matcher that survives preprocessing selects fewer rows here than the scan reads.
let matchers = self.preprocess_label_matchers(&selector.matchers, &selector.name)?;
if !matchers.matchers.is_empty() {
return Ok(None);
}
// An `__field__` matcher narrows the field columns the existing planner builds its scan
// with; folding every field of the table instead would evaluate a different window.
if self.ctx.field_column_matcher.is_some() {
return Ok(None);
}
// A metric without a table reads as an empty metric, which the existing planner plans.
if self.setup_context().await?.is_some() {
return Ok(None);
}
let Some(table_name) = self.ctx.table_name.clone() else {
return Ok(None);
};
let Some(time_index) = self.ctx.time_index_column.clone() else {
return Ok(None);
};
let fields = self.ctx.field_columns.clone();
let tags = self.ctx.tag_columns.clone();
// A series with no field has nothing to fold, and the tree's input would be an empty
// schema, which no window can read.
if fields.is_empty() {
return Ok(None);
}
// The selector's own table scan, built by the same method the existing path uses: the
// physical planner turns it into the region scan the node reads, and building a scan here
// instead would let the two paths disagree about the columns they read.
let table_ref = self.table_ref()?;
let mut input = self.create_table_scan_plan(table_ref.clone()).await?;
let logical_scan = metric_scan_and_table_id(&input);
let has_verified_metric_rewrite = logical_scan.is_some();
let scan = match logical_scan {
Some((mut scan, predicate)) => {
// Preserve logical field order and the table restriction on the direct physical scan.
let source_schema = scan.source.schema();
let Some(mut ordered_projection) = fields
.iter()
.map(|field| source_schema.index_of(field).ok())
.collect::<Option<Vec<_>>>()
else {
return Ok(None);
};
let original_projection = scan.projection.as_ref();
let selected_indices = original_projection
.cloned()
.unwrap_or_else(|| (0..source_schema.fields().len()).collect());
for index in selected_indices {
let is_field = fields
.iter()
.any(|field| field == source_schema.field(index).name());
if !is_field && !ordered_projection.contains(&index) {
ordered_projection.push(index);
}
}
scan.filters.push(predicate);
scan = TableScanBuilder::from(scan)
.with_projection(Some(ordered_projection))
.build()
.context(DataFusionPlanningSnafu)?;
input = LogicalPlan::TableScan(scan.clone());
scan
}
None => match &input {
LogicalPlan::TableScan(scan) => scan.clone(),
_ => return Ok(None),
},
};
let table = self.table_from_source(&scan.source)?;
let table_meta = &table.table_info().meta;
// An engine without a raw-series scanner has no frame to give this node, and by the time
// the physical planner asks, the logical plan is already this node: the refusal there is a
// planning error, not a fallback. So the engine is checked here, where the existing plan is
// still the answer. A file-engine table is the concrete case: its scanner is a
// `SinglePartitionScanner`, which leaves `raw_series_schema` at the default `None`.
if !supports_native_raw_series(&table_meta.engine)
|| (table_meta.engine == METRIC_ENGINE_NAME && !has_verified_metric_rewrite)
{
return Ok(None);
}
// The region's raw-series preflight refuses these, and the physical layer turns that refusal into an error, so decline this route here instead.
let time_index_type = table_meta
.schema
.timestamp_column()
.map(|column| &column.data_type);
if time_index_type
!= Some(&datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype())
|| table_meta
.options
.extra_options
.get(store_api::mito_engine_options::APPEND_MODE_KEY)
.is_some_and(|value| value.eq_ignore_ascii_case("true"))
{
return Ok(None);
}
// FusedSeries evaluates each region independently, so partition keys must identify a series.
if !table
.table_info()
.meta
.partition_column_names()
.all(|column| tags.iter().any(|tag| tag == column))
{
return Ok(None);
}
// The legacy selector converts an offset the same way; sharing that conversion keeps the
// two scan paths from disagreeing about an extreme duration.
let offset = Self::offset_millis(&selector.offset);
let (saved_start, saved_end, saved_range) = (self.ctx.start, self.ctx.end, self.ctx.range);
self.ctx.range = selector_range_millis(prom_expr);
// Keep the fused scan's bounds identical to the legacy selector scan, including @ and offset.
let time_filter = (|| {
let anchored = self.at_modifier_offset(&selector.at, &selector.offset)?;
if anchored.is_some() {
self.ctx.end = saved_start;
}
self.build_time_index_filter(anchored.unwrap_or(offset), input.schema())
})();
self.ctx.start = saved_start;
self.ctx.end = saved_end;
self.ctx.range = saved_range;
let time_filter = time_filter?;
if let Some(filter) = time_filter {
let LogicalPlan::TableScan(scan) = &mut input else {
unreachable!();
};
scan.filters.push(filter);
}
// A window over a native histogram yields a histogram, which the output schema below
// cannot declare; the existing path evaluates those with its own kernels.
if Self::field_columns_contain_native_histogram(input.schema(), &fields) {
return Ok(None);
}
// The region's raw series preflight serves a field only when it is numeric or a native
// histogram, and the physical layer turns that refusal into a planning error because the
// logical plan is already fixed by then. A table whose selected fields are, say, a string
// and a boolean therefore has to be declined here, while the existing plan is still the
// fallback - `stringsfield` over such a table answered normally before this route existed.
if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) {
if selectors.is_empty() {
return Ok(None);
}
let Some(stmt) = self.native_statement(prom_expr) else {
return Ok(None);
};
let Ok(grid) = statement_grid(&stmt) else {
// The statement's grid is not one a tree can be evaluated on, so there is no grid to
// address the node's output by.
return Ok(None);
};
let series_schema = Arc::new(SeriesSchema {
fields: fields
.iter()
.map(|name| FieldSpec {
name: Arc::from(name.as_str()),
})
.collect::<Vec<_>>()
.into(),
eval_grid: None,
});
let tree = match compile(&stmt, Arc::clone(&series_schema), NATIVE_ORDERING) {
Ok(tree) => tree,
// The compiler refusing a shape is this route declining it: the existing planner gets
// the query exactly as it would have without this flag.
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
};
// A vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) reads the whole
// vector at each grid point rather than one series at a time, so it cannot be evaluated by
// one executor per scan partition. Declining here is the only place that still works: once
// the `FusedSeries` node exists the logical plan is fixed, and the categorizer merely
// declining to push it down would leave a node the physical layer must build anyway.
if reads_across_series(tree.root()) {
let original_context = self.ctx.clone();
let mut prepared: Vec<FusedSeriesInput> = Vec::new();
for selector in &selectors {
self.ctx = original_context.clone();
let matchers = match self.preprocess_label_matchers(&selector.matchers, &selector.name)
{
Ok(m) => m,
Err(_) => return Ok(None),
};
if self.setup_context().await?.is_some() {
return Ok(None);
}
let (Some(metric), Some(time)) = (
self.ctx.table_name.clone(),
self.ctx.time_index_column.clone(),
) else {
return Ok(None);
};
let tags = self.ctx.tag_columns.clone();
let fields = self.ctx.field_columns.clone();
// A `__field__` matcher narrows the field set in a projection the existing planner
// builds, and the raw series scan below this node has no equivalent: it reports every
// field the scan carries. Binding all of them would fold fields the query excluded, so
// the route is declined until the field selector is reused here.
if self.ctx.field_column_matcher.is_some() || fields.is_empty() {
return Ok(None);
}
// The selector's own table scan, built by the same method the existing path uses:
// the physical planner turns it into the region scan the node reads, and building a
// scan here instead would let the two paths disagree about the columns they read.
let table_ref = self.table_ref()?;
let mut input = self.create_table_scan_plan(table_ref).await?;
let logical_scan = metric_scan_and_table_id(&input);
let has_verified_metric_rewrite = logical_scan.is_some();
let scan = match logical_scan {
Some((mut scan, predicate)) => {
// Preserve logical field order and the table restriction on the direct
// physical scan.
let source_schema = scan.source.schema();
let Some(mut ordered_projection) = fields
.iter()
.map(|field| source_schema.index_of(field).ok())
.collect::<Option<Vec<_>>>()
else {
return Ok(None);
};
let original_projection = scan.projection.as_ref();
let selected_indices = original_projection
.cloned()
.unwrap_or_else(|| (0..source_schema.fields().len()).collect());
for index in selected_indices {
let is_field = fields
.iter()
.any(|field| field == source_schema.field(index).name());
if !is_field && !ordered_projection.contains(&index) {
ordered_projection.push(index);
}
}
scan.filters.push(predicate);
scan = TableScanBuilder::from(scan)
.with_projection(Some(ordered_projection))
.build()
.context(DataFusionPlanningSnafu)?;
input = LogicalPlan::TableScan(scan.clone());
scan
}
None => match &input {
LogicalPlan::TableScan(scan) => scan.clone(),
_ => return Ok(None),
},
};
let table = self.table_from_source(&scan.source)?;
let table_meta = &table.table_info().meta;
// An engine without a raw-series scanner has no frame to give this node, and by the
// time the physical planner asks, the logical plan is already this node: the refusal
// there is a planning error, not a fallback. So the engine is checked here, where the
// existing plan is still the answer. A file-engine table is the concrete case: its
// scanner is a `SinglePartitionScanner`, which leaves `raw_series_schema` at the
// default `None`. A metric-engine table is served only through the logical rewrite
// recognised above, which is what makes its series the table's own.
if !supports_native_raw_series(&table_meta.engine)
|| (table_meta.engine == METRIC_ENGINE_NAME && !has_verified_metric_rewrite)
{
return Ok(None);
}
// The region's raw-series preflight refuses these, and the physical layer turns that
// refusal into an error, so decline this route here instead.
let time_index_type = table_meta
.schema
.timestamp_column()
.map(|column| &column.data_type);
if time_index_type
!= Some(&datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype())
|| table_meta
.options
.extra_options
.get(store_api::mito_engine_options::APPEND_MODE_KEY)
.is_some_and(|value| value.eq_ignore_ascii_case("true"))
{
return Ok(None);
}
// FusedSeries evaluates each region independently, so partition keys must identify a
// series.
if !table
.table_info()
.meta
.partition_column_names()
.all(|column| tags.iter().any(|tag| tag == column))
{
return Ok(None);
}
// A window over a native histogram yields a histogram, which the output schema below
// cannot declare; the existing path evaluates those with its own kernels.
if Self::field_columns_contain_native_histogram(input.schema(), &fields) {
return Ok(None);
}
// The region's raw series preflight serves a field only when it is numeric or a native
// histogram, and the physical layer turns that refusal into a planning error because
// the logical plan is already fixed by then. A table whose selected fields are, say, a
// string and a boolean therefore has to be declined here, while the existing plan is
// still the fallback - `stringsfield` over such a table answered normally before this
// route existed.
if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) {
return Ok(None);
}
let series_schema = Arc::new(SeriesSchema {
fields: fields
.iter()
.map(|name| FieldSpec {
name: Arc::from(name.as_str()),
})
.collect::<Vec<_>>()
.into(),
eval_grid: None,
});
// The row filter is the selector's own: the time range is added after compiling,
// because only the compiler knows whether this occurrence reads a window or one
// instant.
let mut filters = Self::matchers_to_expr(matchers, input.schema())?;
if let LogicalPlan::TableScan(table_scan) = &mut input {
table_scan.filters.append(&mut filters);
} else {
return Ok(None);
}
prepared.push(FusedSeriesInput {
series_schema,
metric_name: Some(Arc::from(metric)),
time_index: time,
tags,
input,
});
}
self.ctx = original_context;
if prepared
.windows(2)
.any(|w| w[0].time_index != w[1].time_index || w[0].tags != w[1].tags)
{
return Ok(None);
}
let binding = FusedSeriesBinding {
series_schema,
// The tree's own output is evaluated on the statement's grid, and the binding names
// the same one, so a chunk's absolute positions are read on the grid it was computed
// on.
grid,
metric_name: Some(Arc::from(table_name.as_str())),
time_index: time_index.clone(),
tags: tags.clone(),
// The compiler binds one input per selector in the same pre-order `collect_selectors`
// walks, so position i of both lists is the same occurrence. This is the guard that the
// two walks agree: a mismatch is a compiler defect, not a query this route can plan.
let identities: Vec<(Option<String>, Matchers, i64, Option<i64>)> = selectors
.iter()
.map(|selector| {
let offset_ms = selector
.offset
.as_ref()
.map(|o| match o {
promql_parser::parser::Offset::Pos(d) => d.as_millis() as i64,
promql_parser::parser::Offset::Neg(d) => -(d.as_millis() as i64),
})
.unwrap_or_default();
Ok((
selector.name.clone(),
selector.matchers.clone(),
offset_ms,
self.at_ref_time(&selector.at, &selector.offset)?,
))
})
.collect::<Result<Vec<_>>>()?;
let bind_index = std::cell::Cell::new(0usize);
let compiled = match compile_selectors(
&stmt,
&|req| {
let i = bind_index.get();
bind_index.set(i + 1);
let (Some(prepared_input), Some(identity)) = (prepared.get(i), identities.get(i))
else {
return Err(DataFusionError::Internal(
"a selector was bound that the planner did not prepare".into(),
));
};
if *identity
!= (
req.metric.clone(),
req.matchers.clone(),
req.offset_ms,
req.at_ms,
)
{
return Err(DataFusionError::Internal(
"the compiler and the planner walk the selectors differently".into(),
));
}
Ok(Arc::clone(&prepared_input.series_schema))
},
NATIVE_ORDERING,
) {
Ok(v) => v,
// The compiler refusing a shape is this route declining it.
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
Err(e) => return Err(e).context(DataFusionPlanningSnafu),
};
let output_schema = fused_output_schema(&fields, &tags, &time_index)?;
// An aggregate or a vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...)
// reads the whole vector at each grid point rather than one series at a time, so it cannot
// be evaluated by one executor per scan partition. Declining here is the only place that
// still works: once the `FusedSeries` node exists the logical plan is fixed, and the
// categorizer merely declining to push it down would leave a node the physical layer must
// build anyway. A binary operation pairs one series with another and reads each of them
// point-wise, so a tree rooted in one keeps the route: its operands are the independent
// scans prepared above.
//
// TEMPORARY: the exception below is stated over the root alone, while the classifier it
// narrows is a whole-tree walk. The two have to be reconciled with the per-operand
// point-wise check the shared gate will own, so this narrowing is the first stage's anchor
// rather than the shape to keep.
if !matches!(compiled.tree.root().expr, NativeExpr::Binary { .. })
&& reads_across_series(compiled.tree.root())
{
return Ok(None);
}
if compiled.inputs.len() != prepared.len() {
return Err(DataFusionError::Internal(
"the compiled tree reads a different number of inputs than the planner prepared"
.into(),
))
.context(DataFusionPlanningSnafu);
}
let mut inputs = Vec::with_capacity(prepared.len());
for (index, (compiled_input, mut input)) in compiled.inputs.iter().zip(prepared).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.
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) {
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"
)))
.context(DataFusionPlanningSnafu);
}
input.input = scan;
inputs.push(input);
}
let root_fields = compiled
.tree
.root()
.output
.samples()
.ok_or_else(|| DataFusionError::Internal("native tree root has no samples".into()))
.context(DataFusionPlanningSnafu)?
.fields
.iter()
.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)
})
}) {
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()),
tree,
binding,
input,
compiled.tree,
FusedSeriesBinding { grid },
inputs,
output_schema,
)
.context(DataFusionPlanningSnafu)?;
Ok(Some(LogicalPlan::Extension(Extension {
node: Arc::new(node),
})))
}
/// Offers an `EXPLAIN` statement's body to the native compiler, and wraps the plan it makes.
///
/// `TQL EXPLAIN (…) <query>` is the statement whose root extension wraps the query, and the
/// explanation a reader gets should be of the plan that query runs. Only the two plain
/// explanations are handled: `ANALYZE`, which runs the plan and reports its metrics, and
/// `EXPLAIN VERBOSE` are left to the existing path, so this adds nothing to what those report.
pub(super) async fn try_plan_native_fused_explain(
&mut self,
prom_expr: &PromExpr,
) -> Result<Option<LogicalPlan>> {
let PromExpr::Extension(extension) = prom_expr else {
return Ok(None);
};
let explain = match extension.expr.name() {
EXPLAIN_NODE_NAME => false,
EXPLAIN_VERBOSE_NODE_NAME => true,
_ => return Ok(None),
};
let children = extension.expr.children();
let [body] = children else {
return Ok(None);
};
let Some(plan) = self.try_plan_native_fused(body).await? else {
return Ok(None);
};
Ok(Some(
LogicalPlanBuilder::from(plan)
.explain(explain, false)
.context(DataFusionPlanningSnafu)?
.build()
.context(DataFusionPlanningSnafu)?,
))
}
/// The statement being planned, rebuilt from the evaluation numbers the planner holds.
///
/// The compiler reads the statement's grid, lookback and `@` anchors rather than the planner's
@@ -354,6 +494,87 @@ impl PromPlanner {
}
}
/// The time-range filter a selector's scan reads, from the bounds its compiled requirement names.
///
/// The lower edge is exclusive unless the requirement says otherwise, which is how a window and a
/// positive lookback read; an inclusive edge is what a zero lookback instant selection has. The
/// bound is expressed in the scan's own timestamp unit, and a bound that unit cannot represent is
/// left out rather than widened: the other side still prunes, and the evaluator applies the exact
/// rule either way.
fn scan_time_filter(
start: i64,
end: i64,
inclusive: bool,
schema: &DFSchema,
time_column: &str,
) -> Result<Option<DfExpr>> {
use datafusion::scalar::ScalarValue;
let Some(index) = schema.index_of_column_by_name(None, time_column) else {
return Ok(None);
};
let unit = match &schema.field(index).data_type() {
arrow::datatypes::DataType::Timestamp(unit, _) => *unit,
_ => return Ok(None),
};
let native = |milliseconds: i128| match unit {
arrow::datatypes::TimeUnit::Second => milliseconds.div_euclid(1_000),
arrow::datatypes::TimeUnit::Millisecond => milliseconds,
arrow::datatypes::TimeUnit::Microsecond => milliseconds * 1_000,
arrow::datatypes::TimeUnit::Nanosecond => milliseconds * 1_000_000,
};
let literal = |milliseconds: i128| -> Option<DfExpr> {
let value = i64::try_from(native(milliseconds)).ok()?;
Some(DfExpr::Literal(
match unit {
arrow::datatypes::TimeUnit::Second => {
ScalarValue::TimestampSecond(Some(value), None)
}
arrow::datatypes::TimeUnit::Millisecond => {
ScalarValue::TimestampMillisecond(Some(value), None)
}
arrow::datatypes::TimeUnit::Microsecond => {
ScalarValue::TimestampMicrosecond(Some(value), None)
}
arrow::datatypes::TimeUnit::Nanosecond => {
ScalarValue::TimestampNanosecond(Some(value), None)
}
},
None,
))
};
let column = DfExpr::Column(datafusion::common::Column::from_name(time_column));
let lower = literal(i128::from(start)).map(|literal| {
if inclusive {
column.clone().gt_eq(literal)
} else if unit == arrow::datatypes::TimeUnit::Millisecond {
// An exclusive edge on a millisecond axis is the next representable instant, which is
// how the existing selector filter states it.
literal_or_next(start).map_or_else(
|| column.clone().gt(literal.clone()),
|next| column.clone().gt_eq(next),
)
} else {
column.clone().gt(literal)
}
});
let upper = literal(i128::from(end)).map(|literal| column.clone().lt_eq(literal));
Ok(match (lower, upper) {
(Some(lower), Some(upper)) => Some(lower.and(upper)),
(Some(one), None) | (None, Some(one)) => Some(one),
(None, None) => None,
})
}
/// The literal one millisecond after `start`, for an exclusive lower edge on a millisecond axis.
fn literal_or_next(start: i64) -> Option<DfExpr> {
use datafusion::scalar::ScalarValue;
let next = start.checked_add(1)?;
Some(DfExpr::Literal(
ScalarValue::TimestampMillisecond(Some(next), None),
None,
))
}
/// The columns a [`FusedSeries`] node produces.
///
/// The shape is the one the existing unary pipeline consumes — the time index, then the series
@@ -394,22 +615,43 @@ fn fused_output_schema(
))
}
/// The one selector `expr` folds, if it names exactly one.
/// Every selector `expr` reads, in the order the compiler binds them.
///
/// The walk follows the grammar the native compiler accepts — a call, a range selector, a selector
/// and parentheses — and stops at every other shape, because a shape the compiler cannot compile
/// needs no selector resolved. Two distinct selectors are not one input, and a tree built over the
/// wrong one of them would evaluate a window the query did not write.
fn selector_range_millis(expr: &PromExpr) -> Option<i64> {
/// The order is the compiler's own: it compiles a node's operands in the order they were written, so
/// this walk goes into the same children in the same order. The list is then matched position by
/// position against the compiled inputs, which is what makes a walk that visits a different set the
/// signal that the two disagree rather than a silent mismatch of selector to scan.
fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>) {
match expr {
PromExpr::MatrixSelector(matrix) => Some(matrix.range.as_millis() as i64),
PromExpr::Paren(paren) => selector_range_millis(&paren.expr),
PromExpr::Call(call) => call
.args
.args
.iter()
.find_map(|arg| selector_range_millis(arg)),
_ => None,
PromExpr::VectorSelector(selector) => out.push(selector),
PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => out.push(vs),
PromExpr::Paren(ParenExpr { expr }) => collect_selectors(expr, out),
// Left before right, because a non-commutative operator means what that order says.
PromExpr::Binary(binary) => {
collect_selectors(&binary.lhs, out);
collect_selectors(&binary.rhs, out);
}
// The compiler folds a negation into a multiplication whose operand comes second, but the
// selector is the only thing this walk collects, so the order inside one subtree does not
// depend on where the constant sits.
PromExpr::Unary(unary) => collect_selectors(&unary.expr, out),
PromExpr::Call(call) => {
// A label rewrite adds a label the node's output schema cannot declare: that schema is
// built from the table's own tags, so folding `label_replace`/`label_join` in would
// silently drop the destination label the existing plan projects.
if matches!(call.func.name, "label_replace" | "label_join") {
return;
}
for arg in &call.args.args {
collect_selectors(arg, out);
}
}
// An aggregate's parameter is a constant, so only its input holds a selector.
PromExpr::Aggregate(aggregate) => collect_selectors(&aggregate.expr, out),
// A subquery evaluates its own expression on a grid of its own, and the compiler binds that
// expression's selectors before the window above them.
PromExpr::Subquery(subquery) => collect_selectors(&subquery.expr, out),
_ => {}
}
}
@@ -455,35 +697,6 @@ fn metric_scan_and_table_id(
Some((scan.clone(), filter.predicate.clone()))
}
fn single_selector(expr: &PromExpr) -> Option<&VectorSelector> {
let mut selectors = Vec::new();
collect_selectors(expr, &mut selectors);
match selectors.as_slice() {
[only] => Some(only),
_ => None,
}
}
fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>) {
match expr {
PromExpr::VectorSelector(selector) => out.push(selector),
PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => out.push(vs),
PromExpr::Paren(ParenExpr { expr }) => collect_selectors(expr, out),
PromExpr::Call(call) => {
// A label rewrite adds a label the node's output schema cannot declare: that schema is
// built from the table's own tags, so folding `label_replace`/`label_join` in would
// silently drop the destination label the existing plan projects.
if matches!(call.func.name, "label_replace" | "label_join") {
return;
}
for arg in &call.args.args {
collect_selectors(arg, out);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
+54 -2
View File
@@ -1792,6 +1792,55 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> {
plan.inputs().into_iter().find_map(find_fused_series)
}
#[tokio::test]
async fn native_fused_binary_has_two_independent_scans() {
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!(2, fused.fused_inputs().len());
}
#[tokio::test]
async fn native_fused_binary_matchers_are_per_scan() {
let plan = build_native_fused_plan(
"some_metric{tag_0=\"a\"} + on(tag_0) some_metric{tag_0=\"b\"}",
true,
)
.await;
let fused = find_fused_series(&plan).expect("native binary fused route");
assert_eq!(2, fused.fused_inputs().len());
let scans = fused
.fused_inputs()
.iter()
.map(|input| match &input.input {
LogicalPlan::TableScan(scan) => scan,
other => panic!("expected TableScan, got {other:?}"),
})
.collect::<Vec<_>>();
assert_eq!(2, scans[0].filters.len());
assert_eq!(2, scans[1].filters.len());
let left = scans[0]
.filters
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(" AND ");
let right = scans[1]
.filters
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(" AND ");
assert!(left.contains("a"), "{left}");
assert!(right.contains("b"), "{right}");
assert_ne!(left, right);
}
#[tokio::test]
async fn native_fused_binary_flag_off_has_no_fused_node() {
let plan = build_native_fused_plan("some_metric + some_metric", false).await;
assert!(find_fused_series(&plan).is_none());
}
/// The flag on and a shape the compiler accepts: the statement plans to one native node.
#[tokio::test]
async fn native_fused_rate_plans_to_a_fused_series_node() {
@@ -2190,12 +2239,15 @@ async fn native_fused_whole_vector_operation_falls_back() {
#[tokio::test]
async fn native_fused_unsupported_shape_falls_back() {
let plan = build_native_fused_plan("sum(rate(some_metric[5m]))", true).await;
// A set operator combines two vectors' series rather than their values, which no node of the
// tree does, so this is a shape the compiler names and declines.
let query = "some_metric and on(tag_0) some_metric";
let plan = build_native_fused_plan(query, true).await;
let display = plan.display_indent().to_string();
assert!(!display.contains("FusedSeries"), "{display}");
// Falling back is not an approximation of the existing plan: it is the existing plan.
let without_flag = build_native_fused_plan("sum(rate(some_metric[5m]))", false).await;
let without_flag = build_native_fused_plan(query, false).await;
assert_eq!(display, without_flag.display_indent().to_string());
}