Skip to main content

promql/map/
broadcast.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
15use std::sync::Arc;
16
17use datafusion::error::{DataFusionError, Result};
18use datatypes::series::SeriesLabels;
19use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema};
20use datatypes::series::time::TimeAxis;
21
22use crate::grid_series::GridSeriesBuilder;
23use crate::map::{
24    ArithmeticOp, Comparison, MathOp, drop_metric_name, float_sample, validate_float_series,
25    validate_grid_series,
26};
27
28/// A time-varying, unlabelled single-field scalar, with explicit operand direction.
29#[derive(Clone, Copy, Debug)]
30pub enum ScalarSeriesOperand<'a> {
31    Left(&'a Series),
32    Right(&'a Series),
33}
34
35/// Applies arithmetic between vector fields and a time-varying scalar, aligned by absolute grid
36/// index, and drops the metric name.
37///
38/// Prometheus scalars exist at every step; a missing scalar point here yields a missing output.
39/// The output covers the valid rows and nothing else, and `None` means there is none. A scalar
40/// point holding no value is a hole in the one result series, not the end of a piece: the axis
41/// names the runs of consecutive valid positions. The scalar must be unlabelled and single-field
42/// on the same grid; histogram/mixed/raw inputs are rejected even outside the overlap. Both
43/// operands may skip positions: only the positions both carry are evaluated, and the two axes are
44/// aligned by intersecting their runs, never by subtracting one axis' first position from the
45/// other's indices. Two unlabelled single-field inputs also evaluate scalar–scalar operations.
46/// Same-labelset merging is left to the caller, as in [`crate::map::map_math`].
47pub fn map_arithmetic_series(
48    schema: &Arc<SeriesSchema>,
49    vector: &Series,
50    op: ArithmeticOp,
51    scalar: ScalarSeriesOperand<'_>,
52) -> Result<Option<Series>> {
53    let metric = drop_metric_name(&vector.metric)?;
54    let (output, _) = map_grid_scalar(
55        schema,
56        vector,
57        scalar,
58        metric,
59        NonFloatSample::Impossible,
60        |left, right, _| Some(op.calculate(left, right)),
61    )?;
62    Ok(output)
63}
64
65/// Compares against a time-varying scalar. Filter keeps vector values and labels; bool emits
66/// 0/1 and drops the metric name.
67///
68/// Shares [`map_arithmetic_series`]'s alignment and row-keeping contract. Each field is compared
69/// independently; a row is kept where any field passes a filter.
70///
71/// A histogram has no ordering against a scalar, so the positions it holds answer nothing; the
72/// second element of the answer reports whether one was dropped so the caller can say so. The
73/// literal-scalar form ([`crate::map::map_compare_literal`]) applies the same rule, and both exist
74/// because a time-varying scalar cannot be folded into a constant.
75pub fn map_compare_series(
76    schema: &Arc<SeriesSchema>,
77    vector: &Series,
78    comparison: Comparison,
79    scalar: ScalarSeriesOperand<'_>,
80) -> Result<(Option<Series>, bool)> {
81    let metric = if matches!(comparison, Comparison::Bool(_)) {
82        drop_metric_name(&vector.metric)?
83    } else {
84        vector.metric.clone()
85    };
86    map_grid_scalar(
87        schema,
88        vector,
89        scalar,
90        metric,
91        NonFloatSample::Drop,
92        |left, right, sample| comparison.apply(left, right, sample),
93    )
94}
95
96/// `max_of(a, b)` and `min_of(a, b)`, which Prometheus evaluates with Go's `math.Max` and
97/// `math.Min`.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub(crate) enum ScalarFunction {
100    MaxOf,
101    MinOf,
102}
103
104impl ScalarFunction {
105    /// Go's `math.Max` / `math.Min`: an infinity of the function's own sign wins over NaN, NaN
106    /// over any other value, and `+0` is greater than `-0`.
107    ///
108    /// Both are symmetric in their arguments, signed zero included, so the kernel does not depend
109    /// on which operand came first.
110    pub(crate) fn apply(self, a: f64, b: f64) -> f64 {
111        let (wins, signed_zero_wins) = match self {
112            Self::MaxOf => (f64::INFINITY, false),
113            Self::MinOf => (f64::NEG_INFINITY, true),
114        };
115        if a == wins || b == wins {
116            wins
117        } else if a.is_nan() || b.is_nan() {
118            f64::NAN
119        } else if a == 0.0 && a == b {
120            if a.is_sign_negative() == signed_zero_wins {
121                a
122            } else {
123                b
124            }
125        } else if (a > b) == (self == Self::MaxOf) {
126            a
127        } else {
128            b
129        }
130    }
131}
132
133/// A math function whose parameters are scalar expressions, which Prometheus evaluates at every
134/// step, with those parameters as time-varying scalars.
135///
136/// All but `max_of` and `min_of` map an evaluated vector's fields onto the same fields; those two
137/// are functions of two scalars, so the series they map is the unlabelled one-field scalar the
138/// call's first operand evaluates to.
139#[derive(Clone, Copy, Debug)]
140pub enum ParameterizedMath<'a> {
141    /// `round(v, to_nearest)`.
142    Round { to_nearest: &'a Series },
143    /// `clamp(v, min, max)`.
144    Clamp { min: &'a Series, max: &'a Series },
145    /// `clamp_min(v, min)`.
146    ClampMin { min: &'a Series },
147    /// `clamp_max(v, max)`.
148    ClampMax { max: &'a Series },
149    /// `max_of(a, b)`, whose two operands are scalars: the input of the call is `a` and `other` is
150    /// `b`.
151    MaxOf { other: &'a Series },
152    /// `min_of(a, b)`, whose two operands are scalars: the input of the call is `a` and `other` is
153    /// `b`.
154    MinOf { other: &'a Series },
155}
156
157impl<'a> ParameterizedMath<'a> {
158    /// The parameters in argument order.
159    fn parameters(self) -> Vec<&'a Series> {
160        match self {
161            Self::Round { to_nearest } => vec![to_nearest],
162            Self::Clamp { min, max } => vec![min, max],
163            Self::ClampMin { min } => vec![min],
164            Self::ClampMax { max } => vec![max],
165            Self::MaxOf { other } | Self::MinOf { other } => vec![other],
166        }
167    }
168
169    /// The function with the parameter values of one point, in argument order.
170    fn at(self, values: &[f64]) -> PointMath {
171        match self {
172            Self::Round { .. } => PointMath::Math(MathOp::Round { nearest: values[0] }),
173            Self::Clamp { .. } => PointMath::Math(MathOp::Clamp {
174                min: values[0],
175                max: values[1],
176            }),
177            Self::ClampMin { .. } => PointMath::Math(MathOp::ClampMin { min: values[0] }),
178            Self::ClampMax { .. } => PointMath::Math(MathOp::ClampMax { max: values[0] }),
179            Self::MaxOf { .. } => PointMath::Scalar {
180                function: ScalarFunction::MaxOf,
181                other: values[0],
182            },
183            Self::MinOf { .. } => PointMath::Scalar {
184                function: ScalarFunction::MinOf,
185                other: values[0],
186            },
187        }
188    }
189}
190
191/// What one point's parameter values make of a parameterized math function: the kernel that reads
192/// the input's own value, with everything else the point decides already bound.
193#[derive(Clone, Copy, Debug)]
194enum PointMath {
195    /// A math function of the input's value, as `round` is.
196    Math(MathOp),
197    /// The larger or smaller of the input's value and the parameter's, which are the two operands
198    /// of `max_of` and `min_of`.
199    Scalar {
200        function: ScalarFunction,
201        other: f64,
202    },
203}
204
205impl PointMath {
206    /// The value the function answers for `value`, or `None` where it answers nothing: a `clamp`
207    /// whose bounds were written the wrong way round has no result at that point.
208    fn calculate(self, value: f64) -> Option<f64> {
209        match self {
210            Self::Math(op) => (!op.is_empty_clamp()).then(|| op.calculate(value)),
211            Self::Scalar { function, other } => Some(function.apply(value, other)),
212        }
213    }
214}
215
216/// Applies `function` to every field with its parameters read at each point from time-varying
217/// scalars, and drops the metric name, as [`crate::map::map_math`] does with constant parameters;
218/// native histogram samples are skipped the same way.
219///
220/// A point where a parameter has no value has no result. `clamp` with `max < min` at a point has
221/// no result there, as Prometheus returns an empty vector for that step. `None` means no point
222/// holds a result. Same-labelset merging is left to the caller.
223///
224/// `series` is one evaluated series, which for `max_of` and `min_of` is the unlabelled one-field
225/// scalar their first argument evaluates to: those two are functions of two scalars, so what they
226/// map is the first of them and what they read per point is the second.
227pub fn map_math_with_parameters(
228    schema: &Arc<SeriesSchema>,
229    series: &Series,
230    function: ParameterizedMath<'_>,
231) -> Result<Option<Series>> {
232    let time = validate_grid_series(schema, series)?;
233    let parameters = function.parameters();
234    let mut parameter_axes = Vec::with_capacity(parameters.len());
235    for parameter in &parameters {
236        parameter_axes.push(validate_scalar(schema, parameter)?);
237    }
238    // Points only increase, so each parameter's row does too and one cursor reads it.
239    let mut parameter_cursors: Vec<_> = parameters
240        .iter()
241        .map(|parameter| parameter.fields.as_slice()[0].cursor())
242        .collect();
243    let mut field_cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
244    let mut values = Vec::with_capacity(parameters.len());
245    let mut row = Vec::with_capacity(field_cursors.len());
246    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
247    for (point, index) in time.positions() {
248        values.clear();
249        for (axis, cursor) in parameter_axes.iter().zip(&mut parameter_cursors) {
250            let value = axis.row_of(point).and_then(|row| {
251                float_sample(cursor.at(row).expect("parameter rows only increase"))
252            });
253            values.extend(value);
254        }
255        let op = (values.len() == parameters.len()).then(|| function.at(&values));
256        row.clear();
257        for cursor in &mut field_cursors {
258            let sample = cursor
259                .at(index)
260                .expect("the axis and the fields are aligned");
261            row.push(match (op, sample) {
262                (Some(op), SampleRef::Float(value)) => op.calculate(value),
263                _ => None,
264            });
265        }
266        builder.push(point, &row)?;
267    }
268    builder.finish(drop_metric_name(&series.metric)?)
269}
270
271/// Calls `calculate(left, right, vector_sample)` at each index where both operands exist.
272/// What a vector sample that holds no float value means to the kernel being applied.
273#[derive(Clone, Copy, Debug)]
274enum NonFloatSample {
275    /// The caller proved the vector holds floats only, so a histogram here is a bug.
276    Impossible,
277    /// The operation has no answer for it: the position answers nothing and the caller is told
278    /// that a sample was dropped, which is what Prometheus does with a histogram under an operator
279    /// it has no meaning for.
280    Drop,
281}
282
283fn map_grid_scalar(
284    schema: &Arc<SeriesSchema>,
285    vector: &Series,
286    scalar: ScalarSeriesOperand<'_>,
287    metric: SeriesLabels,
288    non_float: NonFloatSample,
289    calculate: impl Fn(f64, f64, f64) -> Option<f64>,
290) -> Result<(Option<Series>, bool)> {
291    let vector_time = match non_float {
292        NonFloatSample::Impossible => validate_float_series(schema, vector)?,
293        NonFloatSample::Drop => validate_grid_series(schema, vector)?,
294    };
295    let (scalar_series, scalar_left) = match scalar {
296        ScalarSeriesOperand::Left(s) => (s, true),
297        ScalarSeriesOperand::Right(s) => (s, false),
298    };
299    let scalar_time = validate_scalar(schema, scalar_series)?;
300    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
301    // The shared runs carry both compact rows, so each operand reads its own field from the row
302    // its own axis assigns to the position. A position only one side carries is missing anyway:
303    // the pairing would be missing, and the builder keeps no row for it.
304    let mut scalar_samples = scalar_series.fields.as_slice()[0].cursor();
305    let mut field_samples = vector
306        .fields
307        .iter()
308        .map(|field| field.cursor())
309        .collect::<Vec<_>>();
310    let mut row = Vec::with_capacity(field_samples.len());
311    let mut dropped_histogram = false;
312    for pair in vector_time.intersect_runs(scalar_time) {
313        for offset in 0..pair.len {
314            let scalar = float_sample(
315                scalar_samples
316                    .at(pair.other_row + offset)
317                    .expect("the shared run lies inside the scalar axis"),
318            );
319            row.clear();
320            for field in &mut field_samples {
321                let sample = match field
322                    .at(pair.row + offset)
323                    .expect("the shared run lies inside the vector axis")
324                {
325                    SampleRef::Float(value) => Some(value),
326                    SampleRef::Missing => None,
327                    SampleRef::Histogram(_) => {
328                        match non_float {
329                            NonFloatSample::Drop => dropped_histogram = true,
330                            NonFloatSample::Impossible => {
331                                unreachable!("validated as float")
332                            }
333                        }
334                        None
335                    }
336                };
337                row.push(scalar.zip(sample).and_then(|(scalar, sample)| {
338                    if scalar_left {
339                        calculate(scalar, sample, sample)
340                    } else {
341                        calculate(sample, scalar, sample)
342                    }
343                }));
344            }
345            builder.push(pair.position + offset, &row)?;
346        }
347    }
348    Ok((builder.finish(metric)?, dropped_histogram))
349}
350
351pub(crate) fn validate_scalar<'a>(
352    schema: &SeriesSchema,
353    scalar: &'a Series,
354) -> Result<&'a TimeAxis> {
355    if scalar.metric.name().is_some() || !scalar.metric.tags().is_empty() {
356        return Err(DataFusionError::Execution(
357            "grid scalar must be unlabelled".into(),
358        ));
359    }
360    let schema = SeriesSchema {
361        fields: vec![FieldSpec {
362            name: "scalar".into(),
363        }]
364        .into(),
365        eval_grid: schema.eval_grid.clone(),
366    };
367    validate_float_series(&schema, scalar)
368}