feat(promql): wire complete aggregation over parallel fused partitions (#9933)

I hereby agree to the terms of the [GreptimeDB
CLA](https://github.com/GreptimeTeam/.github/blob/main/CLA.md).

## Refer to a related PR or issue link (optional)

- Rebased onto `narthex` at `bd6be2cf8f83b04280d3113467563ae81005e2f3`,
including merged #9868, #9937, #9914, #9870, #9871 and #9896. This PR no
longer depends on the old #9896 feature branch.
- Builds on the existing native Complete aggregate runtime from #9873.
#9936 can be restacked after this PR merges.

## What's changed and what's your intention?

Connect Complete aggregation to the current experimental native PromQL
execution path while preserving actual partition-local evaluation:

```text
SeriesScanExec N → FusedSeriesExec N → complete partial accumulator states N
    → CoalescePartitionsExec → FloatMerger → AggregateFinalizeExec 1 → ordinary RecordBatch
```

### Execution and current API adaptations

- Keep #9896's `FusedSeries.children`, physical children,
`BoundInput.source_index`, and existing ordinary multi-input execution.
An optional `partial_fold` changes only the output mode: ordinary
executions still emit query rows; aggregate producers fold evaluated
chunks into complete accumulator state and export it only after
successful input EOF. The aggregate path currently has one actual scan
child, with a separate evaluator for each of its N partitions; no gather
is inserted before evaluation.
- Split at the innermost supported Complete aggregate. The existing
`FloatMerger` combines full state, not finalized partition answers:
average retains count and compensated sum, and variance retains count,
mean and M2. The finalizer waits for all producer input to end
successfully before running the global suffix or returning rows. A late
source error fails the query rather than returning an incomplete
aggregate.
- Build the suffix as a separate `NativeTree`. Its `source_index = 0`
names its own evaluated input, not the original scan. Obtain the actual
input from `NativeExecutionState::input_ids(0)` and call
`NativeExecutor::push_evaluated(InputId, chunk)`; do not equate a source
index with a runtime input ID. No `NodePath` or flat executor is
restored.
- Use current `SeriesLabels` and the raw field layout from Native Input
output samples, without restoring a separate scan-schema mirror. Reuse
the existing row converter for final output. State and output
reservations are execution-local and released on errors and stream drop,
including when a physical plan is retained for another execution.
- Preserve `sum`, `avg`, `count`, `min`, `max`, `group`, `stddev` and
`stdvar`, `by` / `without`, maps and nested aggregate suffixes. Literal
scalar broadcasts work below the cut (`sum(8 * rate(...))`, `max(10 -
rate(...))`) and above it (`100 - avg(...)`, `sum(...) * 2`, `100 /
sum(...)`, `-sum(...)`), keeping subtraction and division operand order.
- Compose the current selector matcher/time-bound filters with aggregate
planning. Add `sum(rate(counter{job="a"}[5m]))` to the existing
standalone fixture; the independently expected answer is 9.

**The private state-row `RecordBatch` codec remains a temporary
bridge.** Producer, codec and finalizer retain the explanation that
future native final aggregation should consume series frames directly,
eliminating the intermediate state-row encoding, decoding and
reconstruction. This PR does not implement that replacement.

### Scope and compatibility

The supported target is standalone, one Region, multiple nonempty scan
partitions, with in-process region transport and the existing
engine/per-query native opt-ins. Ordinary Fused input traversal is not
redesigned. There is no cross-Region series merge, generic Exchange,
multi-input Aggregate Join, distributed Partial/Final architecture, new
public configuration, persisted format or wire format. No performance or
CPU-overlap improvement is claimed. Unsupported aggregate topologies
remain outside this PoC.

### Verification

All commands below passed on exact head
`9720e1bf88a776bd017b304152a055e1735d4ba1`, over the narthex base above,
using `RUST_MIN_STACK=8388608`, a dedicated external Cargo target, and
no test retries:

- `cargo fmt -p promql -p query -p tests-integration -- --check`
- `cargo check --locked -p query -p promql --all-targets`
- `cargo check --locked -p tests-integration --all-targets`
- `cargo nextest run --locked -p query -p promql --no-fail-fast
--retries 0` — **1967 passed, 2 skipped**.
- `cargo nextest run --locked -p tests-integration --lib --no-fail-fast
--retries 0 -E
'test(native_aggregate_complete_over_four_nonempty_mito_partitions) |
test(native_promql_)'` — **16 passed, 251 skipped**.
- `cargo clippy --locked -p query -p promql --all-targets --all-features
-- -D warnings`
- `cargo clippy --locked -p tests-integration --all-targets
--all-features -- -D warnings`
- `git diff --check bd6be2cf8f83b04280d3113467563ae81005e2f3..HEAD`
- `hawkeye format --dry-run` and `hawkeye check`

The standalone aggregate case checks typed physical-plan structure as
well as results: `SeriesScanExec` and partial Fused each retain four
partitions, with no intervening exchange; the finalizer consumes the
producer's state schema and answers one partition. For unfiltered
counter cases all four evaluators must report positive contributions,
totaling five and at most two per partition, forcing the three-member
group across partitions. Results are checked for labels, timestamps,
columns, values and multiplicity against independent expectations, in
addition to legacy execution.

The five nonzero counter rates are 1/3/5/2/4: total sum 15; per-job sums
9/6, means 3/3, counts 3/2 and standard deviations sqrt(8/3)/1. Scalar
cases include `sum(8 * rate(...)) = 120`, `max(10 - rate(...)) = 9`,
`100 - avg(...) = 97`, `100 / sum(...) = 100/15` and unary minus = -15.
The subtraction prefix distinguishes an incorrectly moved suffix (5) or
reversed operands (-5). The matcher selects three series, so only that
case does not require four nonempty partitions; all unfiltered
assertions remain intact.

Unit coverage includes all eight accumulator kinds, unequal producer
counts (one value versus two, so the merged mean is 6 rather than the
mean-of-means 5), nested/map/scalar suffixes, empty input, producer read
barriers, late errors, and reservation/drop boundaries. Local
full-workspace tests, an HTTP smoke run and native SQLness have not been
run; the SQLness runner does not carry the per-query native hint.
Final-head CI for `9720e1bf88a776bd017b304152a055e1735d4ba1` has
completed: [Rust
CI](https://github.com/GreptimeTeam/greptimedb/actions/runs/40201361500),
[Checks](https://github.com/GreptimeTeam/greptimedb/actions/runs/40201361419),
[Integration
CI](https://github.com/GreptimeTeam/greptimedb/actions/runs/40201361402)
all succeeded. The final check rollup contains 40 successful checks and
2 skipped checks, with no pending or failed checks. An earlier Semantic
Pull Request run was cancelled and superseded by a successful run; the
current Semantic PR title check passed. No workflow reruns were
requested.

## PR Checklist
Please convert it to a draft if some of the following conditions are not
met.

- [x] I have written the necessary rustdoc comments.
- [x] I have added the necessary unit tests and integration tests.
- [ ] This PR requires documentation updates.
- [x] API changes are backward compatible.
- [x] Schema or data changes are backward compatible.
- [ ] This PR needs to be backported to release branches, and I have
added the `backport-<target>` labels (e.g. `backport-v1.3` targets
`release/v1.3`).
This commit is contained in:
discord9
2026-10-26 00:06:35 +08:00
committed by GitHub
20 changed files with 6877 additions and 113 deletions
+268 -39
View File
@@ -25,8 +25,10 @@
//! gives the exact 1. Explicit NaN and infinite inputs follow the same rules as the serial fold. Where the serial fold keeps the first of two equal
//! values, as `min` and `max` do for `0` and `-0`, a merge keeps the one merged first.
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::mem::size_of;
use std::sync::Arc;
use datafusion::error::{DataFusionError, Result};
@@ -34,8 +36,9 @@ use datatypes::series::SeriesLabels;
use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
use crate::aggregate::{
AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, LabelKey, count_series,
finish_groups, kahan_inc, label_key,
AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, LabelKey,
btree_backing_bytes, count_series, finish_groups, finish_groups_budgeted,
hash_map_backing_bytes, kahan_inc, label_key, metric_bytes, next_hash_capacity,
};
use crate::map::validate_float_series;
@@ -99,28 +102,52 @@ pub struct PartialAggregate {
impl FloatAggregator {
/// The state folded so far, for a merge with the state of other partitions.
pub fn finish_partial(self) -> PartialAggregate {
self.finish_partial_inner()
}
/// [`Self::finish_partial`] that admits what it builds first: the fold state and the group,
/// point and state vectors, at the exact capacity [`Self::finish_partial_inner`] gives them. A
/// refusal consumes the aggregator, so the caller drops the execution.
pub(crate) fn finish_partial_budgeted(
self,
mut budget: impl FnMut(usize) -> Result<()>,
) -> Result<PartialAggregate> {
let width = self.schema.fields.len();
let groups = self
.groups
.into_iter()
.map(|group| {
let mut points = Vec::new();
for (&block, states) in &group.blocks {
for (offset, point) in states.chunks_exact(width).enumerate() {
if point.iter().any(|state| state.seen) {
points.push((
block * BLOCK_POINTS + offset,
point.iter().map(|state| state.partial()).collect(),
));
}
let mut partial_bytes = self.groups.len().saturating_mul(size_of::<PartialGroup>());
for group in &self.groups {
let points = seen_points(group, width);
partial_bytes = partial_bytes
.saturating_add(points.saturating_mul(size_of::<Point>()))
.saturating_add(
points
.saturating_mul(width)
.saturating_mul(size_of::<Option<AccumulatorState>>()),
);
}
budget(self.state_bytes().saturating_add(partial_bytes))?;
Ok(self.finish_partial_inner())
}
fn finish_partial_inner(self) -> PartialAggregate {
let width = self.schema.fields.len();
let mut groups: Vec<PartialGroup> = Vec::with_capacity(self.groups.len());
for group in self.groups {
let mut points: Vec<Point> = Vec::with_capacity(seen_points(&group, width));
for (&block, states) in &group.blocks {
for (offset, point) in states.chunks_exact(width).enumerate() {
if point.iter().any(|state| state.seen) {
points.push((
block * BLOCK_POINTS + offset,
point.iter().map(|state| state.partial()).collect(),
));
}
}
PartialGroup {
metric: group.metric,
points,
}
})
.collect();
}
groups.push(PartialGroup {
metric: group.metric,
points,
});
}
PartialAggregate {
op: self.op,
groups,
@@ -128,6 +155,67 @@ impl FloatAggregator {
}
}
/// One point of a partial group: its grid position and one state per field.
type Point = (usize, Vec<Option<AccumulatorState>>);
/// The points of `group` that carry a state: the ones a partial of it holds.
fn seen_points(group: &Group, width: usize) -> usize {
group.blocks.values().fold(0usize, |count, states| {
count.saturating_add(
states
.chunks_exact(width)
.filter(|point| point.iter().any(|state| state.seen))
.count(),
)
})
}
/// Bytes one partial group keeps: its labels and its point and state vectors at the capacity they
/// were built with, so spare capacity is paid for rather than skipped.
fn group_bytes(group: &PartialGroup) -> usize {
metric_bytes(&group.metric)
.saturating_add(group.points.capacity().saturating_mul(size_of::<Point>()))
.saturating_add(group.points.iter().fold(0usize, |bytes, (_, states)| {
bytes.saturating_add(
states
.capacity()
.saturating_mul(size_of::<Option<AccumulatorState>>()),
)
}))
}
/// Bytes a group's label key holds: a pair per capacity slot, and the `__name__` entry, whose
/// label and value `label_key` copies, each with its own `Arc` header. The other label strings are
/// the metric's, already counted with it.
fn key_bytes(key: &LabelKey) -> usize {
let name = key
.iter()
.find(|(label, _)| &**label == "__name__")
.map_or(0, |(label, value)| {
label
.len()
.saturating_add(value.len())
.saturating_add(4 * size_of::<usize>())
});
key.capacity()
.saturating_mul(size_of::<(Arc<str>, Arc<str>)>())
.saturating_add(name)
}
/// Coarse bytes the key of `metric` holds while it is built: a pair per slot, the `__name__` label
/// and a copy of the metric name, each with its `Arc` header.
fn key_workspace_bytes(metric: &SeriesLabels) -> usize {
metric
.tags()
.len()
.saturating_add(1)
.saturating_mul(size_of::<(Arc<str>, Arc<str>)>())
.saturating_add("__name__".len())
.saturating_add(metric.name().map_or(0, str::len))
.saturating_add(4 * size_of::<usize>())
.saturating_add(size_of::<LabelKey>())
}
/// Merges the partial states of one aggregation into its result. Groups are identified by their
/// full label set, already grouped by the partitions, and keep the order they first arrive in.
pub struct FloatMerger {
@@ -135,6 +223,7 @@ pub struct FloatMerger {
op: AggregateOp,
group_index: HashMap<LabelKey, usize>,
groups: Vec<Group>,
retained: usize,
}
impl FloatMerger {
@@ -149,12 +238,30 @@ impl FloatMerger {
op,
group_index: HashMap::new(),
groups: Vec::new(),
retained: 0,
})
}
/// Merges the state of one partition. A partial that does not fit this merge, by its
/// aggregation, field count or grid positions, fails and leaves the merge unchanged.
pub fn merge(&mut self, partial: PartialAggregate) -> Result<()> {
self.merge_budgeted(partial, |_| Ok(()))
}
/// Bytes this merge keeps: groups, labels, blocks, B-tree nodes, index table and its keys. Added
/// to by the allocations that change it, never recounted.
pub(crate) fn state_bytes(&self) -> usize {
self.retained
}
/// [`Self::merge`] that admits each allocation before making it: the partial that stays live,
/// the key, and the group, index and block backing about to be reserved. A refusal leaves the
/// merge half applied, so a caller that budgets must drop it rather than merge into it again.
pub(crate) fn merge_budgeted(
&mut self,
partial: PartialAggregate,
mut budget: impl FnMut(usize) -> Result<()>,
) -> Result<()> {
let width = self.schema.fields.len();
let points = self
.schema
@@ -178,27 +285,140 @@ impl FloatMerger {
}
}
}
let input_live = partial.groups.iter().fold(
partial
.groups
.capacity()
.saturating_mul(size_of::<PartialGroup>()),
|bytes, group| bytes.saturating_add(group_bytes(group)),
);
for group in partial.groups {
let index = match self.group_index.entry(label_key(&group.metric)) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
self.groups.push(Group {
metric: group.metric,
blocks: BTreeMap::new(),
});
*entry.insert(self.groups.len() - 1)
let metric = group.metric;
// `label_key` copies the metric name into its own `Arc`, so the copy is admitted
// before it is made. A group that is already merged needs a key too, and its
// admission comes before anything else this call can allocate.
budget(
self.retained
.saturating_add(input_live)
.saturating_add(key_workspace_bytes(&metric)),
)?;
let key = label_key(&metric);
let live = input_live.saturating_add(key_bytes(&key));
let index = match self.group_index.get(&key).copied() {
Some(index) => index,
None => self.open_group(metric, key, live, &mut budget)?,
};
self.merge_points(index, group.points, live, &mut budget)?;
}
Ok(())
}
/// Adds a group and its key, admitting the group vector and index growth first.
fn open_group(
&mut self,
metric: SeriesLabels,
key: LabelKey,
live: usize,
budget: &mut impl FnMut(usize) -> Result<()>,
) -> Result<usize> {
let capacity = self.groups.capacity();
let next_capacity = if self.groups.len() == capacity {
capacity.saturating_mul(2).max(4)
} else {
capacity
};
let map_capacity = self.group_index.capacity();
let next_map_capacity = if self.group_index.len().saturating_add(1) > map_capacity {
next_hash_capacity(map_capacity)
} else {
map_capacity
};
let key_live = key_bytes(&key);
let metric_live = metric_bytes(&metric);
// A realloc that cannot grow in place keeps both buffers alive while it copies, so a
// growing step admits the new buffer beside the old one, which `retained` already holds.
budget(
self.retained
.saturating_add(live)
.saturating_add(key_live)
.saturating_add(metric_live)
.saturating_add(if next_capacity > capacity {
next_capacity.saturating_mul(size_of::<Group>())
} else {
0
})
.saturating_add(if next_map_capacity > map_capacity {
hash_map_backing_bytes(next_map_capacity)
} else {
0
}),
)?;
self.groups.try_reserve(1).map_err(|error| {
DataFusionError::Execution(format!("cannot reserve aggregate groups: {error}"))
})?;
self.groups.push(Group {
metric,
blocks: BTreeMap::new(),
});
let index = self.groups.len() - 1;
self.group_index.insert(key, index);
self.retained = self
.retained
.saturating_add(
self.groups
.capacity()
.saturating_sub(capacity)
.saturating_mul(size_of::<Group>()),
)
.saturating_add(
hash_map_backing_bytes(self.group_index.capacity())
.saturating_sub(hash_map_backing_bytes(map_capacity)),
)
.saturating_add(metric_live)
.saturating_add(key_live);
Ok(index)
}
/// Adds the points of one partial group to group `index`. A missing block is admitted with its
/// states and B-tree node before either is allocated; an existing one only merges state.
fn merge_points(
&mut self,
index: usize,
points: Vec<Point>,
live: usize,
budget: &mut impl FnMut(usize) -> Result<()>,
) -> Result<()> {
let width = self.schema.fields.len();
let block_bytes = BLOCK_POINTS
.saturating_mul(width)
.saturating_mul(size_of::<FloatState>());
let blocks = &mut self.groups[index].blocks;
for (point, states) in points {
let block_index = point / BLOCK_POINTS;
let entries = blocks.len();
let block = match blocks.entry(block_index) {
BTreeEntry::Occupied(entry) => entry.into_mut(),
BTreeEntry::Vacant(entry) => {
budget(
self.retained
.saturating_add(live)
.saturating_add(block_bytes)
.saturating_add(btree_backing_bytes(entries.saturating_add(1))),
)?;
self.retained = self
.retained
.saturating_add(block_bytes)
.saturating_add(btree_backing_bytes(entries.saturating_add(1)))
.saturating_sub(btree_backing_bytes(entries));
entry.insert(
vec![FloatState::default(); BLOCK_POINTS * width].into_boxed_slice(),
)
}
};
let blocks = &mut self.groups[index].blocks;
for (point, states) in group.points {
let block = blocks.entry(point / BLOCK_POINTS).or_insert_with(|| {
vec![FloatState::default(); BLOCK_POINTS * width].into_boxed_slice()
});
let offset = (point % BLOCK_POINTS) * width;
for (slot, state) in block[offset..offset + width].iter_mut().zip(states) {
if let Some(state) = state {
slot.merge(self.op, FloatState::from_partial(state));
}
let offset = (point % BLOCK_POINTS) * width;
for (slot, state) in block[offset..offset + width].iter_mut().zip(states) {
if let Some(state) = state {
slot.merge(self.op, FloatState::from_partial(state));
}
}
}
@@ -209,6 +429,15 @@ impl FloatMerger {
pub fn finish(self) -> Result<Vec<Series>> {
finish_groups(self.schema, self.op, self.groups)
}
/// [`Self::finish`] that admits the result it builds, on top of what the merge still holds. The
/// merge is consumed either way, so a caller that budgets drops it on a refusal.
pub(crate) fn finish_budgeted(
self,
budget: impl FnMut(usize) -> Result<()>,
) -> Result<Vec<Series>> {
finish_groups_budgeted(self.schema, self.op, self.groups, self.retained, budget)
}
}
impl FloatState {
+241
View File
@@ -1446,6 +1446,247 @@ fn merged_and_serial(op: AggregateOp, partitions: &[&[f64]]) -> (f64, f64) {
)
}
/// Runs `run` with a budget that admits everything, returning the largest figure it was asked
/// for: the pool a call needs to succeed.
fn peak_admission(
run: impl FnOnce(
&mut dyn FnMut(usize) -> Result<(), DataFusionError>,
) -> Result<(), DataFusionError>,
) -> (usize, Result<(), DataFusionError>) {
let mut peak = 0usize;
let result = run(&mut |bytes| {
peak = peak.max(bytes);
Ok(())
});
(peak, result)
}
#[test]
fn finish_partial_reserves_one_slot_per_seen_point() {
const SEEN: usize = 65_537;
let schema = schema_with_grid_len(&["value"], SEEN as u64);
let series = input(&schema, metric("m", &[]), 0, &[vec![Some(1.0); SEEN]]);
let mut aggregator =
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
aggregator.update(&series).unwrap();
let expected = aggregator
.state_bytes()
.saturating_add(std::mem::size_of::<PartialGroup>())
.saturating_add(
SEEN.saturating_mul(std::mem::size_of::<(usize, Vec<Option<AccumulatorState>>)>()),
)
.saturating_add(SEEN.saturating_mul(std::mem::size_of::<Option<AccumulatorState>>()));
let mut peak = 0usize;
let partial = aggregator
.finish_partial_budgeted(|bytes| {
peak = peak.max(bytes);
Ok(())
})
.unwrap();
// The vector is reserved once, at the points that carry a state, so pushing does not double it.
assert_eq!(partial.groups[0].points.len(), SEEN);
assert_eq!(partial.groups[0].points.capacity(), SEEN);
assert_eq!(peak, expected);
}
#[test]
fn merge_charges_the_capacity_of_an_input_partial() {
let schema = schema(&["value"]);
let series = input(&schema, metric("m", &[]), 0, &[vec![Some(1.0)]]);
let mut aggregator =
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
aggregator.update(&series).unwrap();
let partial = aggregator.finish_partial();
assert_eq!(partial.groups[0].points.capacity(), 1);
let mut spare = partial.clone();
let point = spare.groups[0].points.pop().unwrap();
let mut points = Vec::with_capacity(1024);
points.push(point);
spare.groups[0].points = points;
let peak = |partial: PartialAggregate| {
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial, budget));
result.unwrap();
peak
};
let slack = 1023 * std::mem::size_of::<(usize, Vec<Option<AccumulatorState>>)>();
assert!(
peak(spare) >= peak(partial).saturating_add(slack),
"spare capacity was not admitted"
);
}
#[test]
fn merge_charges_one_block_per_new_block_not_per_point() {
let names: Vec<String> = (0..64).map(|field| format!("f{field}")).collect();
let labels: Vec<&str> = names.iter().map(String::as_str).collect();
let schema = schema_with_grid_len(&labels, 64);
let fields: Vec<Vec<Option<f64>>> = (0..64).map(|_| vec![Some(1.0); 64]).collect();
let series = input(&schema, metric("m", &[]), 0, &fields);
let mut aggregator =
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
aggregator.update(&series).unwrap();
let partial = aggregator.finish_partial();
assert_eq!(partial.groups[0].points.len(), 64);
let block = BLOCK_POINTS * 64 * std::mem::size_of::<FloatState>();
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial, budget));
result.unwrap();
assert!(
peak < 8 * block,
"admitted {peak} for the one block of {block} the points share"
);
assert_eq!(
values_of(&merger.finish().unwrap(), 0, 64).1,
[Some(1.0); 64]
);
}
#[test]
fn merge_admits_groups_and_blocks_before_it_inserts_them() {
let schema = schema(&["value"]);
let partial = |ids: std::ops::Range<usize>| PartialAggregate {
op: AggregateOp::Sum,
groups: ids
.map(|id| PartialGroup {
metric: metric("m", &[("i", &id.to_string())]),
points: Vec::new(),
})
.collect(),
};
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial(0..64), budget));
result.unwrap();
assert!(peak > 0 && merger.state_bytes() > 0);
// A refused group or block leaves nothing of itself behind; the caller drops the merge.
let retained = merger.state_bytes();
let refused = |_| Err(DataFusionError::Execution("pool exhausted".into()));
assert!(merger.merge_budgeted(partial(100..108), refused).is_err());
assert_eq!(merger.state_bytes(), retained);
let mut invalid = partial(200..201);
invalid.groups[0].points.push((256, Vec::new()));
assert!(merger.merge(invalid).is_err());
assert_eq!(merger.state_bytes(), retained);
assert!(
merger
.finish_budgeted(|_| Err(DataFusionError::Execution("pool exhausted".into())))
.is_err()
);
}
/// Building a label key copies the metric name, so the copy is admitted before it is made: a
/// refusal arrives before the merge touches anything, even for a group and block it already has.
#[test]
fn merge_admits_the_key_before_it_builds_it() {
let schema = schema(&["value"]);
let series = input(&schema, metric("m", &[("job", "a")]), 0, &[vec![Some(1.0)]]);
let partial = || {
let mut aggregator =
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
aggregator.update(&series).unwrap();
aggregator.finish_partial()
};
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
merger.merge(partial()).unwrap();
let retained = merger.state_bytes();
let mut calls = 0;
let result = merger.merge_budgeted(partial(), |_| {
calls += 1;
Err(DataFusionError::Execution("pool exhausted".into()))
});
assert!(result.is_err());
assert!(calls > 0, "the key was built without an admission");
assert_eq!(merger.state_bytes(), retained, "a refused key was kept");
// An existing group and block allocate no block, but the key still is admitted.
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
merger.merge(partial()).unwrap();
let mut calls = 0;
merger
.merge_budgeted(partial(), |_| {
calls += 1;
Ok(())
})
.unwrap();
assert!(
calls > 0,
"an existing group was merged without an admission"
);
}
/// The merge holds two allocations of the metric name: its group's labels, and the copy its label
/// key made. Only one of them is why a longer name costs twice as much.
#[test]
fn a_long_metric_name_is_held_by_the_group_and_by_its_key() {
let schema = schema(&["value"]);
let retained = |name: &str| {
let partial = PartialAggregate {
op: AggregateOp::Sum,
groups: vec![PartialGroup {
metric: metric(name, &[]),
points: Vec::new(),
}],
};
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
merger.merge(partial).unwrap();
merger.state_bytes()
};
const EXTRA: usize = 1000;
let long = format!("m{}", "x".repeat(EXTRA));
let delta = retained(&long) - retained("m");
assert_eq!(
delta,
2 * EXTRA,
"the name is held once by the group and once by the key"
);
}
/// The budgeted partial path keeps the numbers of the public one: one partition, so the merged
/// result is the serial fold bit for bit, for every supported aggregation.
#[test]
fn budgeted_partial_state_merges_to_the_public_numbers() {
let schema = schema(&["value"]);
let series = input(
&schema,
metric("m", &[]),
0,
&[vec![Some(1.0), None, Some(3.0), Some(-2.0)]],
);
for op in [
AggregateOp::Sum,
AggregateOp::Count,
AggregateOp::Avg,
AggregateOp::Min,
AggregateOp::Max,
AggregateOp::Group,
AggregateOp::Stddev,
AggregateOp::Stdvar,
] {
let serial = aggregate_float(
&schema,
std::slice::from_ref(&series),
op,
Grouping::By(&[]),
)
.unwrap();
let expected = values_of(&serial, 0, 128);
let mut aggregator = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
aggregator.update(&series).unwrap();
let partial = aggregator.finish_partial_budgeted(|_| Ok(())).unwrap();
let mut merger = FloatMerger::try_new(&schema, op).unwrap();
merger.merge_budgeted(partial.clone(), |_| Ok(())).unwrap();
let merged = merger.finish_budgeted(|_| Ok(())).unwrap();
assert_eq!(values_of(&merged, 0, 128), expected, "{op:?} budgeted");
let mut plain = FloatMerger::try_new(&schema, op).unwrap();
plain.merge(partial).unwrap();
assert_eq!(
values_of(&plain.finish().unwrap(), 0, 128),
expected,
"{op:?}"
);
}
}
/// Partial states merged in any partition and merge order give the serial result, within the
/// rounding a regrouped fold may change: the same groups, points and fields, the same NaN and
/// infinities. Each partial keeps only the components its aggregation declares, so the layout
+3
View File
@@ -13,6 +13,8 @@
// limitations under the License.
mod absent;
mod aggregate_exchange;
mod aggregate_finalize;
mod empty_metric;
mod fused_series;
mod histogram_fold;
@@ -27,6 +29,7 @@ mod test_util;
mod union_distinct_on;
pub use absent::{Absent, AbsentExec, AbsentStream};
pub use aggregate_finalize::AggregateFinalize;
use common_query::native_histogram::{SUM_FIELD, native_histogram_value_type};
use common_query::prometheus::is_prometheus_stale_nan;
use datafusion::arrow::array::{Array, Float64Array, StructArray};
@@ -0,0 +1,448 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The private Arrow layout of a partition's partial aggregate state, and the fold that writes it.
//! [`decode_state`] reads a batch back into the rows a `FloatMerger` merges. Only that producer and
//! that merge read [`state_schema`]: it is not a wire format, and has no serde or version.
//!
//! TODO(discord9): Replace this temporary state-row bridge with series frames emitted directly by
//! FusedSeries and consumed by native final aggregation, avoiding the extra state-row encoding,
//! decoding and reconstruction. This private layout is not the final intermediate representation.
#[cfg(test)]
mod tests;
use std::mem::size_of;
use std::sync::{Arc, Mutex};
use datafusion::arrow::array::{
Array, ArrayRef, BooleanArray, Float64Array, StringArray, UInt32Array, UInt64Array,
};
use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::error::{DataFusionError, Result as DfResult};
use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
use datatypes::series::samples::SeriesSchema;
use datatypes::series::{Label, SeriesLabels};
use crate::aggregate::{
AccumulatorState, AggregateOp, FloatAggregator, Grouping, PartialAggregate, PartialGroup,
};
use crate::evaluated::EvaluatedChunk;
use crate::grid_series::series_bytes;
use crate::native::plan::{
AggregateKind, AggregateStage, BoundAggregate, Grouping as BoundGrouping,
};
/// Rows per encoded batch; the exchange has no session context to read a batch size from.
const BATCH_ROWS: usize = 4096;
/// One column's `ArrayRef`, its `Field` and its buffers are all well under this.
const COLUMN_OVERHEAD: usize = 256;
/// The value capacity a string column starts with, nulls or not (Arrow's `StringArray::from`).
const STRING_CAPACITY: usize = 1024;
/// One state row: a group's labels, the point and field it is of, and its state. Label columns are
/// nullable, since absent and empty differ; `__name__` has the metric name's column.
pub(crate) fn state_schema(tags: &[String]) -> SchemaRef {
let mut fields = vec![Field::new("metric_name", DataType::Utf8, true)];
let labels = ordinary_tags(tags).count();
fields.extend((0..labels).map(|at| Field::new(format!("tag_{at}"), DataType::Utf8, true)));
fields.extend([
Field::new("point", DataType::UInt64, false),
Field::new("field", DataType::UInt32, false),
]);
for name in ["value", "mean", "compensation", "count"] {
fields.push(Field::new(name, DataType::Float64, false));
}
fields.push(Field::new("incremental_mean", DataType::Boolean, false));
Arc::new(Schema::new(fields))
}
/// The kernel a `Complete` aggregate binds; `quantile` and the other stages are not a fold.
pub(crate) fn aggregate_op(op: &BoundAggregate) -> DfResult<AggregateOp> {
if op.stage != AggregateStage::Complete {
return Err(DataFusionError::NotImplemented(format!(
"the aggregate state exchange folds only `Complete` aggregates, not `{:?}`",
op.stage
)));
}
match op.kind {
AggregateKind::Sum => Ok(AggregateOp::Sum),
AggregateKind::Count => Ok(AggregateOp::Count),
AggregateKind::Avg => Ok(AggregateOp::Avg),
AggregateKind::Min => Ok(AggregateOp::Min),
AggregateKind::Max => Ok(AggregateOp::Max),
AggregateKind::Group => Ok(AggregateOp::Group),
AggregateKind::Stddev => Ok(AggregateOp::Stddev),
AggregateKind::Stdvar => Ok(AggregateOp::Stdvar),
AggregateKind::Quantile { quantile } => Err(DataFusionError::NotImplemented(format!(
"the aggregate state exchange does not carry `quantile {quantile}`"
))),
}
}
/// One partition's fold, and the state it encodes when its input ends.
pub(crate) struct PartialFold {
tags: Arc<[String]>,
pool: Arc<dyn MemoryPool>,
/// What this fold holds beside the kernel's state, so each charge can be added to it.
held: usize,
reservation: MemoryReservation,
/// The plan's charge for exported batches, which live until its queue drains.
export_budget: Arc<Mutex<Option<MemoryReservation>>>,
fold: Option<FloatAggregator>,
}
impl PartialFold {
/// Starts one partition's fold, its `export_budget` registered against `pool` at first export.
pub(crate) fn try_new(
op: BoundAggregate,
schema: Arc<SeriesSchema>,
tags: Arc<[String]>,
export_budget: Arc<Mutex<Option<MemoryReservation>>>,
pool: &Arc<dyn MemoryPool>,
) -> DfResult<Self> {
let kind = aggregate_op(&op)?;
let per_tag = size_of::<String>() + size_of::<Field>() + size_of::<ArrayRef>();
let held = tags.iter().map(|tag| tag.len() + per_tag).sum::<usize>() + 8 * per_tag;
let reservation = MemoryConsumer::new("AggregateExchangeState").register(pool);
reservation.try_resize(held)?;
// `__name__` has the metric name's column; a list without it is reused, not copied.
let tags: Arc<[String]> = if tags.iter().any(|tag| tag == "__name__") {
ordinary_tags(&tags)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.into()
} else {
tags
};
// The grouping names are a scratch copy of the binding's list, which can be longer than the
// tag list, so they are admitted while the kernel is built and given back after.
let scratch = match &op.group {
BoundGrouping::By(names) | BoundGrouping::Without(names) => {
names.len() * size_of::<&str>()
}
};
reservation.try_resize(held.saturating_add(scratch))?;
let fold = {
let names: Vec<&str> = match &op.group {
BoundGrouping::By(names) | BoundGrouping::Without(names) => {
names.iter().map(AsRef::as_ref).collect()
}
};
let grouping = match &op.group {
BoundGrouping::By(_) => Grouping::By(&names),
BoundGrouping::Without(_) => Grouping::Without(&names),
};
FloatAggregator::try_new_budgeted(&schema, kind, grouping, |total| {
reservation.try_resize(held.saturating_add(scratch).saturating_add(total))
})?
};
reservation.try_resize(held)?;
Ok(Self {
tags,
pool: Arc::clone(pool),
held,
reservation,
export_budget,
fold: Some(fold),
})
}
/// Folds one chunk, held while it is folded and dropped after. The kernel validates the chunk
/// against the schema this fold was built with before it charges anything.
pub(crate) fn update(&mut self, chunk: EvaluatedChunk) -> DfResult<()> {
let fold = self.fold.as_mut().ok_or_else(finished)?;
let pending = self.held + series_bytes(&chunk.series);
fold.update_budgeted(&chunk.series, |fold_bytes| {
self.reservation.try_resize(pending + fold_bytes)
})?;
drop(chunk);
self.reservation.try_resize(self.held + fold.state_bytes())
}
/// Encodes the fold's state once the caller has read the input to its end. The batches stay
/// charged to [`Self::export_budget`] after the states are given back, since they outlive them.
pub(crate) fn finish(&mut self) -> DfResult<Vec<RecordBatch>> {
let fold = self.fold.take().ok_or_else(finished)?;
let partial =
fold.finish_partial_budgeted(|total| self.reservation.try_resize(self.held + total))?;
let batches = self.encode(&partial)?;
drop(partial);
self.reservation.try_resize(self.held)?;
Ok(batches)
}
/// Encodes `partial` as one row buffer, admitted in full before it allocates, and hands it over
/// as slices of at most [`BATCH_ROWS`] rows that share it.
fn encode(&self, partial: &PartialAggregate) -> DfResult<Vec<RecordBatch>> {
let mut rows = 0usize;
let mut label_bytes = 0usize;
for group in &partial.groups {
let labels = group.metric.name().map_or(0, str::len).saturating_add(
ordinary_tags(&self.tags)
.filter_map(|tag| group.metric.get(tag).map(|value| tag.len() + value.len()))
.sum::<usize>(),
);
let present: usize = group
.points
.iter()
.map(|p| p.1.iter().flatten().count())
.sum();
rows += present;
label_bytes += labels * present;
}
if rows > 0 {
self.grow_export(export_bytes(rows, label_bytes, self.tags.len()))?;
}
let mut metric_name: Vec<Option<&str>> = Vec::with_capacity(rows);
let mut tags: Vec<Vec<_>> = self.tags.iter().map(|_| Vec::with_capacity(rows)).collect();
let (mut point, mut field) = (Vec::with_capacity(rows), Vec::with_capacity(rows));
let mut components: [Vec<f64>; 4] = std::array::from_fn(|_| Vec::with_capacity(rows));
let mut incremental_mean: Vec<bool> = Vec::with_capacity(rows);
for group in &partial.groups {
for (at, states) in &group.points {
for (index, state) in states.iter().enumerate() {
let Some(state) = state else {
continue;
};
metric_name.push(group.metric.name());
for (column, tag) in tags.iter_mut().zip(self.tags.iter()) {
column.push(group.metric.get(tag));
}
point.push(*at as u64);
field.push(index as u32);
components[0].push(state.value);
components[1].push(state.mean);
components[2].push(state.compensation);
components[3].push(state.count);
incremental_mean.push(state.incremental_mean);
}
}
}
let mut columns: Vec<ArrayRef> = Vec::with_capacity(8 + tags.len());
columns.push(Arc::new(StringArray::from(metric_name)));
for values in tags {
columns.push(Arc::new(StringArray::from(values)));
}
columns.push(Arc::new(UInt64Array::from(point)));
columns.push(Arc::new(UInt32Array::from(field)));
for values in components {
columns.push(Arc::new(Float64Array::from(values)));
}
columns.push(Arc::new(BooleanArray::from(incremental_mean)));
let batch = RecordBatch::try_new(state_schema(&self.tags), columns)?;
Ok((0..rows)
.step_by(BATCH_ROWS)
.map(|offset| batch.slice(offset, BATCH_ROWS.min(rows - offset)))
.collect())
}
/// Admits `bytes` to the plan's export reservation, registered against this pool at first use.
fn grow_export(&self, bytes: usize) -> DfResult<()> {
let mut budget = self.export_budget.lock().unwrap_or_else(|e| e.into_inner());
let consumer = MemoryConsumer::new("AggregateExchangeExport");
budget
.get_or_insert_with(|| consumer.register(&self.pool))
.try_grow(bytes)
}
}
/// Reads one state batch back into the rows a `FloatMerger` merges.
///
/// Rows of one group and point arrive together, so consecutive rows carrying the same labels and
/// point fill one state vector of the schema's width, and a change of either opens the next one.
/// Rows of one point split across batches stay separate groups, which the merge folds together.
pub(crate) fn decode_state(
batch: &RecordBatch,
schema: &Arc<SeriesSchema>,
op: AggregateOp,
tags: &[String],
mut budget: impl FnMut(usize) -> DfResult<()>,
) -> DfResult<PartialAggregate> {
// The expected layout builds a name and a field per column, so it is admitted before it is
// built, together with the column lookups below.
let mut total = (tags.len() + 9)
.saturating_mul(size_of::<&str>() + size_of::<String>() + size_of::<Field>());
budget(total)?;
let layout = state_schema(tags);
let batch_schema = batch.schema_ref();
if batch_schema.as_ref() != layout.as_ref() {
return Err(DataFusionError::Execution(format!(
"not the layout {layout:?}"
)));
}
let grid = schema.eval_grid.as_ref().ok_or_else(|| {
DataFusionError::Execution("aggregate state is indexed on an evaluated grid".into())
})?;
let width = schema.fields.len();
// The name list and the label column lookups are workspace, sized exactly and charged before
// either allocates.
total = total.saturating_add(tags.len() * (size_of::<&str>() + size_of::<&StringArray>()));
budget(total)?;
let mut names: Vec<&str> = Vec::with_capacity(tags.len());
names.extend(ordinary_tags(tags));
let metric_name: &StringArray = column(batch, "metric_name")?;
let mut tag_columns: Vec<&StringArray> = Vec::with_capacity(names.len());
for at in 0..names.len() {
tag_columns.push(column(batch, &format!("tag_{at}"))?);
}
let point: &UInt64Array = column(batch, "point")?;
let field: &UInt32Array = column(batch, "field")?;
let value: &Float64Array = column(batch, "value")?;
let mean: &Float64Array = column(batch, "mean")?;
let compensation: &Float64Array = column(batch, "compensation")?;
let count: &Float64Array = column(batch, "count")?;
let incremental_mean: &BooleanArray = column(batch, "incremental_mean")?;
// A null in a state column is not a zero: that state was never folded. Only the label columns
// ahead of these are nullable.
for at in names.len() + 1..batch.num_columns() {
let nulls = batch.column(at).null_count();
let name = batch_schema.field(at).name();
if nulls > 0 {
return Err(DataFusionError::Execution(format!(
"the aggregate state column `{name}` holds {nulls} nulls, a state being a value"
)));
}
}
let mut groups: Vec<PartialGroup> = Vec::new();
for row in 0..batch.num_rows() {
let at = usize::try_from(point.value(row)).unwrap_or(usize::MAX);
let field = field.value(row) as usize;
if at >= grid.spec().len as usize || field >= width {
return Err(DataFusionError::Execution(format!(
"aggregate state row {row} is of point {at} of the grid's {} or of field {field} \
of the aggregate's {width}",
grid.spec().len
)));
}
// A row repeating the labels of the row before it, on the same point, is that point's next
// field; a change of either opens a group.
let differs = |column: &StringArray| {
column.is_null(row - 1) != column.is_null(row)
|| (!column.is_null(row) && column.value(row - 1) != column.value(row))
};
let opens = row == 0
|| groups.last().is_none_or(|group| group.points[0].0 != at)
|| differs(metric_name)
|| tag_columns.iter().any(|column| differs(column));
if opens {
// A push outgrowing the group vector doubles it, so the block it is about to allocate
// is admitted here; the point's tuple and state vector and the label scratch follow
// before either allocates, then what the labels carry once they are read.
let growth = if groups.len() == groups.capacity() {
groups.capacity().max(1) * 2 * size_of::<PartialGroup>()
} else {
0
};
total = total.saturating_add(
growth
+ size_of::<(usize, Vec<Option<AccumulatorState>>)>()
+ width * size_of::<Option<AccumulatorState>>()
+ (names.len() + 1) * size_of::<(&str, &str)>(),
);
budget(total)?;
let name = (!metric_name.is_null(row)).then(|| metric_name.value(row));
let mut carried: Vec<(&str, &str)> = Vec::with_capacity(names.len());
for (column, label) in tag_columns.iter().zip(&names) {
if !column.is_null(row) {
carried.push((*label, column.value(row)));
}
}
// The label vector, the `Arc<str>` header each name and value points at, and the bytes
// they hold. One extra pair is the metric name.
total = total.saturating_add(
(names.len() + 1) * (size_of::<Label>() + size_of::<usize>())
+ name.map_or(0, str::len)
+ carried
.iter()
.map(|(label, value)| label.len() + value.len())
.sum::<usize>(),
);
budget(total)?;
let mut labels: Vec<Label> = Vec::with_capacity(carried.len());
for (label, value) in carried {
labels.push(Label {
name: Arc::from(label),
value: Arc::from(value),
});
}
let metric = SeriesLabels::try_new(name.map(Arc::from), labels).map_err(|error| {
DataFusionError::Execution(format!(
"aggregate state row {row} does not carry a label set: {error}"
))
})?;
groups.push(PartialGroup {
metric,
points: vec![(at, vec![None; width])],
});
}
let group = groups.last_mut().ok_or_else(|| {
DataFusionError::Execution(format!("aggregate state row {row} opened no group"))
})?;
let states = &mut group.points[0].1;
if states[field].is_some() {
return Err(DataFusionError::Execution(format!(
"aggregate state row {row} repeats field {field} of its group's point"
)));
}
states[field] = Some(AccumulatorState {
value: value.value(row),
mean: mean.value(row),
compensation: compensation.value(row),
count: count.value(row),
incremental_mean: incremental_mean.value(row),
});
}
Ok(PartialAggregate { op, groups })
}
/// The caller's tag names in column order, without the metric name, which has its own column.
fn ordinary_tags(tags: &[String]) -> impl Iterator<Item = &str> + '_ {
tags.iter()
.filter(|tag| tag.as_str() != "__name__")
.map(String::as_str)
}
/// The error for a fold that has already been finished.
fn finished() -> DataFusionError {
DataFusionError::Execution("the partial aggregate already finished its fold".into())
}
/// An upper bound on one export: the scratch row vectors, the Arrow arrays they are frozen into --
/// which live beside them while the strings are copied -- and the slices the output holds.
///
/// A string column starts at [`STRING_CAPACITY`] value bytes even when every row is null, and the
/// builder copies what it appended before handing its buffer over, so one minimum capacity is
/// admitted per column beside the label payload twice over. Coarse on purpose: an overestimate.
fn export_bytes(rows: usize, label_bytes: usize, tags: usize) -> usize {
let strings = tags.saturating_add(1);
let row = size_of::<u64>() + size_of::<u32>() + 4 * size_of::<f64>() + size_of::<bool>();
rows * row
+ strings * rows * size_of::<Option<&str>>()
+ strings * (rows + 1) * size_of::<i32>()
+ strings * (rows / 8 + 1)
+ strings * STRING_CAPACITY
+ 2 * label_bytes
+ (strings + 8) * COLUMN_OVERHEAD
+ rows.div_ceil(BATCH_ROWS) * size_of::<RecordBatch>()
}
/// Reads the column `name` as `A`, which the layout check has already made certain.
fn column<'a, A: 'static>(batch: &'a RecordBatch, name: &str) -> DfResult<&'a A> {
let found = batch
.column_by_name(name)
.and_then(|c| c.as_any().downcast_ref::<A>());
found.ok_or_else(|| DataFusionError::Execution(format!("the column `{name}` has another type")))
}
@@ -0,0 +1,887 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use datafusion::execution::memory_pool::{GreedyMemoryPool, UnboundedMemoryPool};
use datatypes::series::samples::{FieldSpec, SampleRef, Samples, Series, SeriesFields};
use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
use datatypes::series::{Label, SeriesLabels};
use super::*;
use crate::aggregate::FloatMerger;
/// One field's samples, as a grid position and the value at it.
type FieldPoints = Vec<(usize, f64)>;
fn series_schema(fields: &[&str], points: u64) -> Arc<SeriesSchema> {
Arc::new(SeriesSchema {
fields: fields
.iter()
.map(|name| FieldSpec {
name: (*name).into(),
})
.collect(),
eval_grid: Some(Arc::new(
EvalGrid::try_new(GridSpec::try_new(-1000, 250, points).unwrap()).unwrap(),
)),
})
}
fn metric(name: Option<&str>, labels: &[(&str, &str)]) -> SeriesLabels {
SeriesLabels::try_new(
name.map(Arc::from),
labels
.iter()
.map(|(name, value)| Label {
name: (*name).into(),
value: (*value).into(),
})
.collect(),
)
.unwrap()
}
/// One closed chunk of `metric` over `fields`, from grid position zero.
fn chunk(
schema: &Arc<SeriesSchema>,
metric: SeriesLabels,
fields: &[Vec<Option<f64>>],
) -> EvaluatedChunk {
let rows = fields[0].len();
let fields = fields
.iter()
.map(|values| Samples::from_float(Float64Array::from(values.clone())))
.collect();
let series = Series::try_new(
schema,
metric,
TimeAxis::Grid(GridRange::try_new(schema.eval_grid.clone().unwrap(), 0, rows).unwrap()),
SeriesFields::try_from_vec(fields).unwrap(),
)
.unwrap();
EvaluatedChunk::try_new(series, true).unwrap()
}
fn bind(kind: AggregateKind, group: &[&str]) -> BoundAggregate {
BoundAggregate {
kind,
group: BoundGrouping::By(group.iter().map(|label| Arc::from(*label)).collect()),
stage: AggregateStage::Complete,
}
}
fn tags(names: &[&str]) -> Arc<[String]> {
names
.iter()
.map(|name| name.to_string())
.collect::<Vec<_>>()
.into()
}
fn unbounded() -> Arc<dyn MemoryPool> {
Arc::new(UnboundedMemoryPool::default())
}
fn fold(
op: &BoundAggregate,
schema: &Arc<SeriesSchema>,
tags: &Arc<[String]>,
pool: &Arc<dyn MemoryPool>,
) -> DfResult<PartialFold> {
PartialFold::try_new(
op.clone(),
Arc::clone(schema),
Arc::clone(tags),
Arc::new(Mutex::new(None)),
pool,
)
}
/// The fold's own state, from the kernel's serial fold of the same input.
fn expected(
op: AggregateOp,
by: &[&str],
schema: &Arc<SeriesSchema>,
chunks: &[EvaluatedChunk],
) -> PartialAggregate {
let mut aggregator = FloatAggregator::try_new(schema, op, Grouping::By(by)).unwrap();
for chunk in chunks {
aggregator.update(&chunk.series).unwrap();
}
aggregator.finish_partial()
}
/// Every state of `partial` as one row, sorted so that two sides compare whatever their order.
fn rows(partial: &PartialAggregate) -> Vec<(String, usize, usize, AccumulatorState)> {
let mut rows: Vec<_> = partial
.groups
.iter()
.flat_map(|group| {
group.points.iter().flat_map(|(at, states)| {
states.iter().enumerate().filter_map(|(field, state)| {
state.map(|state| (format!("{:?}", group.metric), *at, field, state))
})
})
})
.collect();
rows.sort_unstable_by(|a, b| (&a.0, a.1, a.2).cmp(&(&b.0, b.1, b.2)));
rows
}
fn decode(
batch: &RecordBatch,
schema: &Arc<SeriesSchema>,
op: AggregateOp,
tags: &[String],
) -> DfResult<PartialAggregate> {
decode_state(batch, schema, op, tags, |_| Ok(()))
}
/// Each decoded batch's rows, for a roundtrip that spans several of them.
fn decoded_rows(
batches: &[RecordBatch],
schema: &Arc<SeriesSchema>,
op: AggregateOp,
tags: &[String],
) -> Vec<(String, usize, usize, AccumulatorState)> {
batches
.iter()
.flat_map(|batch| rows(&decode(batch, schema, op, tags).unwrap()))
.collect()
}
/// What the merge of `partials` answers, as its values per field per series.
fn merged(
op: AggregateOp,
schema: &Arc<SeriesSchema>,
partials: Vec<PartialAggregate>,
) -> Vec<(String, Vec<FieldPoints>)> {
let mut merger = FloatMerger::try_new(schema, op).unwrap();
for partial in partials {
merger.merge(partial).unwrap();
}
merger
.finish()
.unwrap()
.into_iter()
.map(|series| {
let positions: Vec<usize> = series.time.positions().map(|(at, _)| at).collect();
let fields = series
.fields
.iter()
.map(|field| {
field
.iter()
.zip(&positions)
.filter_map(|(sample, at)| match sample {
SampleRef::Float(value) => Some((*at, value)),
_ => None,
})
.collect()
})
.collect();
(format!("{:?}", series.metric), fields)
})
.collect()
}
fn state(value: f64) -> AccumulatorState {
AccumulatorState {
value,
mean: 0.0,
compensation: 0.0,
count: 1.0,
incremental_mean: false,
}
}
/// One hand-written state row, for the batches a fold would not produce.
#[derive(Clone, Copy)]
struct Row {
name: Option<&'static str>,
/// One per ordinary tag, `None` for an absent label.
labels: &'static [Option<&'static str>],
point: u64,
field: u32,
/// Every state column is non-nullable, so a row of [`state_batch`] carries one: writing a null
/// here would be a batch Arrow refuses, which the null-state test builds itself.
state: Option<AccumulatorState>,
}
fn state_batch(tags: &[String], rows: &[Row]) -> RecordBatch {
let mut columns: Vec<ArrayRef> = vec![Arc::new(StringArray::from(
rows.iter().map(|row| row.name).collect::<Vec<_>>(),
))];
for (position, _) in ordinary_tags(tags).enumerate() {
columns.push(Arc::new(StringArray::from(
rows.iter()
.map(|row| row.labels[position])
.collect::<Vec<_>>(),
)));
}
columns.push(Arc::new(UInt64Array::from(
rows.iter().map(|row| row.point).collect::<Vec<_>>(),
)));
columns.push(Arc::new(UInt32Array::from(
rows.iter().map(|row| row.field).collect::<Vec<_>>(),
)));
let components: [Vec<Option<f64>>; 4] = std::array::from_fn(|index| {
rows.iter()
.map(|row| {
row.state
.map(|state| [state.value, state.mean, state.compensation, state.count][index])
})
.collect()
});
columns.extend(
components
.into_iter()
.map(|values| Arc::new(Float64Array::from(values)) as ArrayRef),
);
columns.push(Arc::new(BooleanArray::from(
rows.iter()
.map(|row| row.state.map(|state| state.incremental_mean))
.collect::<Vec<_>>(),
)));
RecordBatch::try_new(state_schema(tags), columns).unwrap()
}
#[test]
fn state_schema_is_the_private_layout() {
let schema = state_schema(&["job".to_string(), "__name__".into(), "instance".into()]);
let fields: Vec<(&str, DataType, bool)> = schema
.fields()
.iter()
.map(|field| {
(
field.name().as_str(),
field.data_type().clone(),
field.is_nullable(),
)
})
.collect();
assert_eq!(
fields,
vec![
("metric_name", DataType::Utf8, true),
("tag_0", DataType::Utf8, true),
("tag_1", DataType::Utf8, true),
("point", DataType::UInt64, false),
("field", DataType::UInt32, false),
("value", DataType::Float64, false),
("mean", DataType::Float64, false),
("compensation", DataType::Float64, false),
("count", DataType::Float64, false),
("incremental_mean", DataType::Boolean, false),
]
);
}
#[test]
fn aggregate_op_folds_complete_kinds_only() {
for (kind, op) in [
(AggregateKind::Sum, AggregateOp::Sum),
(AggregateKind::Count, AggregateOp::Count),
(AggregateKind::Avg, AggregateOp::Avg),
(AggregateKind::Min, AggregateOp::Min),
(AggregateKind::Max, AggregateOp::Max),
(AggregateKind::Group, AggregateOp::Group),
(AggregateKind::Stddev, AggregateOp::Stddev),
(AggregateKind::Stdvar, AggregateOp::Stdvar),
] {
assert_eq!(aggregate_op(&bind(kind, &["job"])).unwrap(), op);
}
for stage in [AggregateStage::Partial, AggregateStage::Final] {
let op = BoundAggregate {
kind: AggregateKind::Sum,
group: bind(AggregateKind::Sum, &["job"]).group,
stage,
};
assert!(matches!(
aggregate_op(&op),
Err(DataFusionError::NotImplemented(_))
));
}
let quantile = bind(AggregateKind::Quantile { quantile: 0.5 }, &["job"]);
assert!(matches!(
aggregate_op(&quantile),
Err(DataFusionError::NotImplemented(_))
));
}
#[test]
fn roundtrip_carries_every_component() {
let schema = series_schema(&["a", "b"], 4);
let tags = tags(&["job", "instance"]);
for (kind, op) in [
(AggregateKind::Sum, AggregateOp::Sum),
(AggregateKind::Count, AggregateOp::Count),
(AggregateKind::Avg, AggregateOp::Avg),
(AggregateKind::Stddev, AggregateOp::Stddev),
(AggregateKind::Stdvar, AggregateOp::Stdvar),
] {
let chunks = vec![
chunk(
&schema,
metric(None, &[("job", "x"), ("instance", "one")]),
&[
vec![Some(1.0), None, Some(3.0), Some(4.0)],
vec![Some(10.0), Some(20.0), None, None],
],
),
chunk(
&schema,
metric(None, &[("job", "x"), ("instance", "two")]),
&[
vec![Some(5.0), None, None, Some(7.0)],
vec![None, None, Some(30.0), Some(40.0)],
],
),
];
let pool = unbounded();
let mut fold = fold(&bind(kind, &["job"]), &schema, &tags, &pool).unwrap();
for chunk in &chunks {
fold.update(chunk.clone()).unwrap();
}
let batches = fold.finish().unwrap();
assert_eq!(
decoded_rows(&batches, &schema, op, &tags),
rows(&expected(op, &["job"], &schema, &chunks))
);
}
}
#[test]
fn roundtrip_keeps_the_name_and_absent_labels() {
let schema = series_schema(&["a"], 2);
// `__name__` is in the tag list and must be filtered out; `instance` never reaches a group.
let tags = tags(&["instance", "__name__", "job"]);
let chunks = [chunk(
&schema,
metric(Some("up"), &[("job", "x"), ("instance", "one")]),
&[vec![Some(1.0), Some(2.0)]],
)];
let pool = unbounded();
let mut fold = fold(
&bind(AggregateKind::Sum, &["job", "__name__"]),
&schema,
&tags,
&pool,
)
.unwrap();
fold.update(chunks[0].clone()).unwrap();
let batches = fold.finish().unwrap();
assert_eq!(batches[0].num_columns(), 10);
let decoded = decode(&batches[0], &schema, AggregateOp::Sum, &tags).unwrap();
// One group per point, so both points are checked over every group rather than one of them.
let mut points: Vec<usize> = decoded
.groups
.iter()
.flat_map(|group| group.points.iter().map(|(at, _)| *at))
.collect();
points.sort_unstable();
assert_eq!(points, vec![0, 1]);
assert!(decoded.groups.iter().all(|group| {
group.metric.name() == Some("up")
&& group.metric.get("job") == Some("x")
&& group.metric.get("instance").is_none()
}));
}
#[test]
fn decoded_rows_keep_an_empty_label_beside_an_absent_one() {
let schema = series_schema(&["a"], 2);
let tags = tags(&["job", "instance"]);
let batch = state_batch(
&tags,
&[Row {
name: None,
labels: &[Some(""), None],
point: 1,
field: 0,
state: Some(state(4.0)),
}],
);
let decoded = decode(&batch, &schema, AggregateOp::Sum, &tags).unwrap();
let group = &decoded.groups[0];
assert_eq!(group.metric.name(), None);
assert_eq!(group.metric.get("job"), Some(""));
assert_eq!(group.metric.get("instance"), None);
assert_eq!(group.points, vec![(1, vec![Some(state(4.0))])]);
}
#[test]
fn group_state_roundtrips_where_a_value_exists() {
let schema = series_schema(&["a"], 3);
let tags = tags(&["job"]);
let chunks = vec![
chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![Some(1.0), None, Some(1.0)]],
),
chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![None, Some(1.0), Some(1.0)]],
),
];
let pool = unbounded();
let mut fold = fold(&bind(AggregateKind::Group, &["job"]), &schema, &tags, &pool).unwrap();
for chunk in &chunks {
fold.update(chunk.clone()).unwrap();
}
let batches = fold.finish().unwrap();
let decoded = decode(&batches[0], &schema, AggregateOp::Group, &tags).unwrap();
assert_eq!(
rows(&decoded),
rows(&expected(AggregateOp::Group, &["job"], &schema, &chunks))
);
assert_eq!(rows(&decoded).len(), 3);
}
#[test]
fn a_sparse_field_leaves_the_other_field_unset() {
let schema = series_schema(&["a", "b"], 3);
let tags = tags(&["job"]);
let chunks = [chunk(
&schema,
metric(None, &[("job", "x")]),
&[
vec![Some(1.0), None, Some(2.0)],
vec![None, Some(5.0), None],
],
)];
let pool = unbounded();
let mut fold = fold(&bind(AggregateKind::Sum, &["job"]), &schema, &tags, &pool).unwrap();
fold.update(chunks[0].clone()).unwrap();
let batches = fold.finish().unwrap();
let decoded = decode(&batches[0], &schema, AggregateOp::Sum, &tags).unwrap();
let points: Vec<(usize, usize)> = rows(&decoded)
.into_iter()
.map(|(_, at, field, _)| (at, field))
.collect();
assert_eq!(points, vec![(0, 0), (1, 1), (2, 0)]);
}
#[test]
fn a_point_is_assembled_from_its_fields() {
let names: Vec<String> = (0..64).map(|index| format!("f{index}")).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
let schema = series_schema(&names, 64);
let tags = tags(&["job"]);
let values: Vec<Option<f64>> = (0..64).map(|at| Some(at as f64)).collect();
let chunks = vec![chunk(
&schema,
metric(None, &[("job", "x")]),
&vec![values; 64],
)];
let pool = unbounded();
let mut fold = fold(&bind(AggregateKind::Sum, &["job"]), &schema, &tags, &pool).unwrap();
fold.update(chunks[0].clone()).unwrap();
let batches = fold.finish().unwrap();
let decoded = decode(&batches[0], &schema, AggregateOp::Sum, &tags).unwrap();
// One group per point, each holding one field-wide state vector, rather than one per row.
assert_eq!(decoded.groups.len(), 64);
assert!(
decoded
.groups
.iter()
.all(|group| group.points.len() == 1 && group.points[0].1.len() == 64)
);
assert_eq!(rows(&decoded).len(), 64 * 64);
assert_eq!(
rows(&decoded),
rows(&expected(AggregateOp::Sum, &["job"], &schema, &chunks))
);
}
#[test]
fn one_group_spans_several_batches() {
let points = BATCH_ROWS as u64 / 2 + 1;
let schema = series_schema(&["a", "b"], points);
let tags = tags(&["job"]);
let values: Vec<Option<f64>> = (0..points).map(|at| Some(at as f64)).collect();
let chunks = vec![chunk(
&schema,
metric(None, &[("job", "x")]),
&[values.clone(), values],
)];
let pool = unbounded();
let mut fold = fold(&bind(AggregateKind::Sum, &["job"]), &schema, &tags, &pool).unwrap();
fold.update(chunks[0].clone()).unwrap();
let batches = fold.finish().unwrap();
assert_eq!(batches.len(), 2);
assert_eq!(batches[0].num_rows(), BATCH_ROWS);
assert_eq!(batches[1].num_rows(), 2);
assert_eq!(
decoded_rows(&batches, &schema, AggregateOp::Sum, &tags),
rows(&expected(AggregateOp::Sum, &["job"], &schema, &chunks))
);
}
#[test]
fn a_point_split_across_batches_merges_back_together() {
let schema = series_schema(&["a", "b"], 1);
let tags = tags(&["job"]);
let chunks = [chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![Some(3.0)], vec![Some(4.0)]],
)];
let pool = unbounded();
let mut fold = fold(&bind(AggregateKind::Sum, &["job"]), &schema, &tags, &pool).unwrap();
fold.update(chunks[0].clone()).unwrap();
let batch = fold.finish().unwrap().remove(0);
assert_eq!(batch.num_rows(), 2);
let partials = [batch.slice(0, 1), batch.slice(1, 1)]
.iter()
.map(|batch| decode(batch, &schema, AggregateOp::Sum, &tags).unwrap())
.collect::<Vec<_>>();
assert_eq!(partials[0].groups.len(), 1);
assert_eq!(partials[1].groups.len(), 1);
// One group at one point again, carrying both fields the split batches held apart.
let merged = merged(AggregateOp::Sum, &schema, partials);
assert_eq!(merged.len(), 1);
assert_eq!(merged[0].1, vec![vec![(0, 3.0)], vec![(0, 4.0)]]);
}
#[test]
fn finish_charges_the_export_and_releases_the_fold() {
let schema = series_schema(&["a"], 2);
let tags = tags(&["job"]);
let budget = Arc::new(Mutex::new(None));
let pool = unbounded();
let mut fold = PartialFold::try_new(
bind(AggregateKind::Sum, &["job"]),
Arc::clone(&schema),
Arc::clone(&tags),
Arc::clone(&budget),
&pool,
)
.unwrap();
fold.update(chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![Some(1.0), Some(2.0)]],
))
.unwrap();
assert!(budget.lock().unwrap().is_none());
assert_eq!(fold.finish().unwrap().len(), 1);
// The states are given back; what this fold still holds is its own tags and schema.
assert_eq!(fold.reservation.size(), fold.held);
assert!(budget.lock().unwrap().as_ref().unwrap().size() > 0);
// A finished partition folds and finishes nothing more.
assert!(matches!(fold.finish(), Err(DataFusionError::Execution(_))));
assert!(matches!(
fold.update(chunk(&schema, metric(None, &[]), &[vec![Some(1.0)]])),
Err(DataFusionError::Execution(_))
));
}
#[test]
fn absent_labels_still_need_export_budget() {
let names: Vec<String> = (0..8).map(|index| format!("t{index}")).collect();
let schema = series_schema(&["a"], 2);
let tags: Arc<[String]> = names.into();
let tiny = Arc::new(GreedyMemoryPool::new(16)) as Arc<dyn MemoryPool>;
let claimed = Arc::new(Mutex::new(Some(
MemoryConsumer::new("test.export").register(&tiny),
)));
let mut fold = PartialFold::try_new(
bind(AggregateKind::Sum, &["job"]),
Arc::clone(&schema),
Arc::clone(&tags),
claimed,
&unbounded(),
)
.unwrap();
// No label is present, so only the rows themselves are charged -- and refused, by the pool
// itself: the refusal is a resource error, not one of this module's own.
fold.update(chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![Some(1.0), Some(2.0)]],
))
.unwrap();
let error = fold
.finish()
.expect_err("16 bytes cannot hold the rows the fold exports");
assert!(
matches!(
error,
DataFusionError::ResourcesExhausted(ref reason)
if reason.contains("Failed to allocate additional")
),
"refused with another error: {error}"
);
}
#[test]
fn a_tiny_pool_refuses_the_fold() {
let schema = series_schema(&["a"], 2);
let tags = tags(&["job"]);
let pool = Arc::new(GreedyMemoryPool::new(1)) as Arc<dyn MemoryPool>;
let result =
fold(&bind(AggregateKind::Sum, &["job"]), &schema, &tags, &pool).and_then(|mut fold| {
fold.update(chunk(
&schema,
metric(None, &[("job", "x")]),
&[vec![Some(1.0), Some(2.0)]],
))
});
assert!(result.is_err());
}
#[test]
fn decode_refuses_a_foreign_layout() {
let schema = series_schema(&["a"], 2);
let tags = tags(&["job"]);
let batch = state_batch(
&tags,
&[Row {
name: None,
labels: &[Some("x")],
point: 0,
field: 0,
state: Some(state(1.0)),
}],
);
for (from, to) in [("point", "grid_point"), ("value", "sum")] {
let fields: Vec<Arc<Field>> = batch
.schema()
.fields()
.iter()
.map(|field| {
if field.name() == from {
Arc::new(Field::new(
to,
field.data_type().clone(),
field.is_nullable(),
))
} else {
Arc::clone(field)
}
})
.collect();
let foreign =
RecordBatch::try_new(Arc::new(Schema::new(fields)), batch.columns().to_vec()).unwrap();
assert!(matches!(
decode(&foreign, &schema, AggregateOp::Sum, &tags),
Err(DataFusionError::Execution(_))
));
}
let mut columns = batch.columns().to_vec();
columns.push(Arc::new(UInt64Array::from(vec![0])));
let mut fields = batch.schema().fields().to_vec();
fields.push(Arc::new(Field::new("extra", DataType::UInt64, false)));
let extra = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
assert!(matches!(
decode(&extra, &schema, AggregateOp::Sum, &tags),
Err(DataFusionError::Execution(_))
));
}
/// A null state cannot reach the decoder: the layout's state columns are non-nullable, so Arrow
/// refuses such a batch, and a valid batch against a grid-less schema is what the decoder refuses.
#[test]
fn a_null_state_is_rejected_at_the_batch_boundary_and_ungridded_decode_is_refused() {
let tags = tags(&["job"]);
let batch = state_batch(
&tags,
&[Row {
name: None,
labels: &[Some("x")],
point: 0,
field: 0,
state: Some(state(1.0)),
}],
);
// The decoder's own null check is unreachable through a batch: a non-nullable state column
// holding nulls cannot be built at all, so the boundary refuses it before decode is called.
let mut columns = batch.columns().to_vec();
let value = batch
.schema()
.index_of("value")
.expect("the layout has a value column");
columns[value] = Arc::new(Float64Array::from(vec![None]));
let error = RecordBatch::try_new(Arc::clone(batch.schema_ref()), columns)
.expect_err("a null in a non-nullable state column is not a batch");
assert!(
error.to_string().contains("non-nullable"),
"refused for another reason: {error}"
);
let plain = Arc::new(SeriesSchema {
fields: vec![FieldSpec { name: "a".into() }].into(),
eval_grid: None,
});
let error = decode(&batch, &plain, AggregateOp::Sum, &tags)
.expect_err("state is indexed on a grid the schema does not have");
assert!(
error.to_string().contains("grid"),
"refused for another reason: {error}"
);
}
#[test]
fn decode_refuses_a_point_a_field_or_a_field_twice() {
let schema = series_schema(&["a"], 2);
let tags = tags(&["job"]);
let row = |point, field| Row {
name: None,
labels: &[Some("x")],
point,
field,
state: Some(state(1.0)),
};
for row in [row(2, 0), row(0, 1)] {
assert!(matches!(
decode(
&state_batch(&tags, &[row]),
&schema,
AggregateOp::Sum,
&tags
),
Err(DataFusionError::Execution(_))
));
}
// Two rows of one point naming one field: the producer contract's one defect.
let repeated = decode(
&state_batch(&tags, &[row(0, 0), row(0, 0)]),
&schema,
AggregateOp::Sum,
&tags,
);
assert!(
matches!(repeated, Err(DataFusionError::Execution(ref reason)) if reason.contains("repeats field"))
);
}
/// Decode admits a figure that covers every container its answer keeps.
///
/// The decoded answer retains the group vector, each group's point vector and state vectors, and the
/// labels of each group. What was admitted has to reach that; a budget one byte below it must refuse
/// rather than answer with containers nothing paid for.
#[test]
fn decode_admits_the_groups_it_keeps() {
let schema = series_schema(&["a", "b"], 2);
let tags = tags(&["job", "instance"]);
let batch = state_batch(
&tags,
&[
Row {
name: Some("up"),
labels: &[Some("x"), Some("one")],
point: 0,
field: 0,
state: Some(state(1.0)),
},
Row {
name: Some("up"),
labels: &[Some("x"), Some("one")],
point: 1,
field: 0,
state: Some(state(2.0)),
},
Row {
name: None,
labels: &[None, Some("two")],
point: 0,
field: 1,
state: Some(state(3.0)),
},
],
);
let mut totals = Vec::new();
let decoded = decode_state(&batch, &schema, AggregateOp::Sum, &tags, |total| {
totals.push(total);
Ok(())
})
.unwrap();
// Every container the answer keeps, at the capacity it actually has.
let retained = decoded.groups.capacity() * size_of::<PartialGroup>()
+ decoded
.groups
.iter()
.map(|group| {
group.points.capacity() * size_of::<(usize, Vec<Option<AccumulatorState>>)>()
+ group
.points
.iter()
.map(|(_, states)| {
states.capacity() * size_of::<Option<AccumulatorState>>()
})
.sum::<usize>()
+ group.metric.name().map_or(0, str::len)
+ group
.metric
.tags()
.iter()
.map(|tag| {
size_of::<Label>()
+ 2 * size_of::<usize>()
+ tag.name.len()
+ tag.value.len()
})
.sum::<usize>()
})
.sum::<usize>();
let admitted = *totals.iter().max().expect("decode charged its workspace");
assert!(
admitted >= retained,
"decode admitted {admitted} and kept {retained}"
);
let refused = decode_state(&batch, &schema, AggregateOp::Sum, &tags, |total| {
if total >= retained {
Err(DataFusionError::Execution("no budget".into()))
} else {
Ok(())
}
});
assert!(
refused.is_err(),
"a budget below the {retained} bytes decode keeps answered anyway"
);
}
#[test]
fn decode_admits_before_it_allocates() {
let schema = series_schema(&["a", "b"], 2);
let tags = tags(&["job"]);
let batch = state_batch(
&tags,
&[Row {
name: None,
labels: &[Some("x")],
point: 0,
field: 1,
state: Some(state(1.0)),
}],
);
let mut totals = Vec::new();
let decoded = decode_state(&batch, &schema, AggregateOp::Sum, &tags, |total| {
totals.push(total);
Ok(())
})
.unwrap();
// The workspace, the group's state vector and its labels, and the figure never shrinks.
assert!(totals.len() >= 3);
assert!(totals.windows(2).all(|pair| pair[1] >= pair[0]));
assert_eq!(decoded.groups.len(), 1);
assert!(matches!(
decode_state(&batch, &schema, AggregateOp::Sum, &tags, |_| Err(
DataFusionError::Execution("no budget".into())
)),
Err(DataFusionError::Execution(_))
));
}
@@ -0,0 +1,988 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The merge half of a split native aggregate.
//!
//! A native `Complete` aggregate folds every contribution to a group, which is only correct when one
//! execution reads all of them. A raw-series scan hands its partitions to separate executions, so the
//! aggregate is split instead: the per-series prefix of the tree runs in a [`FusedSeries`] node that
//! exports the state each partition folded, and [`AggregateFinalize`] merges that state into the
//! statement's series.
//!
//! The split is structural. The innermost aggregate of the tree is replaced by an input node at its
//! own output - that is where merged values enter - and the nodes above it become this node's suffix.
//! What cannot be split correctly is refused with [`DataFusionError::NotImplemented`], which the
//! planner reads as "plan this query the existing way".
//!
//! [`AggregateFinalize`] is the logical half and [`AggregateFinalizeExec`] the physical one: the
//! executor gathers every producer's state, merges it with the same kernel a whole-vector aggregate
//! folds, runs the suffix over the merged series and converts its chunks into the statement's rows.
//! Nothing is handed over before the input ended and the suffix closed, so a row that reached a
//! consumer is a row no contribution can still change.
use std::cmp::Ordering;
use std::fmt::{self, Formatter};
use std::hash::{Hash, Hasher};
use std::mem::size_of;
use std::sync::Arc;
use datafusion::arrow::datatypes::{DataType, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::DFSchemaRef;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::error::{DataFusionError, Result as DfResult};
use datafusion::execution::context::TaskContext;
use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion::logical_expr::{Expr, Extension, LogicalPlan, UserDefinedLogicalNodeCore};
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion::physical_plan::execution_plan::EmissionType;
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements,
Partitioning, PlanProperties, SendableRecordBatchStream,
};
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::{FieldSpec, Series, SeriesSchema};
use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
use crate::aggregate::{AggregateOp, FloatMerger};
use crate::evaluated::EvaluatedChunk;
use crate::extension_plan::aggregate_exchange::{aggregate_op, decode_state, state_schema};
use crate::extension_plan::fused_series::{OutputColumn, classify_output, series_to_record_batch};
use crate::extension_plan::{FusedSeries, FusedSeriesBinding};
use crate::grid_series::series_bytes;
use crate::map::MathOp;
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
use crate::native::plan::{
AggregateKind, AggregateStage, BoundAggregate, BoundInput, Grouping, MapOp, NativeExpr,
NativeNode, NativeTree, NativeType,
};
/// One node that merges the partition-local state of a split aggregate.
///
/// Its input is the partition-local [`FusedSeries`] producer; its schema is the statement's row shape,
/// the time index, the aggregate's value columns and the labels its grouping keeps, not the state
/// layout the producer exports.
///
/// The fields are what the merge and the suffix are built from: the aggregate, the binding the
/// producer's state is named by (its wider tag list included), the tree above the merge, and the
/// field layout of the series being merged, which is the cut aggregate's own output - evaluated on
/// the statement's grid - and not the prefix's raw input.
#[derive(Debug)]
pub struct AggregateFinalize {
/// The PromQL text the whole tree was compiled from, which is what the plan line shows.
promql: Arc<str>,
/// The aggregate the split took out of the tree, bound as the compiler bound it.
op: BoundAggregate,
/// What the producer's frames were compiled against. Its `tags` are every logical tag of the
/// input, which is what an exported state row has to be able to name.
binding: FusedSeriesBinding,
/// The tree above the split aggregate, with that aggregate replaced by the input its merged
/// values enter at.
suffix: Arc<NativeTree>,
/// The partition-local producer, whose batches are aggregate state.
input: LogicalPlan,
/// The columns this node produces: its `Utf8` columns are the labels it writes.
output_schema: DFSchemaRef,
/// The field layout the split aggregate folds, on the grid its input is evaluated on.
series_schema: Arc<SeriesSchema>,
}
impl AggregateFinalize {
/// The name this node is shown under.
pub const fn name() -> &'static str {
"AggregateFinalize"
}
/// Splits `full_tree` around its innermost aggregate.
///
/// `rawinput` produces the raw series frames the prefix reads, and `output_schema` is the shape
/// the statement's rows have: the time index, the aggregate's value columns and the labels its
/// grouping keeps, as the existing planner names them.
///
/// The fields a grouping may not name are read off the tree's own raw input, not off its root:
/// the root is the prefix and is already evaluated, so its fields are the statement's value
/// columns rather than the raw ones a `by(...)` clause names.
///
/// [`DataFusionError::NotImplemented`] says this tree cannot be split correctly - a shape whose
/// per-partition half would not be one series at a time, or whose suffix would not run on merged
/// values - and the caller is expected to keep the plan it would have built without this node.
pub fn try_new(
promql: Arc<str>,
full_tree: NativeTree,
binding: FusedSeriesBinding,
rawinput: LogicalPlan,
output_schema: DFSchemaRef,
) -> DfResult<Self> {
let fields = prefix_fields(&full_tree)?;
let Some(split) = split(full_tree.root(), &fields, &binding.time_index)? else {
return Err(declined("the tree holds no splittable aggregate"));
};
let values = output_schema
.fields()
.iter()
.filter(|field| field.data_type() == &DataType::Float64)
.count();
if values != split.schema.fields.len() {
return Err(DataFusionError::Plan(format!(
"the aggregate of `{promql}` folds {} field(s), and the output schema declares \
{values} value column(s)",
split.schema.fields.len()
)));
}
let partial = FusedSeries::try_new_partial(
Arc::clone(&promql),
NativeTree::try_new(split.prefix)?,
binding.clone(),
vec![rawinput],
split.op.clone(),
)?;
Ok(Self {
promql,
op: split.op,
binding,
suffix: Arc::new(NativeTree::try_new(split.suffix)?),
input: LogicalPlan::Extension(Extension {
node: Arc::new(partial),
}),
output_schema,
series_schema: split.schema,
})
}
/// Whether `tree` holds an aggregate this node can merge.
///
/// The walk is the one [`Self::try_new`] does, without building either half. A caller uses it to
/// decide *before* planning anything else, so a shape this node declines is planned once, by the
/// path it keeps, instead of being planned once for a schema and again after the refusal.
///
/// `fields` is the raw field layout of the scan the tree was compiled against, which the caller
/// that resolved that scan already holds: the same names the tree's own raw input carries, and
/// the ones a `by(...)` may not name.
pub fn can_split(tree: &NativeTree, fields: &[FieldSpec], time_index: &str) -> bool {
matches!(split(tree.root(), fields, time_index), Ok(Some(_)))
}
/// The physical node that merges the state `input` produces and runs the tree above the cut.
///
/// `input` is the physical plan of [`Self::input`], the partition-local producer: its batches are
/// aggregate state, one partition per producer execution, so this node gathers them and answers
/// one partition whatever `input`'s layout is.
///
/// The row layout is read off this node's output schema the way the producer reads its frames off
/// its binding: its `Utf8` columns are the labels it writes, and its `Float64` columns name the
/// merged fields by position, since the merge folds the cut aggregate's fields in the order the
/// statement declares them. Building rejects an input that is not state, a suffix the runtime
/// does not execute and a schema [`classify_output`] cannot convert.
pub fn to_execution_plan(
&self,
input: Arc<dyn ExecutionPlan>,
) -> DfResult<Arc<dyn ExecutionPlan>> {
let op = aggregate_op(&self.op)?;
let output_schema: SchemaRef = self.output_schema.inner().clone();
// The same classification the producer makes over the series it writes, applied to the series
// the merge assembles: a second copy would let the two nodes disagree about which column a
// name reads.
let mut tags: Vec<String> = Vec::new();
let mut values: Vec<FieldSpec> = Vec::new();
for field in output_schema.fields() {
match field.data_type() {
DataType::Utf8 => tags.push(field.name().clone()),
DataType::Float64 => values.push(FieldSpec {
name: field.name().as_str().into(),
}),
// The time column and everything else are the classification's business below: it
// is the authority on which columns the conversion can produce.
_ => {}
}
}
let classification =
classify_output(&output_schema, &values, &tags, &self.binding.time_index)?;
Ok(Arc::new(AggregateFinalizeExec::try_new(
Arc::clone(&self.promql),
input,
Arc::clone(&self.suffix),
Arc::clone(&self.series_schema),
op,
self.binding.tags.clone(),
tags,
classification,
output_schema,
)?))
}
/// The comparable form of the split this node carries, for its plan line and its identity.
///
/// [`BoundAggregate`] carries no `Eq`/`Hash` - a quantile's parameter is an `f64` - so its
/// `Debug` rendering stands in, the way [`FusedSeries`] renders the tree it runs.
fn key(&self) -> String {
format!("{:?} {:?} {:?}", self.op.kind, self.op.group, self.op.stage)
}
}
impl UserDefinedLogicalNodeCore for AggregateFinalize {
fn name(&self) -> &str {
Self::name()
}
fn inputs(&self) -> Vec<&LogicalPlan> {
vec![&self.input]
}
fn schema(&self) -> &DFSchemaRef {
&self.output_schema
}
fn expressions(&self) -> Vec<Expr> {
// The aggregate and the tree above it are bound inside this node; there is no expression an
// optimizer could rewrite separately from the aggregate that owns it.
Vec::new()
}
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "AggregateFinalize: {} [{}]", self.promql, self.key())
}
fn with_exprs_and_inputs(
&self,
_exprs: Vec<Expr>,
mut inputs: Vec<LogicalPlan>,
) -> DfResult<Self> {
if inputs.len() != 1 {
return Err(DataFusionError::Internal(
"AggregateFinalize should have exactly one input".to_string(),
));
}
// The aggregate, the binding and the suffix are this node's own, so a rewritten input changes
// where the state comes from and nothing about how it is merged.
Ok(Self {
promql: Arc::clone(&self.promql),
op: self.op.clone(),
binding: self.binding.clone(),
suffix: Arc::clone(&self.suffix),
input: inputs.swap_remove(0),
output_schema: Arc::clone(&self.output_schema),
series_schema: Arc::clone(&self.series_schema),
})
}
}
impl PartialEq for AggregateFinalize {
fn eq(&self, other: &Self) -> bool {
// `NativeTree` carries no structural equality, so the rendered suffix stands in for it, as
// [`FusedSeries`] compares the tree it runs.
self.promql == other.promql
&& self.key() == other.key()
&& self.binding == other.binding
&& self.suffix.to_string() == other.suffix.to_string()
&& self.input == other.input
&& self.output_schema == other.output_schema
}
}
impl Eq for AggregateFinalize {}
impl Hash for AggregateFinalize {
fn hash<H: Hasher>(&self, state: &mut H) {
self.promql.hash(state);
self.key().hash(state);
self.binding.hash(state);
self.suffix.to_string().hash(state);
self.input.hash(state);
self.output_schema.hash(state);
}
}
impl PartialOrd for AggregateFinalize {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// The rendered forms stand in for the trees, as they do in equality.
let mine = (self.promql.to_string(), self.key(), self.suffix.to_string());
let theirs = (
other.promql.to_string(),
other.key(),
other.suffix.to_string(),
);
match mine.partial_cmp(&theirs) {
Some(Ordering::Equal) => {}
ord => return ord,
}
match self.binding.partial_cmp(&other.binding) {
Some(Ordering::Equal) => {}
ord => return ord,
}
match self.input.partial_cmp(&other.input) {
Some(Ordering::Equal) => {}
ord => return ord,
}
(self.output_schema == other.output_schema).then_some(Ordering::Equal)
}
}
/// One split: the two halves the tree was cut into, and what the cut aggregate folds.
struct Split {
/// The per-series tree below the cut aggregate, which the producer runs.
prefix: NativeNode,
/// The tree above it, starting at the input the merged values enter at.
suffix: NativeNode,
/// The aggregate that was cut out.
op: BoundAggregate,
/// What that aggregate produces: the layout the exported state is indexed by.
schema: Arc<SeriesSchema>,
}
/// Splits the innermost aggregate out of `node`.
///
/// `Ok(None)` is a subtree holding no aggregate. Only a map, an aggregate and a binary operation with
/// a constant on one side may sit above the cut: a map is point-wise and so is the same operation over
/// merged values, an aggregate runs over the complete merge, and a constant is broadcast over whatever
/// the other side answers - while an instant selection, a window, a vector-wide operation or a binary
/// operation between two vectors would read evaluated values, the whole vector or a matched pair,
/// shapes the merge does not produce.
fn split(node: &NativeNode, fields: &[FieldSpec], time_index: &str) -> DfResult<Option<Split>> {
match &node.expr {
NativeExpr::Input(_) | NativeExpr::Scalar(_) => Ok(None),
NativeExpr::Map { input, op } => {
let Some(mut inner) = split(input, fields, time_index)? else {
return Ok(None);
};
inner.suffix = NativeNode {
expr: NativeExpr::Map {
input: Box::new(inner.suffix),
op: op.clone(),
},
output: node.output.clone(),
};
Ok(Some(inner))
}
NativeExpr::Aggregate { input, op } => {
check_cut(op, fields, time_index)?;
match split(input, fields, time_index)? {
// An aggregate above the cut runs in the suffix, over the merged values: correct
// once every contribution is in, which is what the merge delivers.
Some(mut inner) => {
inner.suffix = NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(inner.suffix),
op: op.clone(),
},
output: node.output.clone(),
};
Ok(Some(inner))
}
None => {
admit_prefix(input)?;
let NativeType::Samples(schema) = &node.output else {
return Err(declined("an aggregate that produces no values"));
};
if schema.eval_grid.is_none() {
return Err(declined("an aggregate that produces no values"));
}
Ok(Some(Split {
prefix: (**input).clone(),
// The merged values enter the suffix as the aggregate's own output: the same
// binding and the same value, which is what the tree validates, at source
// `0` of the suffix's own execution - a source index is local to one
// execution, so the suffix names its one input rather than inheriting the
// prefix's.
suffix: NativeNode {
expr: NativeExpr::Input(BoundInput {
source_index: 0,
output: node.output.clone(),
ordering: SeriesOrdering::Contiguous,
}),
output: node.output.clone(),
},
op: op.clone(),
schema: Arc::clone(schema),
}))
}
}
}
NativeExpr::Instant { input, .. }
| NativeExpr::Window { input, .. }
| NativeExpr::Vector { input, .. } => match split(input, fields, time_index)? {
Some(_) => Err(declined(
"an aggregate under an operation that reads evaluated values",
)),
None => Ok(None),
},
NativeExpr::Binary {
left,
right,
matching,
} => {
// Each side is split once, and at most one of them may hold the innermost aggregate: two
// would be two cuts, which this node cannot merge.
let (left_split, right_split) = (
split(left, fields, time_index)?,
split(right, fields, time_index)?,
);
// A constant operand is broadcast over whatever the other side answers, so applying the
// same operation to the merged values is the operation the query wrote. Any other sibling
// would have to be matched with those values by label, which nothing below this node
// gathers.
let (mut inner, constant_on_the_left) = match (left_split, right_split) {
(None, None) => return Ok(None),
(Some(inner), None) if matches!(right.expr, NativeExpr::Scalar(_)) => {
(inner, false)
}
(None, Some(inner)) if matches!(left.expr, NativeExpr::Scalar(_)) => (inner, true),
_ => {
return Err(declined(
"an aggregate under a binary operation without a constant on the other side",
));
}
};
// The cut side's own suffix takes the place of the aggregate, on the side the query wrote
// it: a non-commutative operator means what that order says, and the matching and the
// output are the ones the compiler bound.
let (left, right) = if constant_on_the_left {
((**left).clone(), inner.suffix)
} else {
(inner.suffix, (**right).clone())
};
inner.suffix = NativeNode {
expr: NativeExpr::Binary {
left: Box::new(left),
right: Box::new(right),
matching: matching.clone(),
},
output: node.output.clone(),
};
Ok(Some(inner))
}
}
}
/// The field names of the raw series the prefix reads, in source order.
///
/// Read off the tree's own raw input node, which is the one authority on what the prefix is
/// compiled against: the root is already evaluated on the statement's grid, so its fields are the
/// statement's value columns rather than the raw ones a `by(...)` clause would name. The prefix is
/// one series at a time and the tree reads exactly one source, so the first raw input answers for
/// all of them.
fn prefix_fields(tree: &NativeTree) -> DfResult<Vec<FieldSpec>> {
fn raw_fields(node: &NativeNode) -> Option<Vec<FieldSpec>> {
match &node.expr {
NativeExpr::Input(input) => input
.output
.samples()
.filter(|schema| schema.eval_grid.is_none())
.map(|schema| schema.fields.to_vec()),
NativeExpr::Scalar(_) => None,
NativeExpr::Instant { input, .. }
| NativeExpr::Window { input, .. }
| NativeExpr::Map { input, .. }
| NativeExpr::Aggregate { input, .. }
| NativeExpr::Vector { input, .. } => raw_fields(input),
NativeExpr::Binary { left, right, .. } => {
raw_fields(left).or_else(|| raw_fields(right))
}
}
}
raw_fields(tree.root()).ok_or_else(|| declined("a tree that reads no raw series"))
}
/// Refuses an aggregate whose state the split cannot carry, and one grouped by a value field.
///
/// Only the eight fixed-width accumulators are carried: a quantile's state is the group's samples, and
/// a non-`Complete` stage is a state or a merge rather than an answer. A `by(...)` naming a value field
/// or the time index cannot be kept either - the state rows are indexed by field and by grid point,
/// so a group that varies with either is not a group - while a label the input does not have is
/// simply absent, exactly as it is in the existing planner.
fn check_cut(op: &BoundAggregate, fields: &[FieldSpec], time_index: &str) -> DfResult<()> {
if op.stage != AggregateStage::Complete {
return Err(declined("an aggregate that is not `Complete`"));
}
if matches!(op.kind, AggregateKind::Quantile { .. }) {
return Err(declined("a `quantile` aggregate"));
}
if let Grouping::By(labels) = &op.group
&& labels.iter().any(|label| {
label.as_ref() == time_index
|| fields
.iter()
.any(|field| field.name.as_ref() == label.as_ref())
})
{
return Err(declined("an aggregate grouped by a value field"));
}
Ok(())
}
/// Checks that the per-series prefix is a tree one partition can evaluate on its own.
///
/// The producer runs one execution per partition and folds exactly the series that partition's scan
/// returned, so the prefix has to answer one series from one series' samples: maps are point-wise, a
/// binary operation with a constant side applies that constant to each series its other side answers,
/// and a window or an instant selection reads the raw input itself. A raw input means no evaluation
/// grid - a tree whose input is already evaluated is a subquery's, which one partition cannot evaluate.
///
/// A `clamp` whose maximum is below its minimum answers no value at all, so the fold would see a group
/// with no sample of that field rather than the query the reader wrote.
fn admit_prefix(root: &NativeNode) -> DfResult<()> {
let mut node = root;
loop {
match &node.expr {
NativeExpr::Map { input, op } => {
for map_op in op.ops.iter() {
if let MapOp::Math(MathOp::Clamp { min, max }) = map_op
&& max < min
{
return Err(declined("a `clamp` whose maximum is below its minimum"));
}
}
node = input;
}
// Only a constant side is broadcast: it reaches each series the other side answers, so
// that side is the one the fold runs. Two constants answer one value per grid point and
// read no series, and two vectors are a label match over the whole vector, which is not
// what either half of the split produces.
NativeExpr::Binary { left, right, .. } => {
node = match (&left.expr, &right.expr) {
(NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => {
return Err(declined("a per-series prefix of two constants"));
}
(NativeExpr::Scalar(_), _) => &**right,
(_, NativeExpr::Scalar(_)) => &**left,
(_, _) => {
return Err(declined(
"a per-series prefix that matches two vectors by label",
));
}
};
}
_ => break,
}
}
let raw = |node: &NativeNode| match &node.expr {
NativeExpr::Input(input) => input
.output
.samples()
.is_some_and(|schema| schema.eval_grid.is_none()),
_ => false,
};
match &node.expr {
NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } if raw(input) => {
Ok(())
}
_ => Err(declined(
"a per-series prefix that is not one series at a time",
)),
}
}
fn declined(reason: &str) -> DataFusionError {
DataFusionError::NotImplemented(format!(
"the native aggregate split does not carry {reason}"
))
}
/// One converted output column: its array header, the buffers that hold its length and validity, and
/// its slot in the batches vector are each well under this.
const COLUMN_OVERHEAD: usize = 256;
/// The value capacity a converted string column starts with (Arrow's `StringArray::from`), which one
/// label column is charged for before it holds a row.
const STRING_CAPACITY: usize = 1024;
/// The physical half of a split aggregate: merges the state each partition folded, runs the tree
/// above the cut over the merged series and converts the result into the statement's rows.
///
/// The answer is built before its first batch is handed over, so a late input error is the stream's
/// first item rather than a row the error invalidates after it. What the answer holds is charged to
/// that stream, which is the only owner it has: the plan answers once.
///
/// The cut is the innermost aggregate of a tree of inputs, maps and aggregates, so the suffix the
/// runtime is asked to build is one of those; [`ExecutionPlan::execute`] builds its state and is
/// where a shape the runtime cannot run is refused.
///
/// The plain state-batch input is temporary. The final design consumes series frames directly
/// from FusedSeries instead of decoding and rebuilding this intermediate state-row layout.
struct AggregateFinalizeExec {
/// The PromQL text the whole tree was compiled from, which is what the plan line shows.
promql: Arc<str>,
/// The producer of the partition-local state, gathered to one partition.
input: Arc<dyn ExecutionPlan>,
/// The tree above the cut, which runs over the merged series.
suffix: Arc<NativeTree>,
/// The field layout the cut aggregate folds, which every decoded state row is checked against.
series_schema: Arc<SeriesSchema>,
/// The kernel the merge folds with.
op: AggregateOp,
/// The tag names the state rows are labelled by, which is what names their columns.
state_tags: Vec<String>,
/// The label column names this node writes, indexed by [`OutputColumn`].
tags: Arc<[String]>,
/// Where each output column comes from.
classification: Arc<[OutputColumn]>,
/// The columns this node produces.
output_schema: SchemaRef,
/// Per-node metrics, registered by the one execution of the suffix.
metric: ExecutionPlanMetricsSet,
/// This node's partitioning, emission and boundedness.
properties: Arc<PlanProperties>,
}
impl AggregateFinalizeExec {
/// The name this node is shown under.
const fn name() -> &'static str {
"AggregateFinalizeExec"
}
/// Creates the node, rejecting an input that is not the producer's state and a suffix the
/// runtime does not execute.
#[allow(clippy::too_many_arguments)]
fn try_new(
promql: Arc<str>,
input: Arc<dyn ExecutionPlan>,
suffix: Arc<NativeTree>,
series_schema: Arc<SeriesSchema>,
op: AggregateOp,
state_tags: Vec<String>,
tags: Vec<String>,
classification: Vec<OutputColumn>,
output_schema: SchemaRef,
) -> DfResult<Self> {
let state_layout = state_schema(&state_tags);
if input.schema().as_ref() != state_layout.as_ref() {
return Err(DataFusionError::Plan(format!(
"AggregateFinalizeExec merges the aggregate state of `{promql}`, whose layout is \
{state_layout:?}, not {:?}",
input.schema()
)));
}
let partitions = input.properties().partitioning.partition_count();
if partitions == 0 {
return Err(DataFusionError::Plan(
"AggregateFinalizeExec input has no partitions".to_string(),
));
}
// One merge is one operation over every partition's state, so the partitions are gathered
// first; a lone partition is used as it is.
let input: Arc<dyn ExecutionPlan> = if partitions > 1 {
Arc::new(CoalescePartitionsExec::new(input))
} else {
input
};
let properties = Arc::new(PlanProperties::new(
EquivalenceProperties::new(output_schema.clone()),
// One answer: every partition's state is merged into the same groups.
Partitioning::UnknownPartitioning(1),
// Nothing is handed over before the input ended and the suffix closed.
EmissionType::Final,
input.properties().boundedness,
));
Ok(Self {
promql,
input,
suffix,
series_schema,
op,
state_tags,
tags: tags.into(),
classification: classification.into(),
output_schema,
metric: ExecutionPlanMetricsSet::new(),
properties,
})
}
}
impl fmt::Debug for AggregateFinalizeExec {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("AggregateFinalizeExec").finish()
}
}
impl DisplayAs for AggregateFinalizeExec {
/// The query, then the tree above the cut, rendered by [`NativeTree`]'s own `Display`.
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
write!(f, "AggregateFinalizeExec: {}\n{}", self.promql, self.suffix)
}
}
impl ExecutionPlan for AggregateFinalizeExec {
fn name(&self) -> &str {
Self::name()
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.properties
}
/// The constructor gathered the input, so the single partition this node reads is already the one
/// it requires and no exchange can improve on it.
fn input_distribution_requirements(&self) -> InputDistributionRequirements {
InputDistributionRequirements::new(vec![Distribution::SinglePartition])
}
/// Raising the count is what an optimizer does by adding an exchange the constructor would then
/// have to gather again.
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![false]
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DfResult<TreeNodeRecursion>,
) -> DfResult<TreeNodeRecursion> {
// The aggregate and the tree above it are bound inside this node, which owns no expression.
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> DfResult<Arc<dyn ExecutionPlan>> {
let [child] = <[Arc<dyn ExecutionPlan>; 1]>::try_from(children).map_err(|children| {
DataFusionError::Plan(format!(
"AggregateFinalizeExec requires exactly one child, got {}",
children.len()
))
})?;
// Rebuilt rather than patched, so a child that changed shape is refused instead of decoded
// with a stale layout. The rebuild carries the same configuration and fresh reservations,
// which is what the next execution registers into.
Ok(Arc::new(Self::try_new(
Arc::clone(&self.promql),
child,
Arc::clone(&self.suffix),
Arc::clone(&self.series_schema),
self.op,
self.state_tags.clone(),
self.tags.to_vec(),
self.classification.to_vec(),
self.output_schema.clone(),
)?))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> DfResult<SendableRecordBatchStream> {
// One answer per statement: a second partition would answer the same groups again.
if partition != 0 {
return Err(DataFusionError::Execution(format!(
"AggregateFinalizeExec has exactly one partition, asked for {partition}"
)));
}
let pool = Arc::clone(&context.runtime_env().memory_pool);
// What the answer holds is charged to this stream and nothing else: the plan answers once, so
// the reservation is registered here and given back when the stream is dropped, whether the
// answer was read, dropped half way or refused.
let answer = Arc::new(MemoryConsumer::new("AggregateFinalizeExec output").register(&pool));
let state = NativeExecutionState::try_new(&self.suffix, Arc::clone(&pool))?;
state.register_metrics(&self.metric, 0);
let input_id = state.input_ids(0).next().ok_or_else(|| {
DataFusionError::Execution("AggregateFinalize suffix has no source-0 input".to_string())
})?;
if state.input_ids(0).count() != 1 {
return Err(DataFusionError::Execution(
"AggregateFinalize suffix must have exactly one source-0 input".to_string(),
));
}
let input = self.input.execute(0, Arc::clone(&context))?;
let merged = merge_into_batches(
input,
MemoryConsumer::new("AggregateFinalizeExec state").register(&pool),
NativeExecutor::new(state),
input_id,
Arc::clone(&self.series_schema),
self.op,
self.state_tags.clone(),
Arc::clone(&self.classification),
Arc::clone(&self.tags),
self.output_schema.clone(),
Arc::clone(&answer),
);
let batches = futures::stream::once(merged).flat_map(
|result: DfResult<Vec<RecordBatch>>| -> BoxStream<'static, DfResult<RecordBatch>> {
match result {
Ok(batches) => Box::pin(futures::stream::iter(
batches.into_iter().map(Ok::<_, DataFusionError>),
)),
// The answer never started, so the error is the stream's only item.
Err(error) => Box::pin(futures::stream::once(async move { Err(error) })),
}
},
);
let batches = batches.map(move |batch| {
// A failed answer has dropped every queued batch; successful batches stay charged
// until this stream drops.
if batch.is_err() {
answer.free();
}
batch
});
Ok(Box::pin(RecordBatchStreamAdapter::new(
self.output_schema.clone(),
batches,
)))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metric.clone_inner())
}
}
/// Merges every partition's state, runs the suffix over the merged series and converts its chunks
/// into the statement's rows.
///
/// Each batch is decoded and merged as it arrives, so at most one batch and one partition's state are
/// live beside the merge's own. Every admission here is a total rather than a step - the kernels report
/// what their work would keep live, not what it would add - so each one is charged together with what
/// the rest of this function already holds.
#[allow(clippy::too_many_arguments)]
async fn merge_into_batches(
mut input: SendableRecordBatchStream,
reservation: MemoryReservation,
mut executor: NativeExecutor,
input_id: InputId,
series_schema: Arc<SeriesSchema>,
op: AggregateOp,
state_tags: Vec<String>,
classification: Arc<[OutputColumn]>,
tags: Arc<[String]>,
output_schema: SchemaRef,
answer: Arc<MemoryReservation>,
) -> DfResult<Vec<RecordBatch>> {
let mut merger = FloatMerger::try_new(&series_schema, op)?;
while let Some(batch) = input.try_next().await? {
let batch_bytes = batch.get_array_memory_size();
// The batch is live beside the state decoded from it, which is live beside the merge's own.
reservation.try_resize(merger.state_bytes().saturating_add(batch_bytes))?;
let partial = decode_state(&batch, &series_schema, op, &state_tags, |total| {
reservation.try_resize(
merger
.state_bytes()
.saturating_add(batch_bytes)
.saturating_add(total),
)
})?;
// The decoded state is counted by the merge's own total, so only the batch is added here.
merger.merge_budgeted(partial, |total| {
reservation.try_resize(batch_bytes.saturating_add(total))
})?;
// The rows are folded in, so only what the merge keeps is still held.
drop(batch);
reservation.try_resize(merger.state_bytes())?;
}
// Only a successful end of the input answers: a failed read dropped the state above instead.
let series = merger.finish_budgeted(|total| reservation.try_resize(total))?;
// The merge is consumed by its answer, which replaces what it kept. The whole answer is charged at
// once and held until the loop ends: the vector and every series still waiting in it stay live
// while the loop folds them one by one, so releasing them one at a time would leave the rest
// uncharged. The amount is deliberately conservative - every series counted whole, no release.
let retained = series
.capacity()
.saturating_mul(size_of::<Series>())
.saturating_add(series.iter().map(series_bytes).sum::<usize>());
reservation.try_resize(retained)?;
let mut batches = Vec::new();
let mut held = 0usize;
for series in series {
// Every group is one series and is complete here, so it closes its own chunk: the suffix runs
// on merged values, not on fragments of them.
executor.push_evaluated(
input_id,
EvaluatedChunk {
series,
is_last: true,
},
)?;
drain(
&mut executor,
&mut batches,
&mut held,
&answer,
&classification,
&tags,
&output_schema,
)?;
}
// Every series is the suffix's now, and its own reservations account for it.
reservation.try_resize(0)?;
// Nothing more will arrive, so this is what a collecting node answers.
executor.end_of_input()?;
drain(
&mut executor,
&mut batches,
&mut held,
&answer,
&classification,
&tags,
&output_schema,
)?;
// The rows are what stays held once the series they came from are gone.
answer.try_resize(batches.iter().map(RecordBatch::get_array_memory_size).sum())?;
Ok(batches)
}
/// Hands over every chunk the suffix has settled, as rows.
///
/// Each chunk is admitted before it is converted, by a coarse estimate of the storage its rows need -
/// the series itself, one copy of the timestamps and values, and each label column's initial capacity,
/// offsets and repeated text - so an answer that outgrows the pool is refused while it is built. The
/// batch's own size replaces the estimate once it exists.
#[allow(clippy::too_many_arguments)]
fn drain(
executor: &mut NativeExecutor,
batches: &mut Vec<RecordBatch>,
held: &mut usize,
answer: &MemoryReservation,
classification: &[OutputColumn],
tags: &[String],
output_schema: &SchemaRef,
) -> DfResult<()> {
while let Some(chunk) = executor.next_chunk()? {
let series = &chunk.series;
let rows = series.time.len();
// The series itself, one copy of the timestamps and values at eight bytes a cell, and a header
// for each column and its batch slot.
let mut estimate = series_bytes(series)
.saturating_add(rows.saturating_mul(8 * series.fields.len().saturating_add(1)))
.saturating_add(classification.len().saturating_mul(COLUMN_OVERHEAD))
.saturating_add(size_of::<RecordBatch>());
// A label column is a string column: its starting capacity, an offset and a validity bit a row,
// and the value it repeats with the room a growing buffer needs.
for tag in tags.iter() {
let text = rows.saturating_mul(series.metric.get(tag).map_or(0, str::len));
estimate = estimate
.saturating_add(STRING_CAPACITY)
.saturating_add(rows.saturating_mul(8))
.saturating_add(text.saturating_mul(2));
}
answer.try_resize(held.saturating_add(estimate))?;
let batch = series_to_record_batch(classification, tags, output_schema, &chunk)?;
// What the batch holds replaces the estimate: the chunk is dropped as its rows are kept.
*held = held.saturating_add(batch.get_array_memory_size());
answer.try_resize(*held)?;
batches.push(batch);
}
Ok(())
}
#[cfg(test)]
mod exec_tests;
#[cfg(test)]
mod tests;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,584 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! What the split has to keep right: which aggregate is cut out, what stays above the merge, and
//! which shapes are declined so the caller can keep the plan it had.
//!
//! The trees are built node by node with the same bindings the PromQL compiler produces, because the
//! compiler lives in the `query` crate, which depends on this one.
use super::*;
use datafusion::arrow::datatypes::{Field, TimeUnit};
use datafusion::common::DFSchema;
use datatypes::series::samples::FieldSpec;
use datatypes::series::time::{EvalGrid, GridSpec};
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
/// The statement's grid, which every evaluated chunk is addressed on.
fn grid() -> Arc<EvalGrid> {
Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).unwrap()).unwrap())
}
/// The raw fields the tree's input binds, which a scan below it has to be able to produce.
fn raw_fields() -> Arc<[FieldSpec]> {
Arc::from([FieldSpec { name: "v0".into() }])
}
/// The raw samples a scan hands over: one field, no grid.
fn raw() -> NativeNode {
let output = NativeType::Samples(Arc::new(SeriesSchema {
fields: raw_fields(),
eval_grid: None,
}));
NativeNode {
expr: NativeExpr::Input(BoundInput {
source_index: 0,
output: output.clone(),
ordering: SeriesOrdering::KeyThenTime,
}),
output,
}
}
/// The evaluated layout a selection or a window reports.
fn evaluated() -> NativeType {
NativeType::Samples(Arc::new(SeriesSchema {
fields: Arc::from([FieldSpec { name: "v0".into() }]),
eval_grid: Some(grid()),
}))
}
/// `rate(v0[5m])`, the per-series prefix of every aggregate below.
fn window() -> NativeNode {
NativeNode {
expr: NativeExpr::Window {
input: Box::new(raw()),
op: crate::native::plan::BoundWindow {
function: crate::range_eval::RangeFunction::Rate,
window: crate::range_eval::RangeWindow {
range_ms: 300_000,
offset_ms: 0,
anchor_ms: None,
modifier: None,
},
input_grid: None,
output_grid: grid(),
},
},
output: evaluated(),
}
}
/// An instant selection, the other per-series prefix the split admits.
fn instant() -> NativeNode {
NativeNode {
expr: NativeExpr::Instant {
input: Box::new(raw()),
op: crate::native::plan::BoundInstant {
lookback_ms: 300_000,
offset_ms: 0,
output_grid: grid(),
},
},
output: evaluated(),
}
}
fn map_over(inner: NativeNode, ops: Vec<MathOp>) -> NativeNode {
let output = inner.output.clone();
NativeNode {
expr: NativeExpr::Map {
input: Box::new(inner),
op: crate::native::plan::BoundMap {
ops: ops.into_iter().map(MapOp::Math).collect::<Vec<_>>().into(),
},
},
output,
}
}
fn aggregate_over(
inner: NativeNode,
kind: AggregateKind,
group: Grouping,
stage: AggregateStage,
) -> NativeNode {
let output = inner.output.clone();
NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(inner),
op: BoundAggregate { kind, group, stage },
},
output,
}
}
fn complete(kind: AggregateKind, group: Grouping) -> impl Fn(NativeNode) -> NativeNode {
move |inner| aggregate_over(inner, kind, group.clone(), AggregateStage::Complete)
}
fn by(labels: &[&str]) -> Grouping {
Grouping::By(
labels
.iter()
.map(|label| Arc::<str>::from(*label))
.collect(),
)
}
/// The plan below the producer: a scan producing the raw fields the tree's input binds.
///
/// The producer checks that its child can produce every field its tree input declares, so the scan
/// names them as nullable float columns; the merge itself reads none of them.
fn scan() -> LogicalPlan {
let columns = raw_fields()
.iter()
.map(|field| {
(
None,
Arc::new(Field::new(field.name.as_ref(), DataType::Float64, true)),
)
})
.collect::<Vec<_>>();
LogicalPlan::EmptyRelation(datafusion::logical_expr::EmptyRelation {
produce_one_row: false,
schema: Arc::new(DFSchema::new_with_metadata(columns, Default::default()).unwrap()),
})
}
fn binding() -> FusedSeriesBinding {
FusedSeriesBinding {
grid: grid(),
metric_name: Some(Arc::from("m")),
time_index: "ts".to_string(),
tags: vec!["k0".to_string(), "k1".to_string()],
}
}
/// The rows a finalized aggregate reports: the time index, one value column and the grouped labels.
fn output_schema(values: &[&str], tags: &[&str]) -> DFSchemaRef {
let mut columns = vec![(
None,
Arc::new(Field::new(
"ts",
DataType::Timestamp(TimeUnit::Millisecond, None),
false,
)),
)];
for name in values {
columns.push((None, Arc::new(Field::new(*name, DataType::Float64, true))));
}
for name in tags {
columns.push((None, Arc::new(Field::new(*name, DataType::Utf8, true))));
}
Arc::new(DFSchema::new_with_metadata(columns, Default::default()).unwrap())
}
fn finalize(root: NativeNode, output: DFSchemaRef) -> DfResult<AggregateFinalize> {
AggregateFinalize::try_new(
Arc::from("sum(rate(m[5m]))"),
NativeTree::try_new(root)?,
binding(),
scan(),
output,
)
}
/// The labels this node writes, read off its schema the way the physical half reads them.
fn output_tags(node: &AggregateFinalize) -> Vec<String> {
node.schema()
.fields()
.iter()
.filter(|field| field.data_type() == &DataType::Utf8)
.map(|field| field.name().clone())
.collect()
}
/// The producer this node merges.
fn producer(node: &AggregateFinalize) -> &FusedSeries {
let LogicalPlan::Extension(Extension { node }) = &node.input else {
panic!("the merge should read a producer");
};
node.as_any()
.downcast_ref::<FusedSeries>()
.expect("the producer is a fused series node")
}
/// The innermost aggregate is the one cut out, and only the nodes that may sit above it keep their
/// place: the outer aggregate runs in the suffix, over the merged values.
#[test]
fn the_innermost_aggregate_is_cut_out_of_a_nested_tree() {
let inner = complete(AggregateKind::Avg, by(&["k0"]))(window());
let root = complete(AggregateKind::Sum, by(&[]))(inner);
let node = finalize(root, output_schema(&["sum(avg(v0))"], &[])).unwrap();
// The producer runs the per-series prefix and exports the inner aggregate's state.
let producer = producer(&node);
assert_eq!(
Some(AggregateKind::Avg),
producer.partial_fold().map(|op| op.kind)
);
let prefix = producer.tree().to_string();
assert!(prefix.contains("Window"), "{prefix}");
assert!(!prefix.contains("Aggregate"), "{prefix}");
// The suffix starts at the merged values and holds the outer aggregate.
let suffix = node.suffix.to_string();
assert!(suffix.contains("Aggregate"), "{suffix}");
assert!(suffix.contains("Input"), "{suffix}");
assert!(!suffix.contains("Window"), "{suffix}");
}
/// A map above the merge is point-wise, so it is the same operation over merged values.
#[test]
fn an_outer_map_stays_in_the_suffix() {
let root = map_over(
complete(AggregateKind::Sum, by(&["k0"]))(instant()),
vec![MathOp::Ceil],
);
let node = finalize(root, output_schema(&["ceil(sum(v0))"], &["k0"])).unwrap();
let suffix = node.suffix.to_string();
assert!(suffix.contains("Map"), "{suffix}");
assert!(suffix.contains("Input"), "{suffix}");
assert_eq!(output_tags(&node), ["k0".to_string()]);
}
/// `left <op> right` with a constant on one side, bound the way the compiler binds a broadcast: the
/// operation reports the vector side's samples.
fn broadcast(left: NativeNode, right: NativeNode, op: BinaryOp) -> NativeNode {
let output = if matches!(left.output, NativeType::Scalar(_)) {
right.output.clone()
} else {
left.output.clone()
};
NativeNode {
expr: NativeExpr::Binary {
left: Box::new(left),
right: Box::new(right),
matching: BinaryMatching {
op,
return_bool: false,
labels: MatchingLabels::Ignoring(Vec::new()),
cardinality: Cardinality::OneToOne,
fill: FillValues::default(),
},
},
output,
}
}
/// The constant scalar `value`, on the statement's grid.
fn scalar_on(value: f64) -> NativeNode {
NativeNode {
expr: NativeExpr::Scalar(crate::native::plan::BoundScalar { value }),
output: NativeType::Scalar(grid()),
}
}
/// A constant operand is broadcast over the merged values, so the aggregate under the other side is
/// still the one cut: the suffix keeps the operation, the operand order and the matching, with the
/// merged values where the aggregate was.
#[test]
fn a_constant_operand_keeps_the_cut_below_it() {
for (constant_on_the_left, value) in [(true, "100 - avg(v0)"), (false, "avg(v0) - 100")] {
let aggregate = complete(AggregateKind::Avg, by(&["k0"]))(window());
let root = if constant_on_the_left {
broadcast(scalar_on(100.0), aggregate, BinaryOp::Sub)
} else {
broadcast(aggregate, scalar_on(100.0), BinaryOp::Sub)
};
let node = finalize(root, output_schema(&[value], &["k0"])).unwrap();
// The producer still runs only the per-series prefix: the constant is above the cut, so the
// window is all the prefix holds and the constant is applied in the suffix.
let prefix = producer(&node).tree().to_string();
assert!(prefix.contains("Window"), "{prefix}");
assert!(!prefix.contains("Binary"), "{prefix}");
assert!(!prefix.contains("Scalar"), "{prefix}");
// The suffix is the operation over the merged values, which enter it as its own source `0`:
// the prefix's and the suffix's inputs are separate executions, not one exchange.
let NativeExpr::Binary {
left,
right,
matching,
} = &node.suffix.root().expr
else {
panic!("the operation stays above the cut: {}", node.suffix);
};
assert_eq!(BinaryOp::Sub, matching.op, "the operator is kept");
let (constant, merged) = if constant_on_the_left {
(left, right)
} else {
(right, left)
};
assert!(
matches!(constant.expr, NativeExpr::Scalar(_)),
"the constant keeps its side: {}",
node.suffix
);
assert!(
matches!(&merged.expr, NativeExpr::Input(input) if input.source_index == 0),
"the merged values enter where the aggregate was: {}",
node.suffix
);
assert!(
!node.suffix.to_string().contains("Window"),
"{}",
node.suffix
);
}
}
/// A binary operation above the cut is only the operation over merged values when its other side is a
/// constant: two aggregates are two cuts, a vector sibling would have to be matched with the merged
/// values by label, and a prefix that pairs two vectors reads the whole vector rather than one series.
#[test]
fn a_binary_operation_without_a_constant_operand_is_refused() {
let folded = || {
complete(AggregateKind::Sum, by(&[]))(complete(AggregateKind::Avg, by(&["k0"]))(window()))
};
for root in [
// Two sides fold, and one cut cannot answer two aggregates.
broadcast(folded(), folded(), BinaryOp::Add),
// A vector sibling is another series set, which nothing below the merge brings together.
broadcast(
complete(AggregateKind::Sum, by(&["k0"]))(window()),
window(),
BinaryOp::Add,
),
broadcast(
window(),
complete(AggregateKind::Sum, by(&["k0"]))(window()),
BinaryOp::Div,
),
// A prefix that pairs two vectors reads the whole vector at a point, which one partition
// cannot do: admitting a constant operand does not admit this.
complete(AggregateKind::Sum, by(&["k0"]))(broadcast(window(), window(), BinaryOp::Div)),
] {
let error = finalize(root, output_schema(&["sum(v0)"], &["k0"])).unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
}
}
/// The output's labels are the schema's string columns, which is what the merge writes.
#[test]
fn the_output_labels_are_the_schema_labels() {
let root = complete(AggregateKind::Sum, by(&["k0", "k1"]))(window());
let node = finalize(root, output_schema(&["sum(v0)"], &["k0", "k1"])).unwrap();
assert_eq!(output_tags(&node), ["k0".to_string(), "k1".to_string()]);
}
/// An aggregate directly over the raw input never reaches the split: the tree's own validation
/// refuses a `Complete` aggregate that consumes raw samples, so nothing here has a prefix to run.
#[test]
fn a_raw_aggregate_is_refused_at_the_tree_boundary() {
let error = NativeTree::try_new(complete(AggregateKind::Sum, by(&["k0"]))(raw())).unwrap_err();
assert!(matches!(error, DataFusionError::Internal(_)), "{error}");
assert!(
error.to_string().contains("evaluated vector"),
"the refusal names the input a complete aggregate needs: {error}"
);
}
/// A window over an evaluated input is a subquery, evaluated on its own grid, so what the merge
/// produces is not its input: the split keeps the existing plan.
#[test]
fn a_subquery_above_an_aggregate_is_refused() {
let root = complete(AggregateKind::Sum, by(&["k0"]))(NativeNode {
expr: NativeExpr::Window {
input: Box::new(complete(AggregateKind::Sum, by(&["k0"]))(window())),
op: crate::native::plan::BoundWindow {
function: crate::range_eval::RangeFunction::Rate,
window: crate::range_eval::RangeWindow {
range_ms: 300_000,
offset_ms: 0,
anchor_ms: None,
modifier: None,
},
input_grid: Some(grid()),
output_grid: grid(),
},
},
output: evaluated(),
});
let error = finalize(root, output_schema(&["sum(v0)"], &["k0"])).unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
}
/// `clamp` with its maximum below its minimum answers nothing, so the fold would see a group with no
/// sample rather than the query the reader wrote.
#[test]
fn an_empty_clamp_is_refused() {
let empty = map_over(instant(), vec![MathOp::Clamp { min: 2.0, max: 1.0 }]);
let error = finalize(
complete(AggregateKind::Sum, by(&["k0"]))(empty),
output_schema(&["sum(v0)"], &["k0"]),
)
.unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
// The same clamp the other way round is a range, and the prefix keeps it.
let range = map_over(instant(), vec![MathOp::Clamp { min: 0.0, max: 1.0 }]);
assert!(
finalize(
complete(AggregateKind::Sum, by(&["k0"]))(range),
output_schema(&["sum(v0)"], &["k0"])
)
.is_ok()
);
}
/// A group that varies with a value field or the grid point is not a group the state rows can name.
#[test]
fn an_aggregate_grouped_by_a_value_field_or_the_time_index_is_refused() {
for group in [by(&["v0"]), by(&["ts"])] {
let error = finalize(
complete(AggregateKind::Sum, group)(window()),
output_schema(&["sum(v0)"], &["v0"]),
)
.unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
}
// A label the input does not carry is simply absent, as in the existing planner.
assert!(
finalize(
complete(AggregateKind::Sum, by(&["absent"]))(window()),
output_schema(&["sum(v0)"], &["absent"])
)
.is_ok()
);
}
/// A quantile's state is the group's samples, which neither half of this node can carry.
#[test]
fn a_quantile_aggregate_is_refused() {
let root = complete(AggregateKind::Quantile { quantile: 0.5 }, by(&["k0"]))(window());
let error = finalize(root, output_schema(&["q(v0)"], &["k0"])).unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
}
/// A tree with no aggregate at all is not this node's.
#[test]
fn a_tree_without_an_aggregate_is_refused() {
let error = finalize(window(), output_schema(&["v0"], &[])).unwrap_err();
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"{error}"
);
}
/// The caller's schema has to describe the rows this node reports: one value column per field the
/// aggregate folds.
#[test]
fn the_output_schema_has_to_match_the_cut() {
let root = || complete(AggregateKind::Sum, by(&["k0"]))(window());
for output in [
// No value column where the aggregate folds one field.
output_schema(&[], &["k0"]),
// A value column per field the aggregate does not fold.
output_schema(&["sum(v0)", "sum(v1)"], &["k0"]),
] {
let error = finalize(root(), output).unwrap_err();
assert!(matches!(error, DataFusionError::Plan(_)), "{error}");
}
assert!(finalize(root(), output_schema(&["sum(v0)"], &["k0"])).is_ok());
}
/// The two halves of a split name their own sources, and neither reuses the other's.
///
/// The prefix still reads the one raw scan at execution source `0` and declares no grid - it is raw
/// samples. The suffix is a tree of its own, built at the cut, so its one input is source `0` of
/// *its* execution and carries the cut aggregate's evaluated output, on the same grid the node was
/// bound to: the merged values enter there, as the aggregate's own output shape.
#[test]
fn the_prefix_and_the_suffix_each_name_their_own_source_zero() {
let root = complete(AggregateKind::Sum, by(&["k0"]))(window());
let node = finalize(root, output_schema(&["sum(v0)"], &["k0"])).unwrap();
// The prefix is what the producer runs: one raw input on source 0, and no evaluation grid.
fn inputs(node: &NativeNode, found: &mut Vec<(usize, Option<Arc<EvalGrid>>)>) {
match &node.expr {
NativeExpr::Input(input) => found.push((
input.source_index,
input
.output
.samples()
.cloned()
.and_then(|schema| schema.eval_grid.clone()),
)),
NativeExpr::Scalar(_) => {}
NativeExpr::Instant { input, .. }
| NativeExpr::Window { input, .. }
| NativeExpr::Map { input, .. }
| NativeExpr::Aggregate { input, .. }
| NativeExpr::Vector { input, .. } => inputs(input, found),
NativeExpr::Binary { left, right, .. } => {
inputs(left, found);
inputs(right, found);
}
}
}
let prefix = producer(&node).tree().clone();
let mut raw_inputs = Vec::new();
inputs(prefix.root(), &mut raw_inputs);
let [raw_input] = raw_inputs.as_slice() else {
panic!("the prefix reads one raw input, got {raw_inputs:?}");
};
assert_eq!(0, raw_input.0, "the prefix reads execution source 0");
assert!(
raw_input.1.is_none(),
"the prefix's input is raw samples, so it has no grid: {raw_input:?}"
);
// The suffix is its own tree: one input, named by its own execution's source 0, evaluated on
// the grid the node is bound to.
let mut suffix_inputs = Vec::new();
inputs(node.suffix.root(), &mut suffix_inputs);
let [suffix_input] = suffix_inputs.as_slice() else {
panic!("the suffix reads one input, got {suffix_inputs:?}");
};
assert_eq!(
0, suffix_input.0,
"the suffix's merged values are source 0 of its own execution"
);
let grid = suffix_input
.1
.as_ref()
.expect("the merged values are evaluated, so they are on a grid");
assert_eq!(
node.binding.grid.spec(),
grid.spec(),
"the suffix runs on the grid the node is bound to"
);
}
+193 -25
View File
@@ -41,7 +41,7 @@ use std::collections::VecDeque;
use std::fmt::{self, Formatter};
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use common_query::series_frame::{ensure_frame_matches_label_source, unpack_raw_series};
@@ -53,7 +53,7 @@ use datafusion::common::DFSchemaRef;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::error::{DataFusionError, Result as DataFusionResult};
use datafusion::execution::context::TaskContext;
use datafusion::execution::memory_pool::UnboundedMemoryPool;
use datafusion::execution::memory_pool::{MemoryReservation, UnboundedMemoryPool};
use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNodeCore};
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};
@@ -64,14 +64,18 @@ use datafusion::physical_plan::{
};
use datatypes::series::SeriesOrdering;
use datatypes::series::raw::RawSeriesChunk;
use datatypes::series::samples::{DenseSamplesRef, SampleRef, Samples, SeriesSchema};
use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, Samples, SeriesSchema};
use datatypes::series::time::EvalGrid;
use futures::Stream;
use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream};
use crate::evaluated::EvaluatedChunk;
use crate::extension_plan::aggregate_exchange::{PartialFold, aggregate_op, state_schema};
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
use crate::native::plan::{NativeExpr, NativeNode, NativeTree, NativeType};
use crate::native::plan::{
AggregateKind, BoundAggregate, Grouping, NativeExpr, NativeNode, NativeTree, NativeType,
reads_across_series,
};
use crate::source::materialize_raw_labels;
#[cfg(test)]
@@ -176,6 +180,11 @@ pub struct FusedSeries {
children: Vec<LogicalPlan>,
/// The columns this node produces.
output_schema: DFSchemaRef,
/// The aggregate whose partition-local state this node exports instead of query rows.
///
/// This row-state bridge is temporary: native final aggregation will consume series frames
/// directly, removing state-row encoding and reconstruction.
partial_fold: Option<BoundAggregate>,
}
impl FusedSeries {
@@ -199,9 +208,48 @@ impl FusedSeries {
binding,
children,
output_schema,
partial_fold: None,
})
}
/// Creates a one-source node that exports partition-local state for a complete aggregate.
pub(crate) fn try_new_partial(
promql: Arc<str>,
tree: NativeTree,
binding: FusedSeriesBinding,
children: Vec<LogicalPlan>,
op: BoundAggregate,
) -> DataFusionResult<Self> {
validate_binding(&tree, &binding, children.len())?;
if children.len() != 1 {
return Err(DataFusionError::Plan(
"FusedSeries partial fold requires one raw child".into(),
));
}
if reads_across_series(tree.root()) {
return Err(DataFusionError::Plan(
"FusedSeries partial fold prefix reads across series".into(),
));
}
aggregate_op(&op)?;
let output_schema = Arc::new(datafusion::common::DFSchema::try_from(state_schema(
&binding.tags,
))?);
Ok(Self {
promql,
tree,
binding,
children,
output_schema,
partial_fold: Some(op),
})
}
/// The aggregate whose partition-local state this node exports.
pub fn partial_fold(&self) -> Option<&BoundAggregate> {
self.partial_fold.as_ref()
}
/// The PromQL text this node was compiled from.
pub fn promql(&self) -> &str {
&self.promql
@@ -239,13 +287,14 @@ impl FusedSeries {
self.children.len()
)));
}
Ok(Arc::new(FusedSeriesExec::try_new(
Ok(Arc::new(FusedSeriesExec::build(
Arc::clone(&self.promql),
inputs,
Arc::new(self.tree.clone()),
output_schema,
self.binding.time_index.clone(),
self.binding.tags.clone(),
self.partial_fold.clone(),
)?))
}
}
@@ -270,7 +319,15 @@ impl UserDefinedLogicalNodeCore for FusedSeries {
}
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "FusedSeries: {}", self.promql)
match &self.partial_fold {
Some(op) => write!(
f,
"FusedSeries: {} [partial {}]",
self.promql,
render_partial_fold(op)
),
None => write!(f, "FusedSeries: {}", self.promql),
}
}
fn with_exprs_and_inputs(
@@ -285,6 +342,7 @@ impl UserDefinedLogicalNodeCore for FusedSeries {
binding: self.binding.clone(),
children: inputs,
output_schema: Arc::clone(&self.output_schema),
partial_fold: self.partial_fold.clone(),
})
}
}
@@ -301,6 +359,7 @@ impl PartialEq for FusedSeries {
&& self.binding == other.binding
&& self.children == other.children
&& self.output_schema == other.output_schema
&& partial_key(self.partial_fold.as_ref()) == partial_key(other.partial_fold.as_ref())
}
}
@@ -312,6 +371,7 @@ impl Hash for FusedSeries {
self.binding.hash(state);
self.children.hash(state);
self.output_schema.hash(state);
partial_key(self.partial_fold.as_ref()).hash(state);
}
}
@@ -333,6 +393,12 @@ impl PartialOrd for FusedSeries {
Some(Ordering::Equal) => {}
ord => return ord,
}
match partial_key(self.partial_fold.as_ref())
.partial_cmp(&partial_key(other.partial_fold.as_ref()))
{
Some(Ordering::Equal) => {}
ord => return ord,
}
match tree_input_fields(&self.tree).cmp(&tree_input_fields(&other.tree)) {
Ordering::Equal => {}
ord => return Some(ord),
@@ -345,6 +411,24 @@ impl PartialOrd for FusedSeries {
}
}
/// Renders a partial aggregate with the stable names used by the exchange plan.
fn render_partial_fold(op: &BoundAggregate) -> String {
let group = match &op.group {
Grouping::By(labels) => format!("by ({})", labels.join(", ")),
Grouping::Without(labels) => format!("without ({})", labels.join(", ")),
};
let kind = match op.kind {
AggregateKind::Quantile { quantile } => format!("quantile({quantile})"),
kind => format!("{kind:?}").to_lowercase(),
};
format!("{kind} {group} {:?}", op.stage)
}
/// A stable comparable representation for an optional partial fold.
fn partial_key(partial: Option<&BoundAggregate>) -> Option<String> {
partial.map(render_partial_fold)
}
/// The raw field names bound to each input leaf, retaining source association and leaf order.
fn tree_input_fields(tree: &NativeTree) -> Vec<(usize, Vec<String>)> {
tree_inputs(tree)
@@ -506,7 +590,7 @@ fn validate_physical_tree(tree: &NativeTree) -> DataFusionResult<Vec<Arc<SeriesS
/// Where one output column of [`FusedSeriesExec`] comes from.
#[derive(Clone, Copy, Debug)]
enum OutputColumn {
pub(crate) enum OutputColumn {
/// The evaluation grid timestamps of the current chunk.
Time,
/// Series field by index in the bound series schema.
@@ -516,9 +600,9 @@ enum OutputColumn {
}
/// Classifies every output column, rejecting anything the conversion cannot produce.
fn classify_output(
pub(crate) fn classify_output(
output_schema: &SchemaRef,
series_schema: &SeriesSchema,
series_fields: &[FieldSpec],
tags: &[String],
time_column: &str,
) -> DataFusionResult<Vec<OutputColumn>> {
@@ -533,11 +617,7 @@ fn classify_output(
"tag column {tag:?} of FusedSeriesExec cannot be the time column"
)));
}
if series_schema
.fields
.iter()
.any(|field| field.name.as_ref() == tag)
{
if series_fields.iter().any(|field| field.name.as_ref() == tag) {
return Err(DataFusionError::Plan(format!(
"tag column {tag:?} of FusedSeriesExec clashes with a series field"
)));
@@ -545,7 +625,7 @@ fn classify_output(
}
let mut time_seen = false;
let mut field_seen = vec![false; series_schema.fields.len()];
let mut field_seen = vec![false; series_fields.len()];
let mut tag_seen = vec![false; tags.len()];
let mut classification = Vec::with_capacity(output_schema.fields().len());
for field in output_schema.fields() {
@@ -573,8 +653,7 @@ fn classify_output(
classification.push(OutputColumn::Time);
continue;
}
if let Some(index) = series_schema
.fields
if let Some(index) = series_fields
.iter()
.position(|field| field.name.as_ref() == name)
{
@@ -635,7 +714,7 @@ fn classify_output(
if !seen {
return Err(DataFusionError::Plan(format!(
"missing field column {:?} in FusedSeriesExec output schema",
series_schema.fields[index].name
series_fields[index].name
)));
}
}
@@ -671,6 +750,8 @@ pub struct FusedSeriesExec {
output_schema: SchemaRef,
/// Per-node metrics, registered by each execution of the tree.
metric: ExecutionPlanMetricsSet,
/// Aggregate state exported by each partition, when this is the partial mode.
partial_fold: Option<BoundAggregate>,
/// This node's partitioning, emission and boundedness.
properties: Arc<PlanProperties>,
}
@@ -694,6 +775,18 @@ impl FusedSeriesExec {
output_schema: SchemaRef,
time_column: String,
tags: Vec<String>,
) -> DataFusionResult<Self> {
Self::build(promql, inputs, tree, output_schema, time_column, tags, None)
}
fn build(
promql: Arc<str>,
inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
tree: Arc<NativeTree>,
output_schema: SchemaRef,
time_column: String,
tags: Vec<String>,
partial_fold: Option<BoundAggregate>,
) -> DataFusionResult<Self> {
let raw_schemas = validate_physical_tree(&tree)?;
if inputs.len() != raw_schemas.len() || inputs.is_empty() {
@@ -710,8 +803,17 @@ impl FusedSeriesExec {
.output
.samples()
.ok_or_else(|| DataFusionError::Plan("FusedSeries output is not samples".into()))?;
if let Some(op) = &partial_fold {
aggregate_op(op)?;
}
if partial_fold.is_some() && (inputs.len() != 1 || reads_across_series(tree.root())) {
return Err(DataFusionError::Plan(
"FusedSeries partial fold requires one raw source and a per-series prefix".into(),
));
}
let mut output_tags = tags.clone();
if let NativeExpr::Binary { matching, .. } = &tree.root().expr
if partial_fold.is_none()
&& let NativeExpr::Binary { matching, .. } = &tree.root().expr
&& matching.cardinality == crate::vector_match::Cardinality::OneToOne
{
match &matching.labels {
@@ -723,8 +825,16 @@ impl FusedSeriesExec {
}
}
}
let classification =
classify_output(&output_schema, output_series, &output_tags, &time_column)?;
let classification = if partial_fold.is_some() {
Vec::new()
} else {
classify_output(
&output_schema,
&output_series.fields,
&output_tags,
&time_column,
)?
};
let partition_count = inputs[0].0.properties().partitioning.partition_count();
for (index, (input, label_source, ordering)) in inputs.iter().enumerate() {
let count = input.properties().partitioning.partition_count();
@@ -773,6 +883,7 @@ impl FusedSeriesExec {
output_schema,
metric: ExecutionPlanMetricsSet::new(),
properties,
partial_fold,
})
}
@@ -792,7 +903,11 @@ impl DisplayAs for FusedSeriesExec {
/// The query, then the tree it compiles to: the tree is rendered by [`NativeTree`]'s own
/// `Display`, so `EXPLAIN` and the node's metrics name the same nodes.
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
write!(f, "FusedSeriesExec: {}\n{}", self.promql, self.tree)
write!(f, "FusedSeriesExec: {}\n{}", self.promql, self.tree)?;
if let Some(op) = &self.partial_fold {
write!(f, "\npartial state: {}", render_partial_fold(op))?;
}
Ok(())
}
}
@@ -858,13 +973,14 @@ impl ExecutionPlan for FusedSeriesExec {
.collect();
// Rebuilt rather than patched: the new child's schema is what the frame is validated
// against, so a child that changed shape is refused instead of decoded with a stale layout.
Ok(Arc::new(Self::try_new(
Ok(Arc::new(Self::build(
Arc::clone(&self.promql),
children,
Arc::clone(&self.tree),
self.output_schema.clone(),
self.time_column.clone(),
self.tags.to_vec(),
self.partial_fold.clone(),
)?))
}
@@ -910,6 +1026,27 @@ impl ExecutionPlan for FusedSeriesExec {
let input_ids = (0..self.series_schemas.len())
.map(|source| state.input_ids(source).collect())
.collect();
let export_budget = Arc::new(Mutex::new(None));
let partial_fold = self
.partial_fold
.clone()
.map(|op| {
PartialFold::try_new(
op,
self.tree
.root()
.output
.samples()
.ok_or_else(|| {
DataFusionError::Plan("FusedSeries output is not samples".into())
})?
.clone(),
Arc::clone(&self.tags),
Arc::clone(&export_budget),
&context.runtime_env().memory_pool,
)
})
.transpose()?;
Ok(Box::pin(FusedSeriesStream {
inputs: streams,
executor: Some(NativeExecutor::new(state)),
@@ -917,6 +1054,8 @@ impl ExecutionPlan for FusedSeriesExec {
classification: Arc::clone(&self.classification),
tags: Arc::clone(&self.tags),
output_schema: self.output_schema.clone(),
partial_fold,
_export_budget: Arc::clone(&export_budget),
ready: VecDeque::new(),
done: false,
}))
@@ -931,7 +1070,7 @@ impl ExecutionPlan for FusedSeriesExec {
///
/// The time column is the absolute grid positions the chunk carries, missing samples are nulls and
/// ordinary NaN stays a value.
fn series_to_record_batch(
pub(crate) fn series_to_record_batch(
classification: &[OutputColumn],
tags: &[String],
output_schema: &SchemaRef,
@@ -1034,6 +1173,10 @@ pub struct FusedSeriesStream {
tags: Arc<[String]>,
/// The schema of every batch this stream yields.
output_schema: SchemaRef,
/// Per-partition aggregate state fold, if this stream exports a partial result.
partial_fold: Option<PartialFold>,
/// Keeps exported state batches charged for as long as this stream holds them.
_export_budget: Arc<Mutex<Option<MemoryReservation>>>,
/// The batches the executor settled since the last poll of the input.
ready: VecDeque<RecordBatch>,
/// Whether the input ended and everything it settled has been handed out.
@@ -1105,13 +1248,26 @@ impl FusedSeriesStream {
fn fail(&mut self) {
self.done = true;
self.executor = None;
self.partial_fold = None;
self.inputs.clear();
// This reservation belongs only to this execution. Release it even if the consumer keeps
// the failed stream and the plan alive.
self._export_budget
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
// A batch queued before the error was settled by a run that has now stopped.
self.ready.clear();
}
/// Converts the chunks the executor settled into batches, in the order it produced them.
/// Converts settled chunks into query rows or folds them into partial aggregate state.
fn convert(&mut self, chunks: Vec<EvaluatedChunk>) -> DataFusionResult<()> {
if let Some(fold) = self.partial_fold.as_mut() {
for chunk in chunks {
fold.update(chunk)?;
}
return Ok(());
}
for chunk in &chunks {
let batch = series_to_record_batch(
&self.classification,
@@ -1123,6 +1279,14 @@ impl FusedSeriesStream {
}
Ok(())
}
/// Publishes the partition's fold only after the input and native execution have drained.
fn finish_fold(&mut self) -> DataFusionResult<()> {
if let Some(mut fold) = self.partial_fold.take() {
self.ready.extend(fold.finish()?);
}
Ok(())
}
}
impl RecordBatchStream for FusedSeriesStream {
@@ -1157,6 +1321,10 @@ impl Stream for FusedSeriesStream {
}
}
Ok(None) => {
if let Err(error) = this.finish_fold() {
this.fail();
return Poll::Ready(Some(Err(error)));
}
this.done = true;
continue;
}
@@ -73,6 +73,7 @@ use store_api::region_engine::RawLabelSource;
use super::{FusedSeries, FusedSeriesBinding, OutputColumn, POLL_BUDGET, series_to_record_batch};
use crate::evaluated::EvaluatedChunk;
use crate::extension_plan::aggregate_exchange::state_schema;
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
use crate::native::plan::{
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundScalar,
@@ -109,6 +110,8 @@ const TIME: &str = "time";
const VALUE: &str = "value";
const OTHER: &str = "other";
const HOST: &str = "host";
/// A second label, so two partitions can hold distinct prefix series that fold into one group.
const JOB: &str = "job";
const ZONE: &str = "zone";
const NAME: &str = "__name__";
const METRIC: &str = "http_requests_total";
@@ -3033,3 +3036,431 @@ async fn repeated_metrics_reads_register_nothing_and_outlive_the_execution() {
);
}
}
/// One chunk of the series keyed `key`, carrying `labels` and closing when `last`.
///
/// The key and labels are separate so a test can hold two raw series under one label set; different
/// keys make such a pair two series.
fn labelled_chunk(
key: &str,
labels: &[(&str, &str)],
rows: &[(i64, f64)],
last: bool,
) -> RawSeriesChunk {
chunk_of(
&raw_schema(),
key,
metric(labels, Some(METRIC)),
&times_of(rows),
vec![values_of(rows)],
last,
)
}
/// The `by (grouped_by)` aggregate of `kind` that the scope side of a split aggregate exports.
fn partial_op(kind: AggregateKind, grouped_by: &[&str]) -> BoundAggregate {
let labels: Vec<Arc<str>> = grouped_by.iter().map(|label| Arc::from(*label)).collect();
BoundAggregate {
kind,
group: Grouping::By(labels.into()),
stage: AggregateStage::Complete,
}
}
/// The binding of the prefix tree, declaring `tags` as the node's labels.
fn partial_binding_of(tree: &NativeTree, tags: &[&str]) -> FusedSeriesBinding {
binding_of(
tree,
raw_schema(),
tags.iter().map(|tag| (*tag).to_string()).collect(),
)
}
/// The logical node that runs the prefix and exports `kind`'s state, grouped by `host`.
///
/// The prefix's one raw input is bound to source `0`, which is the only child the node carries: a
/// state export is per partition of that one scan, not a second source.
fn partial_node(kind: AggregateKind) -> FusedSeries {
let tree = rate_tree();
let binding = partial_binding_of(&tree, &[HOST]);
FusedSeries::try_new_partial(
Arc::from(PROMQL),
tree,
binding,
vec![input_plan(frame_schema())],
partial_op(kind, &[HOST]),
)
.expect("the binding matches the prefix tree")
}
/// The physical node that runs `tree` and exports `op`'s per-partition state over `input`.
///
/// `tags` are the labels the node declares, which the exported state layout is built from.
fn partial_plan(
tree: NativeTree,
input: Arc<dyn ExecutionPlan>,
op: BoundAggregate,
tags: &[&str],
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
let binding = partial_binding_of(&tree, tags);
FusedSeries::try_new_partial(
Arc::from(PROMQL),
tree,
binding,
vec![input_plan(frame_schema())],
op,
)?
.to_execution_plan(vec![(
input,
RawLabelSource::Explicit,
SeriesOrdering::Contiguous,
)])
}
/// The one state batch a partition exports, with the schema `state`.
async fn state_of(
exec: &Arc<dyn ExecutionPlan>,
partition: usize,
state: &SchemaRef,
) -> RecordBatch {
let context = SessionContext::default().task_ctx();
let batches = exec
.execute(partition, Arc::clone(&context))
.expect("the partition exists")
.try_collect::<Vec<_>>()
.await
.expect("the partition's fold ends");
assert_eq!(
1,
batches.len(),
"one partition exports one state batch: {:?}",
batches
.iter()
.map(RecordBatch::num_rows)
.collect::<Vec<_>>()
);
assert_eq!(state.as_ref(), batches[0].schema().as_ref());
batches.into_iter().next().unwrap()
}
/// The `tag_0` values of one state batch, which are the group's first declared label.
fn group_label(state: &SchemaRef, batch: &RecordBatch) -> Vec<Option<String>> {
batch
.column_by_name(state.field(1).name())
.expect("the state carries the group label")
.as_any()
.downcast_ref::<StringArray>()
.expect("a group label is text")
.iter()
.map(|value| value.map(ToOwned::to_owned))
.collect()
}
/// A partial fold exports one state batch per partition, and two partitions may fold one group.
///
/// The two partitions hold series whose *prefix* labels differ (`host="web-0"` and `host="web-1"`)
/// while the aggregate groups by `job` alone, so both fold into the one group `job="shared"`. That
/// group repeats in the exported state, which is legal because the merge above the exchange collects
/// both partitions' states. The first partition's series also arrives in two chunks, so the fold has
/// to keep what it folded between them.
#[tokio::test]
async fn a_partial_fold_exports_state_from_every_partition() {
let rows = series_samples(1.0);
let first = [(HOST, "web-0"), (JOB, "shared")];
let second = [(HOST, "web-1"), (JOB, "shared")];
let partitions = vec![
frames(&[
labelled_chunk("web-0", &first, &rows[..4], false),
labelled_chunk("web-0", &first, &rows[4..], true),
]),
vec![frame(&labelled_chunk("web-1", &second, &rows, true))],
];
let exec = partial_plan(
rate_tree(),
memory_exec_partitioned(partitions),
partial_op(AggregateKind::Count, &[JOB]),
&[JOB],
)
.expect("a rate tree with a partial count is executable");
assert_eq!(
2,
exec.properties().output_partitioning().partition_count(),
"the node's partition count is its input's"
);
let state = state_schema(&[JOB.to_string()]);
assert_eq!(state, exec.schema(), "the node declares the state layout");
for partition in 0..2 {
let batch = state_of(&exec, partition, &state).await;
assert_eq!(
GRID_LEN as usize,
batch.num_rows(),
"the group has one row per grid point, whichever chunks its series arrived in"
);
assert_eq!(
vec![Some("shared".to_string()); GRID_LEN as usize],
group_label(&state, &batch),
"the exported rows name the group they were folded into"
);
}
}
/// Prefix series of one label set on disjoint grid points are legal in state mode.
///
/// The exported states can be merged above this partition-local fold.
///
/// A window is left-open, `(T - 5m, T]`, so a fragment answers at a grid point only when two of its
/// own samples fall inside that window. The two fragments are spaced for exactly that: the early one
/// answers at 300s alone, the late one at 540s alone, and neither answers where the other does.
#[tokio::test]
async fn disjoint_prefix_points_across_partitions_export_state() {
let labels = [(HOST, "web")];
// Sample `0` would fall outside the left-open window of grid point 300s, so both of these do.
let early = [(SAMPLE_STEP, 60.0), (2 * SAMPLE_STEP, 120.0)];
let late = [(470_000, 470.0), (540_000, 540.0)];
let partitions = vec![
vec![frame(&labelled_chunk("web-0", &labels, &early, true))],
vec![frame(&labelled_chunk("web-1", &labels, &late, true))],
];
let exec = partial_plan(
rate_tree(),
memory_exec_partitioned(partitions),
partial_op(AggregateKind::Sum, &[HOST]),
&[HOST],
)
.expect("a rate tree with a partial sum is executable");
let state = state_schema(&[HOST.to_string()]);
for partition in 0..2 {
let batch = state_of(&exec, partition, &state).await;
assert!(
group_label(&state, &batch)
.iter()
.flatten()
.all(|value| value == "web"),
"each partition's state names the group it folded"
);
}
}
/// Each stream owns its exported-state reservation until that stream ends, even while the plan
/// stays alive and another execution of the same plan still holds its own state.
#[tokio::test]
async fn an_exported_state_batch_stays_charged_until_its_stream_ends() {
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
let context = task_context(&pool);
let exec = partial_plan(
rate_tree(),
memory_exec(vec![frame(&series_chunk(
"web-0",
&series_samples(1.0),
true,
))]),
partial_op(AggregateKind::Sum, &[HOST]),
&[HOST],
)
.expect("a rate tree with a partial sum is executable");
let mut first = exec
.execute(0, Arc::clone(&context))
.expect("the first execution's partition exists");
let mut second = exec
.execute(0, Arc::clone(&context))
.expect("the second execution's partition exists");
let first_batches = (&mut first)
.try_collect::<Vec<_>>()
.await
.expect("the first partition's fold ends");
let second_batches = (&mut second)
.try_collect::<Vec<_>>()
.await
.expect("the second partition's fold ends");
assert_eq!(1, first_batches.len(), "one state batch per execution");
assert_eq!(1, second_batches.len(), "one state batch per execution");
assert!(pool.reserved() > 0, "both exported states are charged");
drop(first);
assert!(
pool.reserved() > 0,
"dropping one stream preserves the other stream's reservation while the plan lives"
);
drop(second);
assert_eq!(
0,
pool.reserved(),
"dropping both streams releases their reservations even though the plan remains alive"
);
assert_eq!(
1,
first_batches.len(),
"the first batches are still the test's"
);
assert_eq!(
1,
second_batches.len(),
"the second batches are still the test's"
);
}
/// A partial node keeps its mode when an optimizer rebuilds it, and another aggregate is another
/// node.
#[test]
fn a_partial_mode_survives_rebuilding_and_is_compared() {
let node = partial_node(AggregateKind::Sum);
assert!(node.partial_fold().is_some(), "the fixture exports state");
let rebuilt = node
.with_exprs_and_inputs(Vec::new(), vec![input_plan(frame_schema())])
.expect("the rebuilt node is legal");
assert!(
matches!(rebuilt.partial_fold(), Some(op) if op.kind == AggregateKind::Sum),
"rebuilding the node dropped the aggregate it exports"
);
assert_eq!(node, rebuilt);
let counted = partial_node(AggregateKind::Count);
assert_ne!(node, counted, "another aggregate is another computation");
assert_ne!(Some(std::cmp::Ordering::Equal), node.partial_cmp(&counted));
}
/// A prefix tree that itself reads across series is refused: every partition would fold a part.
#[test]
fn a_prefix_that_reads_across_series_is_refused() {
let tree = aggregate_tree();
let binding = binding(&tree);
let error = FusedSeries::try_new_partial(
Arc::from(PROMQL),
tree,
binding,
vec![input_plan(frame_schema())],
partial_op(AggregateKind::Sum, &[HOST]),
)
.expect_err("a prefix that folds a group per partition is not a per-series prefix");
assert!(error.to_string().contains("reads across"), "{error}");
}
/// `constant <op> vector`, bound the way the compiler binds a scalar broadcast: the constant on the
/// left, and the vector side's samples as the operation's output.
fn broadcast_left(constant: f64, vector: NativeNode, op: BinaryOp) -> NativeNode {
let grid = vector
.output
.grid()
.expect("a broadcast reads one evaluated vector")
.clone();
let output = vector.output.clone();
NativeNode {
expr: NativeExpr::Binary {
left: Box::new(NativeNode {
expr: NativeExpr::Scalar(BoundScalar { value: constant }),
output: NativeType::Scalar(grid),
}),
right: Box::new(vector),
matching: BinaryMatching {
op,
return_bool: false,
labels: MatchingLabels::Ignoring(Vec::new()),
cardinality: Cardinality::OneToOne,
fill: FillValues::default(),
},
},
output,
}
}
/// A constant broadcast is per-series work, so a partition folds it like any other prefix.
///
/// `max(10 - rate(x[5m]))` over the rates `1` and `2` of the two series below folds `9` and `8` of one
/// group and exports `9`. Reading the constant on the other side exports `-8`, and folding the rate
/// and subtracting the constant above the merge exports `10 - 2 = 8`, so the answer says where the
/// operation ran and which operand its constant was.
#[tokio::test]
async fn a_constant_broadcast_prefix_exports_the_values_the_constant_computes() {
let tree = NativeTree::try_new(broadcast_left(
10.0,
rate_tree().root().clone(),
BinaryOp::Sub,
))
.expect("a broadcast over the rate tree is legal");
let exec = partial_plan(
tree,
memory_exec(two_series_frames()),
partial_op(AggregateKind::Max, &[]),
&[],
)
.expect("a per-series broadcast is a prefix one partition evaluates on its own");
let state = state_schema(&[]);
let batch = state_of(&exec, 0, &state).await;
let values = batch
.column_by_name("value")
.expect("the state carries the accumulator")
.as_any()
.downcast_ref::<Float64Array>()
.expect("an accumulator is Float64");
let values: Vec<Option<f64>> = values.iter().collect();
assert_eq!(
vec![Some(9.0); GRID_LEN as usize],
values,
"every grid point holds `10 - 1`, the larger of the two series' values"
);
}
/// A partial fold that fails after valid input exports no state and releases its reservation.
#[tokio::test]
async fn a_failed_input_exports_no_partial_state() {
let pool = Arc::new(GreedyMemoryPool::new(1 << 20));
let context = task_context(&pool);
let dropped = Arc::new(AtomicBool::new(false));
let schema = frame_schema();
let batches = one_series_frames();
let source = staged(schema.clone(), {
let dropped = Arc::clone(&dropped);
move || {
Box::pin(
StagedStream::new(schema.clone(), batches.clone())
.error("the source failed")
.dropped(&dropped),
)
}
});
let exec = partial_plan(
rate_tree(),
source,
partial_op(AggregateKind::Sum, &[HOST]),
&[HOST],
)
.expect("a rate tree with a partial sum is executable");
assert_eq!(
1,
exec.properties().output_partitioning().partition_count(),
"the node's partition count is its input's"
);
let mut stream = exec
.execute(0, Arc::clone(&context))
.expect("the node executes");
match stream.next().await {
Some(Err(error)) => assert!(
error.to_string().contains("the source failed"),
"reported another error: {error}"
),
other => panic!("a failed input exported state: {other:?}"),
}
assert!(
dropped.load(Ordering::SeqCst),
"the failed stream retains its upstream input"
);
assert_eq!(
0,
pool.reserved(),
"failure releases the prefix fold's reservation while the error stream remains held"
);
drop(stream);
let error = match exec.execute(1, Arc::clone(&context)) {
Ok(_) => panic!("a partition the input does not have is answered"),
Err(error) => error,
};
assert!(
error.to_string().contains("partition"),
"refused for another reason: {error}"
);
}
+9 -2
View File
@@ -24,8 +24,8 @@ use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner};
use table::table::scan::RegionScanExec;
use crate::extension_plan::{
Absent, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate, RangeManipulate,
ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn,
Absent, AggregateFinalize, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate,
RangeManipulate, ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn,
};
pub struct PromExtensionPlanner;
@@ -72,6 +72,13 @@ impl ExtensionPlanner for PromExtensionPlanner {
physical_inputs,
session.config_options().execution.target_partitions,
)
} else if let Some(node) = node.as_any().downcast_ref::<AggregateFinalize>() {
// The merge runs where every partition's state arrives, so its own input is the plan
// that exports them.
let Some(input) = physical_inputs.first() else {
return Ok(None);
};
Ok(Some(node.to_execution_plan(Arc::clone(input))?))
} else {
Ok(None)
}
+14 -4
View File
@@ -360,7 +360,9 @@ pub struct NativeNode {
/// Three kinds do: an `Aggregate` folds every series of its group, a `Binary` pairs two vectors'
/// series by label, and a `Vector` operation (`sort`, `absent`, `topk`, `limitk`,
/// `histogram_quantile`, ...) reorders or reads the whole vector at a grid point. Everything else -
/// an input, a scalar, a selection, a window, a map - answers one series from one series' rows.
/// an input, a scalar, a selection, a window, a map, and a binary operation with a constant on one
/// side, whose broadcast reaches each series the other side answers - answers one series from one
/// series' rows.
///
/// Both a region-side placement and the native route's admission ask this, and they must agree: a
/// tree admitted here but refused there becomes a node the physical layer cannot build, and one
@@ -371,9 +373,17 @@ pub fn reads_across_series(node: &NativeNode) -> bool {
NativeExpr::Instant { input, .. }
| NativeExpr::Window { input, .. }
| NativeExpr::Map { input, .. } => reads_across_series(input),
NativeExpr::Aggregate { .. } | NativeExpr::Binary { .. } | NativeExpr::Vector { .. } => {
true
}
NativeExpr::Binary { left, right, .. } => match (&left.expr, &right.expr) {
// Two constants answer the same value for every series there is, so the operation reads
// none of them; one constant is broadcast over the other side's series unchanged, so what
// the operation reads is what that side reads.
(NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => false,
(NativeExpr::Scalar(_), _) => reads_across_series(right),
(_, NativeExpr::Scalar(_)) => reads_across_series(left),
// Two vectors are matched by label, which pairs series of the whole vector.
(_, _) => true,
},
NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } => true,
}
}
+55
View File
@@ -21,6 +21,7 @@ use datatypes::series::time::{EvalGrid, GridSpec};
use super::{
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar,
BoundVectorOp, BoundWindow, Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType,
reads_across_series,
};
use crate::map::MathOp;
use crate::range_eval::{RangeFunction, RangeWindow};
@@ -760,6 +761,60 @@ fn two_scalars_cannot_produce_a_vector() {
);
}
/// A constant operand is broadcast to each series the other side answers, so such an operation reads
/// one series at a time exactly when that other side does.
///
/// Two vectors are a match over the whole vector, and an aggregate folds a group, so either of them
/// under the constant still reads across series. Two constants answer the same value for every series
/// there is, so they read none.
#[test]
fn a_constant_operand_reads_one_series_at_a_time() {
let shared = grid(0, 60_000, 4);
let vector = || window_on(input(), None, Arc::clone(&shared));
let binary = |left: NativeNode, right: NativeNode| NativeNode {
expr: NativeExpr::Binary {
left: Box::new(left),
right: Box::new(right),
matching: add(),
},
output: vector().output,
};
let aggregate = NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(vector()),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Grouping::By(Arc::new(["job".into()])),
stage: AggregateStage::Complete,
},
},
output: evaluated(Arc::new([]), Arc::clone(&shared)),
};
// `100 - rate(v0[5m])`, and the same constant written on the other side.
for node in [
binary(scalar_on(100.0, Arc::clone(&shared)), vector()),
binary(vector(), scalar_on(100.0, Arc::clone(&shared))),
] {
assert!(
!reads_across_series(&node),
"a broadcast reaches each series the vector side answers: {node:?}"
);
}
// `sum(rate(v0[5m])) + 100` folds a group first, so the constant is broadcast to each group.
assert!(reads_across_series(&binary(
aggregate,
scalar_on(100.0, Arc::clone(&shared))
)));
// `rate(v0[5m]) + rate(v0[5m])` matches two vectors by label.
assert!(reads_across_series(&binary(vector(), vector())));
// `1 + 2` answers one value for every series there is.
assert!(!reads_across_series(&binary(
scalar_on(1.0, Arc::clone(&shared)),
scalar_on(2.0, Arc::clone(&shared))
)));
}
/// A binary operation is point-wise on a grid, so a side of raw samples has no positions to line
/// up with the other side.
#[test]
+45 -6
View File
@@ -37,7 +37,7 @@ use datafusion_optimizer::push_down_filter::PushDownFilter;
use datafusion_optimizer::rewrite_set_comparison::RewriteSetComparison;
use datafusion_optimizer::scalar_subquery_to_join::ScalarSubqueryToJoin;
use datafusion_optimizer::simplify_expressions::SimplifyExpressions;
use promql::extension_plan::{FusedSeries, SeriesDivide};
use promql::extension_plan::{AggregateFinalize, FusedSeries, SeriesDivide};
use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
use table::metadata::TableType;
use table::table::adapter::DfTableProviderAdapter;
@@ -115,8 +115,9 @@ pub struct DistPlannerAnalyzer {
///
/// A region input normally has to be encoded to Substrait before it can leave the frontend, and
/// [`PlanRewriter::should_expand`] cuts the plan at the first node that does not encode. In
/// process, a root `FusedSeries` plan travels as a `LogicalPlan` instead and skips that gate;
/// other plans retain the ordinary encoding checks.
/// process, a native fused plan (a `FusedSeries` node, or the `AggregateFinalize` merge over one)
/// travels as a `LogicalPlan` instead and skips that gate; other plans retain the ordinary
/// encoding checks.
///
/// Whoever builds the query engine sets this, once, from the transport it wired. It is neither a
/// query-time decision nor a property of a region.
@@ -449,7 +450,8 @@ struct PlanRewriter {
/// Used for the ordinary standalone fast path when the root plan is encodable. It is not
/// needed when the root itself is the in-process `FusedSeries` exception.
whole_plan_encodable: bool,
/// In-process transport skips the encodability gate only when the rewritten root itself is FusedSeries.
/// In-process transport skips the encodability gate only when the rewritten root is the native
/// route's whole plan: a `FusedSeries` node, or the `AggregateFinalize` merge of one's state.
skip_encodability_gate: bool,
/// Current level in the tree
level: usize,
@@ -528,16 +530,53 @@ fn is_fused_series_plan(plan: &LogicalPlan) -> bool {
matches!(plan, LogicalPlan::Extension(extension) if extension.node.as_any().is::<FusedSeries>())
}
/// Whether `plan` is the native route's whole plan: a `FusedSeries` node over its scan, or the
/// `AggregateFinalize` merge of exactly such a node's partition-local state.
///
/// The merge is the one shape that puts a node above the fused producer: it runs on the frontend over
/// the state every partition exports, and the producer below it still reads its own scan. Every other
/// plan keeps the ordinary encoding checks.
///
/// The producer is checked by what it exports, not only by its node kind: a `FusedSeries` that
/// answers with computed values is not a merge input, and merging those values as if they were
/// partitions' contributions would report one partition's answer as the whole group's. The check is
/// not implied by the constructor either — `with_exprs_and_inputs` hands a node whatever input an
/// optimizer rebuilt, so a merge can hold a replacement producer its own constructor never saw.
fn is_in_process_plan(plan: &LogicalPlan) -> bool {
if is_fused_series_plan(plan) {
return true;
}
let LogicalPlan::Extension(extension) = plan else {
return false;
};
if !extension.node.as_any().is::<AggregateFinalize>() {
return false;
}
// The merge's own child, as this rewrite walks it: the producer over its scan.
let inputs = extension.node.inputs();
let [LogicalPlan::Extension(partial)] = inputs.as_slice() else {
return false;
};
let Some(fused) = partial.node.as_any().downcast_ref::<FusedSeries>() else {
return false;
};
fused.partial_fold().is_some()
&& matches!(
partial.node.inputs().as_slice(),
[LogicalPlan::TableScan(_)]
)
}
impl PlanRewriter {
/// `plan` must be the root of the tree that is about to be rewritten, otherwise
/// [`PlanRewriter::should_expand`] may skip a check it has to perform.
fn new(plan: &LogicalPlan, in_process_region_transport: bool) -> Self {
// An `Explain` wrapper describes the plan below it, which is the route's root here.
let native_root = match plan {
LogicalPlan::Analyze(analyze) => analyze.input.as_ref(),
_ => plan,
};
let skip_encodability_gate =
in_process_region_transport && is_fused_series_plan(native_root);
let skip_encodability_gate = in_process_region_transport && is_in_process_plan(native_root);
Self {
// Preserve the ordinary whole-plan fast path unless this is the in-process root
// exception: no node in that tree needs an encoding check.
+202 -2
View File
@@ -21,7 +21,8 @@ use datafusion::error::Result as DfResult;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
use promql::extension_plan::{
EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize,
AggregateFinalize, EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide,
SeriesNormalize,
};
use promql::native::plan::reads_across_series;
use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
@@ -274,6 +275,9 @@ impl Categorizer {
// execution. It is not a claim that matching is globally commutative across regions.
Commutativity::Commutative
}
// The merge reads every partition's state, so it cannot run in one of them: a region
// would merge the state its own scan produced and report that as the whole group.
name if name == AggregateFinalize::name() => Commutativity::NonCommutative,
name if name == SeriesNormalize::name()
|| name == InstantManipulate::name()
|| name == RangeManipulate::name() =>
@@ -399,7 +403,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::{AggregateFinalize, FusedSeries, FusedSeriesBinding};
use promql::functions::{
NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile,
};
@@ -955,6 +959,202 @@ mod tests {
);
}
/// A split aggregate's merge, over a scan and bound to `sum(some_metric)`.
///
/// The tree is the compiler's own, so the two halves this plan is built from are the ones a query
/// plans: the aggregate is split out of it, and the producer below the merge runs the per-series
/// prefix.
fn aggregate_finalize_plan(input: LogicalPlan) -> LogicalPlan {
let stmt = promql_parser::parser::EvalStmt {
expr: parser::parse("sum(some_metric)").unwrap(),
..native_statement()
};
let series_schema = Arc::new(SeriesSchema {
fields: Arc::from([FieldSpec { name: "v0".into() }]),
eval_grid: None,
});
let tree = compile(
&stmt,
Arc::clone(&series_schema),
SeriesOrdering::KeyThenTime,
)
.unwrap();
let binding = FusedSeriesBinding {
grid: statement_grid(&stmt).unwrap(),
metric_name: Some(Arc::from("some_metric")),
time_index: "ts".to_string(),
tags: Vec::new(),
};
let output_schema: DFSchemaRef = Arc::new(
DFSchema::new_with_metadata(
vec![
(
None,
Arc::new(Field::new(
"ts",
ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
false,
)),
),
(
None,
Arc::new(Field::new("sum(v0)", ArrowDataType::Float64, true)),
),
],
Default::default(),
)
.unwrap(),
);
LogicalPlan::Extension(Extension {
node: Arc::new(
AggregateFinalize::try_new(
Arc::from("sum(some_metric)"),
tree,
binding,
input,
output_schema,
)
.unwrap(),
),
})
}
fn as_aggregate_finalize(plan: &LogicalPlan) -> Option<&AggregateFinalize> {
if let LogicalPlan::Extension(extension) = plan {
extension.node.as_any().downcast_ref::<AggregateFinalize>()
} else {
None
}
}
/// The first fused producer in `plan`'s visible tree.
fn first_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> {
if let LogicalPlan::Extension(extension) = plan
&& let Some(fused) = extension.node.as_any().downcast_ref::<FusedSeries>()
{
return Some(fused);
}
plan.inputs().into_iter().find_map(first_fused_series)
}
/// The merge reads every partition's state, so it cannot run in one of them.
#[test]
fn a_split_aggregate_is_not_commutative() {
let plan = aggregate_finalize_plan(table_scan_plan());
assert!(matches!(
Categorizer::check_plan(&plan, None).unwrap(),
Commutativity::NonCommutative
));
}
/// The merge stays on the frontend and the producer rides inside the merge scan, so the plan a
/// region is handed is exactly the per-series prefix over its own scan.
///
/// Over the wire nothing changes: the merge has no serializer branch either, so the boundary is
/// still drawn at the producer, which is the same place the existing route draws it.
#[test]
fn a_split_aggregate_merges_above_the_region_only_in_process() {
let plan = aggregate_finalize_plan(table_scan_plan());
assert!(
DFLogicalSubstraitConvertor
.encode(&plan, DefaultSerializer)
.is_err(),
"the merge encodes now, so the encoding gate decides nothing"
);
let in_process = analyze(DistPlannerAnalyzer::new(true), plan.clone());
assert!(
as_aggregate_finalize(&in_process).is_some(),
"the merge must stay on the frontend: {in_process}"
);
let inputs = in_process.inputs();
let [child] = inputs.as_slice() else {
panic!("expected the merge to keep one input in: {in_process}");
};
// `expand` keeps a projection over the merge scan to restore the schema of what it wrapped,
// so the boundary is the first merge scan under the child.
let merge_scan = first_merge_scan(child)
.unwrap_or_else(|| panic!("expected a merge scan below the merge in: {in_process}"));
let producer = first_fused_series(merge_scan.input()).unwrap_or_else(|| {
panic!("expected the producer in the region input of: {in_process}")
});
assert!(
producer.partial_fold().is_some(),
"the region input exports state, not values"
);
assert!(
holds_table_scan(merge_scan.input()),
"the producer still reads its own scan in: {in_process}"
);
// Over the wire the plan has to encode, so the boundary is drawn at the producer.
let encoded = analyze(DistPlannerAnalyzer::new(false), plan);
assert!(
!any_remote_input_holds(&encoded, holds_fused_series),
"the analyzer placed the producer although its plan has to encode: {encoded}"
);
}
/// The merge of `plan`, with its partition-local producer replaced by `producer`.
///
/// A swap like this is what a node has to tolerate: `with_exprs_and_inputs` rebuilds it from
/// whatever input an optimizer holds, so the analyzer cannot take a merge over a fused node to be
/// the one `AggregateFinalize::try_new` built.
fn merge_over(plan: LogicalPlan, producer: LogicalPlan) -> LogicalPlan {
let LogicalPlan::Extension(extension) = &plan else {
panic!("a split aggregate is an extension node: {plan}");
};
let finalize = extension
.node
.as_any()
.downcast_ref::<AggregateFinalize>()
.expect("a split aggregate is a merge");
// Qualified: both `UserDefinedLogicalNode` and `UserDefinedLogicalNodeCore` declare this
// method, and only the latter's answer is the node itself.
let swapped =
UserDefinedLogicalNodeCore::with_exprs_and_inputs(finalize, Vec::new(), vec![producer])
.expect("a merge holds the one input it is given");
LogicalPlan::Extension(Extension {
node: Arc::new(swapped),
})
}
/// The in-process exception admits the split the route builds, not the shape it looks like: a
/// merge whose child is an ordinary `FusedSeries` - one that answers with computed values - over
/// the same scan is refused the exception, so the encoding gate still draws the boundary at the
/// scan and the merge stays on the frontend.
///
/// Skipping the gate for it would let a region's values be merged as if they were that
/// partition's contribution to the group, which is the shape no constructor check can rule out:
/// `with_exprs_and_inputs` accepts the replacement.
#[test]
fn a_merge_over_an_ordinary_fused_series_keeps_the_encoding_gate() {
let scan = table_scan_plan();
let split = aggregate_finalize_plan(scan.clone());
// The control: the split's own producer exports state, so it is the shape the exception
// admits and it does ride into the region.
let producer_placed = analyze(DistPlannerAnalyzer::new(true), split.clone());
assert!(
any_remote_input_holds(&producer_placed, holds_fused_series),
"the split's partial producer rides inside the merge scan: {producer_placed}"
);
// The same merge over the same scan, with a producer that answers with values.
let values = fused_series_plan(scan);
let swapped = merge_over(split, values);
let analyzed = analyze(DistPlannerAnalyzer::new(true), swapped);
assert!(
!any_remote_input_holds(&analyzed, holds_fused_series),
"an ordinary fused node exports no state, so the exception does not apply: {analyzed}"
);
assert!(
any_remote_input_holds(&analyzed, holds_table_scan),
"the region still reads the scan the producer reads: {analyzed}"
);
}
/// Skipping the encoding gate removes one reason to expand and adds none: a node that does not
/// encode for its own reasons, and that the categorizer refuses, still draws the boundary at
/// itself when regions are reached in process.
+8 -3
View File
@@ -342,10 +342,12 @@ impl PromPlanner {
// a range function and the math functions over it into one tree: offered any later, the
// expression has already been split into the nodes those functions would have shared. A
// shape it does not accept is planned by the existing path exactly as if it were not here.
if let Some(plan) = planner.try_plan_native_fused(&stmt.expr).await? {
if let Some(plan) = planner
.try_plan_native_fused(&stmt.expr, query_engine_state)
.await?
{
return planner.strip_tsid_column(plan);
}
let plan = planner
.prom_root_expr_to_plan(&stmt.expr, query_engine_state)
.await?;
@@ -2426,7 +2428,10 @@ impl PromPlanner {
ANALYZE_NODE_NAME
| ANALYZE_VERBOSE_NODE_NAME
| EXPLAIN_NODE_NAME
| EXPLAIN_VERBOSE_NODE_NAME => self.try_plan_native_fused(&children[0]).await?,
| EXPLAIN_VERBOSE_NODE_NAME => {
self.try_plan_native_fused(&children[0], query_engine_state)
.await?
}
_ => None,
};
let plan = match native_plan {
+135 -30
View File
@@ -14,12 +14,14 @@
//! The native fused-series route of the PromQL planner.
//!
//! [`PromPlanner::try_plan_native_fused`] offers a small experimental subset to the native
//! compiler: a vector selector (optionally parenthesized), or nested unary `rate`, `increase`,
//! `sum_over_time`, and `abs` calls over a selector, plus a one-to-one arithmetic match between two
//! such operands from the same ordinary Mito table. It replaces that expression with one
//! [`FusedSeries`] node, retaining a separate scan for each selector occurrence. Other expression
//! shapes keep the existing planner's route.
//! [`PromPlanner::try_plan_native_fused`] offers a whole statement expression to the native
//! compiler and, when the compiler accepts it, replaces everything the existing path would plan
//! below the root with one [`FusedSeries`] node over the selector's own table scan. A tree that
//! folds across series - an aggregate - is split instead: its per-series prefix runs in a
//! `FusedSeries` producer and an [`AggregateFinalize`] merges the state every partition exports,
//! because a region holds only part of a group. Declining is 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
@@ -41,7 +43,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};
use promql::extension_plan::{AggregateFinalize, FusedSeries, FusedSeriesBinding};
use promql::native::plan::{NativeExpr, NativeNode, reads_across_series};
use promql::vector_match::{Cardinality, MatchingLabels};
use promql_parser::label::Matchers;
@@ -56,6 +58,7 @@ use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_E
use crate::promql::error::{DataFusionPlanningSnafu, Result};
use crate::promql::native_compile::{compile_selectors, statement_grid};
use crate::promql::planner::PromPlanner;
use crate::query_engine::QueryEngineState;
/// The query-context key that turns the native fused-series route on for one query.
///
@@ -103,20 +106,28 @@ type PreparedInput = (
);
impl PromPlanner {
/// Plans `prom_expr` as one [`FusedSeries`] node, or returns `None` to keep the existing plan.
/// Plans `prom_expr` as one native node, or returns `None` to keep the existing plan.
///
/// The route is offered the whole expression so its tree computes the requested expression
/// over the planner's resolved selector context: table name, time index, tag columns, and
/// field columns (after any `__field__` matcher). These are the raw series schema the input
/// tree is compiled against.
/// `query_engine_state` is only read to build the *existing* plan of an aggregate query, whose
/// column names and grouped labels are what the rows of a split aggregate are named after. That
/// plan is built for its schema, its names are copied, and it is dropped: it is never executed
/// and never stored, so the batch that answers the query is the native route's own.
///
/// `None` is not a failure: unsupported shapes and queries this route cannot bind faithfully
/// continue through the existing planner. Admission is limited to selectors, the unary calls
/// named above, and a same-table one-to-one arithmetic pair, with the scan, schema, matcher,
/// and grid constraints checked below.
/// The route is offered a whole expression because the compiler folds a range function and the
/// math functions over it into one tree: offering a sub-expression instead would compile a tree
/// that computes something the reader did not write. Everything else about the node comes from
/// the planner's resolved selector context: the table name, the time index column, the tag
/// columns and the field columns, which are exactly the raw series schema the tree's input
/// has to be compiled against. Selectors with a `__field__` matcher keep legacy planning.
///
/// `None` is not a failure. It says this query cannot take the route unchanged, and the caller
/// plans it with the existing planner as if this method did not exist. The aggregate split only
/// admits shapes the split can carry; other vector-wide operations, subqueries, alternative
/// matchers, and unbindable scans keep existing planning.
pub(super) async fn try_plan_native_fused(
&mut self,
prom_expr: &PromExpr,
query_engine_state: &QueryEngineState,
) -> Result<Option<LogicalPlan>> {
if !self.native_fused {
return Ok(None);
@@ -138,7 +149,7 @@ impl PromPlanner {
}
// Preserve the original single-selector admission allowlist. Broader binary syntax is only
// considered for a two-occurrence root, where the compiled-tree proof below constrains it.
if selectors.len() == 1 && admitted_selector(prom_expr).is_none() {
if selectors.len() == 1 && !admitted_single_selector(prom_expr) {
return Ok(None);
}
let Some(stmt) = self.native_statement(prom_expr) else {
@@ -431,13 +442,49 @@ impl PromPlanner {
.into_iter()
.map(|(scan, _, _, _, _)| scan)
.collect::<Vec<_>>();
// A tree run once per region must be point-wise over a series. Binary matches between two
// series are supported only for the narrowly admitted one-to-one root pair.
// Ordinary pointwise trees and the existing two-occurrence same-source route keep their
// current admission unchanged. Aggregate splits are restricted to one raw scan child.
let root = compiled.tree.root();
if reads_across_series(root)
&& !(pointwise_operand(root) || (selectors.len() == 2 && independent_scan_pair(root)))
{
return Ok(None);
let per_partition = !reads_across_series(root)
|| pointwise_operand(root)
|| (selectors.len() == 2 && independent_scan_pair(root));
if !per_partition {
if selectors.len() != 1
|| !AggregateFinalize::can_split(&compiled.tree, &series_schema.fields, &time)
{
return Ok(None);
}
let saved = self.ctx.clone();
let planned = self
.prom_root_expr_to_plan(prom_expr, query_engine_state)
.await;
let legacy_fields = self.ctx.field_columns.clone();
let legacy_tags = self.ctx.tag_columns.clone();
self.ctx = saved;
drop(planned?);
let output_schema = fused_output_schema(&legacy_fields, &legacy_tags, &time)?;
let Some(rawinput) = children.into_iter().next() else {
return Ok(None);
};
let node = match AggregateFinalize::try_new(
Arc::from(prom_expr.to_string()),
compiled.tree,
FusedSeriesBinding {
grid,
time_index: time,
tags,
metric_name: metric,
},
rawinput,
output_schema,
) {
Ok(node) => node,
Err(DataFusionError::NotImplemented(_)) => return Ok(None),
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
};
return Ok(Some(LogicalPlan::Extension(Extension {
node: Arc::new(node),
})));
}
let tree = compiled.tree;
let root_fields = tree
@@ -664,7 +711,24 @@ pub(crate) fn pointwise_operand(node: &NativeNode) -> bool {
}
}
/// The single-selector route is limited to a selector or supported unary calls over one selector.
/// Whether a single-selector expression belongs to the native route's existing selector allowlist
/// or is an aggregate expression handled by the aggregate split.
fn admitted_single_selector(expr: &PromExpr) -> bool {
fn aggregate(expr: &PromExpr) -> bool {
match expr {
PromExpr::Aggregate(_aggregate) => true,
PromExpr::Paren(paren) => aggregate(&paren.expr),
PromExpr::Unary(unary) => aggregate(&unary.expr),
PromExpr::Binary(binary) => aggregate(&binary.lhs) || aggregate(&binary.rhs),
PromExpr::Call(call) => call.args.args.iter().any(|arg| aggregate(arg)),
_ => false,
}
}
admitted_selector(expr).is_some() || aggregate(expr)
}
/// The existing selector allowlist: a selector or supported unary calls over one selector.
fn admitted_selector(expr: &PromExpr) -> Option<&VectorSelector> {
match expr {
PromExpr::VectorSelector(selector) => Some(selector),
@@ -682,7 +746,6 @@ fn admitted_selector(expr: &PromExpr) -> Option<&VectorSelector> {
}
}
/// Collect selector occurrences in compiler binding order; reject unsupported expression shapes.
fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>) -> bool {
match expr {
PromExpr::VectorSelector(selector) => out.push(selector),
@@ -701,7 +764,20 @@ fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>)
}
// Literals are permitted only as compiler-recognized broadcasts in a bounded binary tree.
PromExpr::NumberLiteral(_) => return true,
_ => return false,
PromExpr::Unary(unary) => return collect_selectors(&unary.expr, out),
PromExpr::Call(call) => {
if matches!(call.func.name, "label_replace" | "label_join") {
return false;
}
for arg in &call.args.args {
if !collect_selectors(arg, out) {
return false;
}
}
}
PromExpr::Aggregate(aggregate) => return collect_selectors(&aggregate.expr, out),
PromExpr::Subquery(_) => return false,
_ => {}
}
true
}
@@ -748,6 +824,7 @@ fn metric_scan_and_table_id(
Some((scan.clone(), filter.predicate.clone()))
}
/// Whether `expr` calls `rate`/`increase` anywhere in its admitted expression tree.
fn calls_rate_or_increase(expr: &PromExpr) -> bool {
match expr {
PromExpr::Call(call) => {
@@ -759,6 +836,7 @@ fn calls_rate_or_increase(expr: &PromExpr) -> bool {
calls_rate_or_increase(&binary.lhs) || calls_rate_or_increase(&binary.rhs)
}
PromExpr::Unary(unary) => calls_rate_or_increase(&unary.expr),
PromExpr::Aggregate(aggregate) => calls_rate_or_increase(&aggregate.expr),
_ => false,
}
}
@@ -767,17 +845,17 @@ fn calls_rate_or_increase(expr: &PromExpr) -> bool {
mod tests {
use std::sync::Arc;
use session::context::QueryContextBuilder;
use std::time::{Duration, UNIX_EPOCH};
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::{FieldSpec, SeriesSchema};
use promql::native::plan::{NativeExpr, NativeNode, NativeTree};
use session::context::QueryContextBuilder;
use super::{
NATIVE_PROMQL_EXTENSION_KEY, admitted_selector, fused_output_tags, independent_scan_pair,
native_promql_requested, scan_time_filter,
NATIVE_PROMQL_EXTENSION_KEY, admitted_selector, admitted_single_selector,
collect_selectors, fused_output_tags, independent_scan_pair, native_promql_requested,
scan_time_filter,
};
fn compiled_test_tree(query: &str) -> NativeTree {
@@ -823,6 +901,29 @@ mod tests {
sources
}
/// The selectors `query` names, in the order the compiler binds them.
fn collected_selectors(query: &str) -> Vec<String> {
let expr = promql_parser::parser::parse(query).expect("the query parses");
let mut selectors = Vec::new();
assert!(collect_selectors(&expr, &mut selectors));
selectors
.iter()
.map(|selector| selector.name.clone().unwrap_or_default())
.collect()
}
#[test]
fn collect_selectors_descends_into_aggregate_inputs() {
for query in [
"sum(x)",
"sum by (job) (x)",
"sum without (instance) (rate(x[5m]))",
] {
assert_eq!(collected_selectors(query), vec!["x"], "{query}");
}
}
/// The compiler retains both source indices for independent selector occurrences.
#[test]
fn independent_scan_pair_keeps_both_numbered_occurrences() {
for query in [
@@ -866,6 +967,10 @@ mod tests {
let expression = promql_parser::parser::parse(query).unwrap();
assert!(admitted_selector(&expression).is_some(), "{query}");
}
for query in ["sum(x)", "sum by (job) (rate(x[5m]))"] {
let expression = promql_parser::parser::parse(query).unwrap();
assert!(admitted_single_selector(&expression), "{query}");
}
}
#[test]
+281 -2
View File
@@ -42,7 +42,7 @@ use datafusion::logical_expr::{Extension, UserDefinedLogicalNodeCore, col};
use datatypes::prelude::ConcreteDataType;
use datatypes::schema::{ColumnSchema, Schema};
use datatypes::series::SeriesOrdering;
use promql::extension_plan::{FusedSeries, HistogramFold};
use promql::extension_plan::{AggregateFinalize, FusedSeries, HistogramFold};
use promql::native::plan::NativeExpr;
use promql_parser::label::Labels;
use promql_parser::parser;
@@ -2301,6 +2301,10 @@ async fn native_fused_delta_temporality_rates_fall_back() {
"abs(rate(some_metric[5m]))",
"abs(increase(some_metric[5m]))",
"(rate(some_metric[5m]))",
// An aggregate is admitted by descending into its input, so the guard has to see a
// `rate`/`increase` under one: the split would fold counters a delta series does not have.
"sum(rate(some_metric[5m]))",
"sum(increase(some_metric[5m]))",
] {
let marked = build_native_fused_plan_with_provider(
query,
@@ -2378,7 +2382,6 @@ async fn native_fused_whole_vector_operation_falls_back() {
#[tokio::test]
async fn native_fused_unsupported_shape_falls_back() {
for query in [
"sum(rate(some_metric[5m]))",
"sum_over_time(rate(some_metric[5m])[1h:])",
"histogram_count(some_metric)",
"ceil(some_metric)",
@@ -2483,6 +2486,235 @@ async fn native_fused_binary_keeps_independent_scan_occurrences() {
}
}
/// The merge half of a split aggregate, when the plan is one.
fn find_aggregate_finalize(plan: &LogicalPlan) -> Option<&AggregateFinalize> {
if let LogicalPlan::Extension(Extension { node }) = plan
&& let Some(finalize) = node.as_any().downcast_ref::<AggregateFinalize>()
{
return Some(finalize);
}
plan.inputs().into_iter().find_map(find_aggregate_finalize)
}
/// The producer below a split aggregate, which exports the state one partition folded.
fn partial_producer(finalize: &AggregateFinalize) -> &FusedSeries {
// Bound to a local first: the slice handed out by `inputs` borrows this list.
let inputs = UserDefinedLogicalNodeCore::inputs(finalize);
let [LogicalPlan::Extension(Extension { node })] = inputs.as_slice() else {
panic!("the merge should read one producer: {finalize:?}");
};
let fused = node
.as_any()
.downcast_ref::<FusedSeries>()
.expect("the producer is a fused series node");
assert!(
fused.partial_fold().is_some(),
"the producer below a merge exports state"
);
fused
}
/// The column names of a plan, sorted: the two routes may order the same columns differently, and
/// what has to agree is which columns a result carries.
fn sorted_column_names(plan: &LogicalPlan) -> Vec<String> {
let mut names = plan
.schema()
.fields()
.iter()
.map(|field| field.name().clone())
.collect::<Vec<_>>();
names.sort();
names
}
/// An aggregate is split: the merge stays on the frontend and the per-series prefix runs in the
/// producer, which is the one shape a region can evaluate on its own. The rows carry the columns the
/// existing plan carries - names, tags and time - which is what keeps the result readable whichever
/// route answered it.
#[tokio::test]
async fn native_fused_aggregate_splits_into_a_merge_over_a_partial_producer() {
for query in [
"sum(some_metric)",
"avg(some_metric)",
"count(some_metric)",
"min(some_metric)",
"max(some_metric)",
"group(some_metric)",
"stddev(some_metric)",
"stdvar(some_metric)",
"sum by (tag_0) (rate(some_metric[5m]))",
"sum without (tag_0) (some_metric)",
"sum(rate(some_metric[5m]))",
"ceil(sum(some_metric))",
"sum(avg(some_metric) by (tag_0))",
// A literal scalar on either side of the fold. Below the aggregate it is part of the prefix,
// which is the half that computes the values the state folds; above it the merge rebuilds
// the operation over the merged values, in the order the query wrote the operands. A
// negation is the same broadcast with `-1` where the minus was.
"sum(8 * rate(some_metric[5m]))",
"max(10 - rate(some_metric[5m]))",
"100 - avg(rate(some_metric[5m]))",
"sum(some_metric) * 2",
"100 / sum(some_metric)",
"-sum(some_metric)",
// A map between the two: the constant is broadcast over a map above the fold, so the prefix
// stays the selection and the suffix is `abs` over the merged value, then the multiply.
"abs(sum(some_metric)) * 2",
] {
let plan = build_native_fused_plan(query, true).await;
let legacy = build_native_fused_plan(query, false).await;
let display = plan.display_indent().to_string();
assert!(
display.contains("AggregateFinalize: "),
"`{query}`: {display}"
);
assert!(display.contains("[partial "), "`{query}`: {display}");
assert!(display.contains("TableScan: some_metric"), "{display}");
let finalize = find_aggregate_finalize(&plan).expect("the statement plans to a merge");
let producer = partial_producer(finalize);
// The prefix is the per-series tree; the aggregate itself is not in it.
assert!(
!producer.tree().to_string().contains("Aggregate"),
"`{query}`: {}",
producer.tree()
);
assert_eq!(
sorted_column_names(&legacy),
sorted_column_names(&plan),
"`{query}` must report the columns the existing plan reports"
);
}
}
/// Only the innermost aggregate is cut out: everything above it, a map included, runs in the suffix
/// over the merged values.
#[tokio::test]
async fn native_fused_nested_aggregate_splits_at_the_innermost_aggregate() {
for (query, merge, partial) in [
(
"sum(avg(some_metric) by (tag_0))",
r#"AggregateFinalize: sum(avg by (tag_0) (some_metric)) [Avg By(["tag_0"]) Complete]"#,
"[partial avg by (tag_0) Complete]",
),
(
"ceil(sum(rate(some_metric[5m])) by (tag_0))",
r#"AggregateFinalize: ceil(sum by (tag_0) (rate(some_metric[5m]))) [Sum By(["tag_0"]) Complete]"#,
"[partial sum by (tag_0) Complete]",
),
] {
let plan = build_native_fused_plan(query, true).await;
let display = plan.display_indent().to_string();
assert!(display.contains(merge), "{display}");
assert!(display.contains(partial), "{display}");
let finalize = find_aggregate_finalize(&plan).expect("the statement plans to a merge");
let producer = partial_producer(finalize);
// A map above the merge leaves the prefix alone, and so does the outer aggregate.
let prefix = producer.tree().to_string();
assert!(!prefix.contains("Map"), "{query}: {prefix}");
assert!(!prefix.contains("Aggregate"), "{query}: {prefix}");
}
}
/// A nested aggregate's outer names are the existing plan's: `sum(avg(x))` reports the outer `sum`.
#[tokio::test]
async fn native_fused_nested_aggregate_keeps_the_outer_names() {
let query = "sum(avg(some_metric) by (tag_0))";
let plan = build_native_fused_plan(query, true).await;
let legacy = build_native_fused_plan(query, false).await;
assert_eq!(sorted_column_names(&legacy), sorted_column_names(&plan));
// The merged value enters the suffix, so no column is named after the inner aggregate.
assert!(
plan.schema()
.fields()
.iter()
.all(|field| !field.name().starts_with("avg(")),
"{:?}",
sorted_column_names(&plan)
);
}
/// A shape the split cannot keep correct keeps the existing plan: a quantile's state is the group's
/// samples, a binary operation whose sibling is data would match one side's series before the merge,
/// a sibling a call computes has no native node at all, and a group by a value field cannot be named
/// by the state rows. A literal scalar sibling is not one of them: the operation is computed per
/// series below the fold, or rebuilt over the merged values above it.
#[tokio::test]
async fn native_fused_unsplittable_aggregate_falls_back() {
for query in [
"quantile(0.5, some_metric)",
"sum(quantile(0.5, some_metric))",
// The sibling is data rather than a literal scalar, so the operation would pair each series
// with the aggregate's series before the merge.
"sum(some_metric) / some_metric",
// A scalar a call computes is not a literal the split could keep: `scalar(...)` has no
// native node, so the statement keeps the existing plan.
"sum(some_metric) / scalar(some_metric)",
"sum by (field_0) (some_metric)",
] {
let native = build_native_fused_plan(query, true).await;
let without_flag = build_native_fused_plan(query, false).await;
assert!(find_fused_series(&native).is_none(), "`{query}`");
assert!(find_aggregate_finalize(&native).is_none(), "`{query}`");
assert_eq!(
native.display_indent().to_string(),
without_flag.display_indent().to_string(),
"`{query}` must keep the existing plan"
);
}
}
/// `clamp` is not a function the existing planner has a kernel for, so an aggregate over it fails
/// while the legacy plan is being built - before either route is chosen, and the same way on both.
///
/// The native route only reads the legacy plan's column names, which means it inherits that refusal
/// rather than answering a query the existing path would reject. Both the split template
/// (`clamp(x, 1, 2)`) and the empty range (`clamp(x, 2, 1)`) fail here, so neither is claimed as
/// supported.
#[tokio::test]
async fn native_fused_clamp_aggregate_keeps_the_existing_error() {
for query in [
"sum(clamp(some_metric, 1, 2))",
"sum(clamp(some_metric, 2, 1))",
] {
for native_fused in [true, false] {
// Each attempt needs its own provider: planning moves the one it is given.
let table_provider = build_test_table_provider_with_options(
&[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())],
1,
1,
vec![],
ConcreteDataType::timestamp_millisecond_datatype(),
false,
ConcreteDataType::float64_datatype(),
NATIVE_ENGINE,
)
.await;
let eval_stmt = build_eval_stmt(query);
let error = PromPlanner::stmt_to_plan_with_annotations(
table_provider,
&eval_stmt,
&build_query_engine_state(),
None,
native_fused,
)
.await
.unwrap_err();
assert!(
matches!(
&error,
crate::promql::error::Error::UnsupportedExpr { name, .. } if name == "clamp"
),
"`{query}` with the flag {native_fused}: {error}"
);
}
}
}
/// A label rewrite stays on the existing plan, which is the one that projects its new label.
///
/// The native node's output schema is the table's own time index, fields and tags, so a tree that
@@ -2518,6 +2750,53 @@ async fn native_fused_label_rewrites_keep_legacy_output_labels() {
}
}
#[tokio::test]
async fn native_fused_preparation_decline_preserves_legacy_plan() {
let query = "absent(vector(1)) + on(tag_0) some_metric{tag_0=\"x\",__field__=\"field_0\"}";
let native = build_native_fused_plan(query, true).await;
let legacy = build_native_fused_plan(query, false).await;
assert!(!native.display_indent().to_string().contains("FusedSeries"));
assert_eq!(
native.display_indent_schema().to_string(),
legacy.display_indent_schema().to_string(),
"a native preparation decline must leave legacy planning context unchanged"
);
}
/// An aggregate is answered natively now (`sum(rate(..))`, `avg by(..)(..)` are split), so what
/// still falls back here is the shape the split cannot carry: a fold over two actual sources, which
/// no partition holds the whole of.
#[tokio::test]
async fn native_fused_aggregate_falls_back_to_legacy_plan() {
for query in ["some_metric + sum(some_metric)"] {
let plan = build_native_fused_plan(query, true).await;
let display = plan.display_indent().to_string();
assert!(!display.contains("FusedSeries"), "{query}: {display}");
assert!(
!display.contains("AggregateFinalize:"),
"{query}: {display}"
);
assert!(display.contains("Aggregate:"), "{query}: {display}");
let legacy = build_native_fused_plan(query, false).await;
assert_eq!(display, legacy.display_indent().to_string(), "{query}");
}
}
#[tokio::test]
async fn native_fused_subquery_falls_back_to_legacy_plan() {
for query in [
"rate(some_metric[5m:1m])",
"rate(rate(some_metric[5m:1m])[10m:1m])",
] {
let plan = build_native_fused_plan(query, true).await;
let display = plan.display_indent().to_string();
assert!(!display.contains("FusedSeries"), "{query}: {display}");
let legacy = build_native_fused_plan(query, false).await;
assert_eq!(display, legacy.display_indent().to_string(), "{query}");
}
}
/// The flag off: no statement is offered to the native route at all.
#[tokio::test]
async fn native_fused_flag_off_keeps_the_existing_plan() {
+1
View File
@@ -16,6 +16,7 @@ mod gc;
mod instance_kafka_wal_test;
mod instance_noop_wal_test;
mod instance_test;
mod native_aggregate_test;
mod nested_merge_scan_capability_test;
mod promql_test;
mod reconcile_table;
File diff suppressed because it is too large Load Diff