Skip to main content

promql/native/
split.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Where a native aggregate is split so two planes can run it.
16//!
17//! A `Complete` aggregate is only correct when one execution reads every contribution. Over a
18//! partitioned raw-series scan, the innermost aggregate is split: the per-series prefix runs in each
19//! partition under a `Partial` aggregate, and the suffix above the cut runs over a `Final` aggregate
20//! of the merged state.
21//!
22//! What cannot be split correctly is refused with [`DataFusionError::NotImplemented`], which the
23//! planner reads as "plan this query the existing way".
24
25use std::sync::Arc;
26
27use datafusion::error::{DataFusionError, Result as DfResult};
28use datatypes::series::SeriesOrdering;
29use datatypes::series::samples::{FieldSpec, SeriesSchema};
30
31use crate::map::MathOp;
32use crate::native::plan::{
33    AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundVectorOp,
34    Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, aggregate_state_binding,
35};
36
37pub(crate) struct Split {
38    /// The per-series tree below the cut aggregate.
39    prefix: NativeNode,
40    /// The tree above the cut, with an input node where the merged values enter.
41    suffix: NativeNode,
42    op: BoundAggregate,
43    /// The cut aggregate's output, which the exported state is indexed by.
44    schema: Arc<SeriesSchema>,
45    /// The suffix reads whole histograms rather than individual groups.
46    histogram: bool,
47    /// The suffix rewrites at least one label of the histogram routing key.
48    label_rewrite: bool,
49}
50
51/// Whether every histogram-routing key of this aggregate is necessarily empty.
52pub(crate) fn histogram_group_is_single(group: &Grouping) -> bool {
53    matches!(group, Grouping::By(labels) if labels.iter().all(|label| {
54        crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS.contains(&label.as_ref())
55    }))
56}
57
58/// Splits the innermost aggregate out of `node`; `Ok(None)` when `node` holds no aggregate.
59///
60/// The suffix may hold maps, constant-sided binaries, subquery windows, one histogram function and a
61/// ranking (`topk`/`bottomk`). A label rewrite below a histogram function can split one histogram
62/// into two, so it is refused alongside a partitioned histogram when it touches the routing key; a
63/// rewrite above the function renames the answer it already folded and is admitted. A ranking reads
64/// the cut's answer as a whole - `topk(k, A ∪ B)` is `topk(k, topk(k, A) ∪ topk(k, B))` - so ranking
65/// the merged groups once is the query's ranking. Anything answered above the cut (a histogram
66/// parameter, a ranking's `k`) must read no series.
67pub(crate) fn split(
68    node: &NativeNode,
69    fields: &[FieldSpec],
70    time_index: &str,
71) -> DfResult<Option<Split>> {
72    match &node.expr {
73        NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => Ok(None),
74        NativeExpr::Map { input, op } => {
75            let Some(mut inner) = split(input, fields, time_index)? else {
76                return Ok(None);
77            };
78            let changes_key = op.ops.iter().any(|op| {
79                let MapOp::Label(rewrite) = op else {
80                    return false;
81                };
82                let destination = rewrite.destination();
83                !crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS.contains(&destination)
84                    && match &inner.op.group {
85                        Grouping::By(labels) => {
86                            labels.iter().any(|label| label.as_ref() == destination)
87                        }
88                        Grouping::Without(labels) => {
89                            !labels.iter().any(|label| label.as_ref() == destination)
90                        }
91                    }
92            });
93            // Recorded so a histogram function *above* this map still sees the rewrite below it.
94            inner.label_rewrite |= changes_key;
95            inner.suffix = NativeNode {
96                expr: NativeExpr::Map {
97                    input: Box::new(inner.suffix),
98                    op: op.clone(),
99                },
100                output: node.output.clone(),
101            };
102            Ok(Some(inner))
103        }
104        NativeExpr::Aggregate { input, op } => {
105            check_cut(op, fields, time_index)?;
106            match split(input, fields, time_index)? {
107                Some(_) => Err(declined("an aggregate above a split aggregate")),
108                None => {
109                    admit_prefix(input)?;
110                    let NativeType::Samples(schema) = &node.output else {
111                        return Err(declined("an aggregate that produces no values"));
112                    };
113                    if schema.eval_grid.is_none() {
114                        return Err(declined("an aggregate that produces no values"));
115                    }
116                    Ok(Some(Split {
117                        prefix: (**input).clone(),
118                        // Source indices are local to one execution; the suffix has one input.
119                        suffix: NativeNode {
120                            expr: NativeExpr::Input(BoundInput {
121                                source_index: 0,
122                                output: node.output.clone(),
123                                ordering: SeriesOrdering::Contiguous,
124                            }),
125                            output: node.output.clone(),
126                        },
127                        op: op.clone(),
128                        schema: Arc::clone(schema),
129                        histogram: false,
130                        label_rewrite: false,
131                    }))
132                }
133            }
134        }
135        NativeExpr::Vector {
136            input,
137            op: BoundVectorOp::Histogram(function),
138        } => {
139            let Some(mut inner) = split(input, fields, time_index)? else {
140                return Ok(None);
141            };
142            // Two histogram calls may drop different labels at successive levels (in particular,
143            // a native histogram retains `le`), so the first call's partition key is not enough.
144            if inner.histogram {
145                return Err(declined("nested histograms above a split aggregate"));
146            }
147            if inner.label_rewrite && !histogram_group_is_single(&inner.op.group) {
148                return Err(declined(
149                    "a routing-label rewrite around a partitioned histogram",
150                ));
151            }
152            inner.histogram = true;
153            inner.suffix = NativeNode {
154                expr: NativeExpr::Vector {
155                    input: Box::new(inner.suffix),
156                    op: BoundVectorOp::Histogram(*function),
157                },
158                output: node.output.clone(),
159            };
160            Ok(Some(inner))
161        }
162        NativeExpr::ParameterizedHistogram {
163            input,
164            op,
165            parameters,
166        } => {
167            let Some(mut inner) = split(input, fields, time_index)? else {
168                return Ok(None);
169            };
170            if inner.histogram {
171                return Err(declined("nested histograms above a split aggregate"));
172            }
173            if inner.label_rewrite && !histogram_group_is_single(&inner.op.group) {
174                return Err(declined(
175                    "a routing-label rewrite around a partitioned histogram",
176                ));
177            }
178            if parameters
179                .iter()
180                .any(|parameter| !suffix_carries(parameter))
181            {
182                return Err(declined(
183                    "a histogram parameter that reads the series the split reads",
184                ));
185            }
186            inner.histogram = true;
187            inner.suffix = NativeNode {
188                expr: NativeExpr::ParameterizedHistogram {
189                    input: Box::new(inner.suffix),
190                    op: op.clone(),
191                    parameters: parameters.clone(),
192                },
193                output: node.output.clone(),
194            };
195            Ok(Some(inner))
196        }
197        // `state_routing` records a ranking as reading across groups, so the merged groups reach one
198        // owner and no group is ranked apart.
199        NativeExpr::Vector {
200            input,
201            op: ranking @ BoundVectorOp::TopK { .. },
202        } => {
203            let Some(mut inner) = split(input, fields, time_index)? else {
204                return Ok(None);
205            };
206            inner.suffix = NativeNode {
207                expr: NativeExpr::Vector {
208                    input: Box::new(inner.suffix),
209                    op: ranking.clone(),
210                },
211                output: node.output.clone(),
212            };
213            Ok(Some(inner))
214        }
215        // `k` is answered above the cut, so it has to read no series, as a histogram parameter does.
216        NativeExpr::ParameterizedTopK {
217            input,
218            op,
219            parameter,
220        } => {
221            let Some(mut inner) = split(input, fields, time_index)? else {
222                return Ok(None);
223            };
224            if !suffix_carries(parameter) {
225                return Err(declined(
226                    "a ranking parameter that reads the series the split reads",
227                ));
228            }
229            inner.suffix = NativeNode {
230                expr: NativeExpr::ParameterizedTopK {
231                    input: Box::new(inner.suffix),
232                    op: op.clone(),
233                    parameter: parameter.clone(),
234                },
235                output: node.output.clone(),
236            };
237            Ok(Some(inner))
238        }
239        // Always a `quantile`, whose state is its group's samples however its argument is read.
240        NativeExpr::ParameterizedAggregate { .. } => Err(declined("a `quantile` aggregate")),
241        // A merge in the prefix would see one partition's pieces only, so colliding series in
242        // different partitions would be folded instead of reported as
243        // `vector cannot contain metrics with the same labelset`. The merge must stay a boundary
244        // above every partition (`canonical_boundary_stages`).
245        NativeExpr::Merge { .. } => Err(declined("an aggregate split across a canonical merge")),
246        // Only a subquery window, whose input is evaluated, can sit above the cut.
247        NativeExpr::Window { input, op } => {
248            let Some(mut inner) = split(input, fields, time_index)? else {
249                return Ok(None);
250            };
251            let input_grid = input
252                .output
253                .samples()
254                .and_then(|schema| schema.eval_grid.as_ref());
255            if input_grid.is_none() {
256                return Err(declined("a window over raw samples above an aggregate"));
257            }
258            inner.suffix = NativeNode {
259                expr: NativeExpr::Window {
260                    input: Box::new(inner.suffix),
261                    op: op.clone(),
262                },
263                output: node.output.clone(),
264            };
265            Ok(Some(inner))
266        }
267        // These read values the merged state does not answer.
268        NativeExpr::Instant { input, .. }
269        | NativeExpr::Timestamp { input }
270        | NativeExpr::Vector { input, .. }
271        | NativeExpr::VectorOf { input }
272        | NativeExpr::ScalarOf { input }
273        | NativeExpr::ParameterizedMap { input, .. } => match split(input, fields, time_index)? {
274            Some(_) => Err(declined(
275                "an aggregate under an operation that reads evaluated values",
276            )),
277            None => Ok(None),
278        },
279        NativeExpr::Binary {
280            left,
281            right,
282            matching,
283        } => {
284            let (left_split, right_split) = (
285                split(left, fields, time_index)?,
286                split(right, fields, time_index)?,
287            );
288            // Only a broadcast against a literal applies unchanged to the merged values.
289            let (mut inner, constant_on_the_left) = match (left_split, right_split) {
290                (None, None) => return Ok(None),
291                (Some(inner), None) if matches!(right.expr, NativeExpr::Scalar(_)) => {
292                    (inner, false)
293                }
294                (None, Some(inner)) if matches!(left.expr, NativeExpr::Scalar(_)) => (inner, true),
295                _ => {
296                    return Err(declined(
297                        "an aggregate under a binary operation without a constant on the other side",
298                    ));
299                }
300            };
301            let (left, right) = if constant_on_the_left {
302                ((**left).clone(), inner.suffix)
303            } else {
304                (inner.suffix, (**right).clone())
305            };
306            inner.suffix = NativeNode {
307                expr: NativeExpr::Binary {
308                    left: Box::new(left),
309                    right: Box::new(right),
310                    matching: matching.clone(),
311                },
312                output: node.output.clone(),
313            };
314            Ok(Some(inner))
315        }
316        NativeExpr::Set { left, right, .. } => {
317            match (
318                split(left, fields, time_index)?,
319                split(right, fields, time_index)?,
320            ) {
321                (None, None) => Ok(None),
322                _ => Err(declined("an aggregate under a set operation")),
323            }
324        }
325        NativeExpr::Info { base, info, .. } => {
326            match (
327                split(base, fields, time_index)?,
328                split(info, fields, time_index)?,
329            ) {
330                (None, None) => Ok(None),
331                _ => Err(declined("an aggregate under info")),
332            }
333        }
334    }
335}
336
337/// The fields of the first raw input in `tree`, which a `by(...)` naming a value field would name.
338/// The split tree reads exactly one source.
339pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult<Vec<FieldSpec>> {
340    tree.root()
341        .inputs()
342        .into_iter()
343        .find_map(|input| {
344            input
345                .output
346                .samples()
347                .filter(|schema| schema.eval_grid.is_none())
348                .map(|schema| schema.fields.to_vec())
349        })
350        .ok_or_else(|| declined("a tree that reads no raw series"))
351}
352
353/// Refuses a non-`Complete` aggregate, a `quantile` (no fixed-width state), and a `by(...)` naming
354/// a value field or the time index.
355pub(crate) fn check_cut(
356    op: &BoundAggregate,
357    fields: &[FieldSpec],
358    time_index: &str,
359) -> DfResult<()> {
360    if op.stage != AggregateStage::Complete {
361        return Err(declined("an aggregate that is not `Complete`"));
362    }
363    if matches!(op.kind, AggregateKind::Quantile { .. }) {
364        return Err(declined("a `quantile` aggregate"));
365    }
366    if let Grouping::By(labels) = &op.group
367        && labels.iter().any(|label| {
368            label.as_ref() == time_index
369                || fields
370                    .iter()
371                    .any(|field| field.name.as_ref() == label.as_ref())
372        })
373    {
374        return Err(declined("an aggregate grouped by a value field"));
375    }
376    Ok(())
377}
378
379/// Checks that the prefix answers one series from one series' samples: maps and constant-sided
380/// binaries over a window or instant selection of a raw input.
381///
382/// A `clamp` whose maximum is below its minimum answers no value, so it is refused too.
383pub(crate) fn admit_prefix(root: &NativeNode) -> DfResult<()> {
384    let mut node = root;
385    loop {
386        match &node.expr {
387            NativeExpr::Map { input, op } => {
388                for map_op in op.ops.iter() {
389                    if let MapOp::Math(MathOp::Clamp { min, max }) = map_op
390                        && max < min
391                    {
392                        return Err(declined("a `clamp` whose maximum is below its minimum"));
393                    }
394                }
395                node = input;
396            }
397            NativeExpr::Binary { left, right, .. } => {
398                node = match (&left.expr, &right.expr) {
399                    (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => {
400                        return Err(declined("a per-series prefix of two constants"));
401                    }
402                    (NativeExpr::Scalar(_), _) => &**right,
403                    (_, NativeExpr::Scalar(_)) => &**left,
404                    (_, _) => {
405                        return Err(declined(
406                            "a per-series prefix that matches two vectors by label",
407                        ));
408                    }
409                };
410            }
411            NativeExpr::Merge { .. } => {
412                return Err(declined("a per-series prefix that collects a label set"));
413            }
414            _ => break,
415        }
416    }
417    let raw = |node: &NativeNode| match &node.expr {
418        NativeExpr::Input(input) => input
419            .output
420            .samples()
421            .is_some_and(|schema| schema.eval_grid.is_none()),
422        _ => false,
423    };
424    match &node.expr {
425        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } if raw(input) => {
426            Ok(())
427        }
428        _ => Err(declined(
429            "a per-series prefix that is not one series at a time",
430        )),
431    }
432}
433
434pub(crate) fn declined(reason: &str) -> DataFusionError {
435    DataFusionError::NotImplemented(format!(
436        "the native aggregate split does not carry {reason}"
437    ))
438}
439
440/// A split aggregate as the two trees that run it.
441pub struct SplitTrees {
442    /// The prefix under a `Partial` aggregate, answering aggregate state per partition.
443    pub partial: NativeTree,
444    /// The suffix over a `Final` aggregate of every partition's state.
445    pub final_tree: NativeTree,
446}
447
448impl Split {
449    /// `Ok(None)` when the aggregate has no mergeable state.
450    pub fn into_trees(self) -> DfResult<Option<SplitTrees>> {
451        let Self {
452            prefix,
453            suffix,
454            op,
455            schema,
456            histogram: _,
457            label_rewrite: _,
458        } = self;
459        let Some((kind, components)) = aggregate_state_binding(op.kind, op.field_kind) else {
460            return Ok(None);
461        };
462        let Some(grid) = schema.eval_grid.clone() else {
463            return Err(DataFusionError::Internal(
464                "a split aggregate has no evaluation grid".into(),
465            ));
466        };
467        let state = Arc::new(AggregateStateSchema {
468            group: op.group.clone(),
469            kind,
470            components: components.into(),
471            accumulators: schema.fields.clone(),
472            grid,
473        });
474        let partial = NativeTree::try_new(NativeNode {
475            expr: NativeExpr::Aggregate {
476                input: Box::new(prefix),
477                op: BoundAggregate {
478                    stage: AggregateStage::Partial,
479                    ..op.clone()
480                },
481            },
482            output: NativeType::AggregateState(Arc::clone(&state)),
483        })?;
484        let merged = NativeNode {
485            expr: NativeExpr::Aggregate {
486                input: Box::new(NativeNode {
487                    expr: NativeExpr::Input(BoundInput {
488                        source_index: 0,
489                        output: NativeType::AggregateState(Arc::clone(&state)),
490                        ordering: SeriesOrdering::Contiguous,
491                    }),
492                    output: NativeType::AggregateState(Arc::clone(&state)),
493                }),
494                op: BoundAggregate {
495                    stage: AggregateStage::Final,
496                    ..op
497                },
498            },
499            output: NativeType::Samples(Arc::clone(&schema)),
500        };
501        let root = enter_suffix(suffix, &merged)?;
502        Ok(Some(SplitTrees {
503            partial,
504            final_tree: NativeTree::try_new(root)?,
505        }))
506    }
507}
508
509/// Puts `merged` at the cut and returns the suffix above it.
510fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
511    let NativeNode { expr, output } = node;
512    let rejected = || {
513        DataFusionError::Internal("the split suffix holds an operation it does not build".into())
514    };
515    let expr = match expr {
516        NativeExpr::Input(_) => return Ok(merged.clone()),
517        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
518            return Ok(NativeNode { expr, output });
519        }
520        NativeExpr::Window { input, op } => NativeExpr::Window {
521            input: Box::new(enter_suffix(*input, merged)?),
522            op,
523        },
524        NativeExpr::Map { input, op } => NativeExpr::Map {
525            input: Box::new(enter_suffix(*input, merged)?),
526            op,
527        },
528        NativeExpr::Vector {
529            input,
530            op: op @ BoundVectorOp::Histogram(_),
531        } => NativeExpr::Vector {
532            input: Box::new(enter_suffix(*input, merged)?),
533            op,
534        },
535        NativeExpr::Vector {
536            input,
537            op: op @ BoundVectorOp::TopK { .. },
538        } => NativeExpr::Vector {
539            input: Box::new(enter_suffix(*input, merged)?),
540            op,
541        },
542        NativeExpr::ParameterizedTopK {
543            input,
544            op,
545            parameter,
546        } => NativeExpr::ParameterizedTopK {
547            input: Box::new(enter_suffix(*input, merged)?),
548            op,
549            parameter,
550        },
551        // `split` checked the parameters read no series, so they are kept as they are.
552        NativeExpr::ParameterizedHistogram {
553            input,
554            op,
555            parameters,
556        } => NativeExpr::ParameterizedHistogram {
557            input: Box::new(enter_suffix(*input, merged)?),
558            op,
559            parameters,
560        },
561        NativeExpr::Binary {
562            left,
563            right,
564            matching,
565        } => NativeExpr::Binary {
566            left: Box::new(enter_suffix(*left, merged)?),
567            right: Box::new(enter_suffix(*right, merged)?),
568            matching,
569        },
570        _ => return Err(rejected()),
571    };
572    Ok(NativeNode { expr, output })
573}
574
575/// Whether [`enter_suffix`] rebuilds this subtree from constants alone. It accepts a subset of the
576/// shapes `enter_suffix` builds; a shape outside them would become an `Internal` error there.
577fn suffix_carries(node: &NativeNode) -> bool {
578    match &node.expr {
579        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true,
580        NativeExpr::Map { input, .. }
581        | NativeExpr::Vector {
582            input,
583            op: BoundVectorOp::Histogram(_),
584        } => suffix_carries(input),
585        NativeExpr::Binary { left, right, .. } => suffix_carries(left) && suffix_carries(right),
586        _ => false,
587    }
588}