Skip to main content

promql/
map.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//! Pointwise kernels for evaluated series, independent of planning and execution nodes.
16//!
17//! Expression column naming and omission of missing points belong to the planner/output adapter;
18//! these kernels retain the shared field schema and represent missing grid positions by validity.
19
20mod broadcast;
21mod comparison;
22#[cfg(test)]
23mod tests;
24
25pub(crate) use broadcast::validate_scalar;
26pub use broadcast::{
27    ParameterizedMath, ScalarSeriesOperand, map_arithmetic_series, map_compare_series,
28    map_math_with_parameters,
29};
30pub use comparison::{Comparison, ComparisonOp, map_compare_literal};
31
32use std::f64::consts::PI;
33use std::sync::Arc;
34
35use datafusion::error::{DataFusionError, Result};
36use datatypes::arrow::array::{Float64Array, Float64Builder, UInt32Builder};
37use datatypes::series::histogram::HistogramBatchBuilder;
38use datatypes::series::samples::{
39    DenseSamplesRef, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
40};
41use datatypes::series::time::{GridRange, TimeAxis};
42use datatypes::series::{Label, SeriesLabels};
43
44use crate::histogram_eval::float_histogram::FloatHistogram;
45
46use crate::functions::Round;
47use crate::grid_series::GridSeriesBuilder;
48use crate::map_time::DateFunction;
49
50/// Float math supported by the evaluated-series kernel.
51#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
52pub enum MathOp {
53    Abs,
54    Ceil,
55    Floor,
56    Sqrt,
57    /// Rounds to a multiple of `nearest`; PromQL's default is `1.0`.
58    Round {
59        nearest: f64,
60    },
61    Exp,
62    Ln,
63    Log2,
64    Log10,
65    Sin,
66    Cos,
67    Tan,
68    Asin,
69    Acos,
70    Atan,
71    Sinh,
72    Cosh,
73    Tanh,
74    Asinh,
75    Acosh,
76    Atanh,
77    Deg,
78    Rad,
79    Sgn,
80    Clamp {
81        min: f64,
82        max: f64,
83    },
84    ClampMin {
85        min: f64,
86    },
87    ClampMax {
88        max: f64,
89    },
90    /// A date function of the value read as Unix seconds, such as `hour(v)`.
91    Date(DateFunction),
92}
93
94/// Float arithmetic between a vector and a scalar, as in Prometheus.
95#[derive(Clone, Copy, Debug)]
96pub enum ArithmeticOp {
97    Add,
98    Subtract,
99    Multiply,
100    Divide,
101    Modulo,
102    Power,
103    Atan2,
104}
105
106impl std::fmt::Display for ArithmeticOp {
107    /// The operator as written in the query, which names it in the dropped-histogram info.
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str(match self {
110            Self::Add => "+",
111            Self::Subtract => "-",
112            Self::Multiply => "*",
113            Self::Divide => "/",
114            Self::Modulo => "%",
115            Self::Power => "^",
116            Self::Atan2 => "atan2",
117        })
118    }
119}
120
121/// The scalar's position in a binary expression; noncommutative operators retain this order.
122#[derive(Clone, Copy, Debug)]
123pub enum ScalarOperand {
124    Left(f64),
125    Right(f64),
126}
127
128/// Applies float math to every field of one evaluated series and drops the metric name, like
129/// Prometheus' `simpleFloatFunc`.
130///
131/// Requires an evaluated grid axis; missingness is validity, not a NaN payload, so raw staleness
132/// must be resolved before. Missing samples stay missing and NaNs stay values. Histogram samples
133/// are skipped: their points have no result. Returns `None` for `clamp` with `max < min`, which
134/// yields no series in Prometheus, or when a series with histograms has no float result left.
135///
136/// Transcendental functions use the platform math library and can differ from Go in the last bits.
137///
138/// Distinct inputs can share a label set once the name is dropped; merging them is left to the
139/// caller (Prometheus `mergeSeriesWithSameLabelset`).
140pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Option<Series>> {
141    if op.is_empty_clamp() {
142        validate_grid_series(schema, series)?;
143        return Ok(None);
144    }
145    if !is_float_series(series) {
146        let time = validate_grid_series(schema, series)?;
147        let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
148        let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
149        let mut row = Vec::with_capacity(cursors.len());
150        for (point, index) in time.positions() {
151            row.clear();
152            for cursor in &mut cursors {
153                row.push(
154                    match cursor
155                        .at(index)
156                        .expect("the axis and the fields are aligned")
157                    {
158                        SampleRef::Float(value) => Some(op.calculate(value)),
159                        SampleRef::Missing | SampleRef::Histogram(_) => None,
160                    },
161                );
162            }
163            builder.push(point, &row)?;
164        }
165        return builder.finish(drop_metric_name(&series.metric)?);
166    }
167    let mut output = map_float_fields(schema, series, |floats| op.apply(floats))?;
168    output.metric = drop_metric_name(&output.metric)?;
169    Ok(Some(output))
170}
171
172/// Applies arithmetic against a constant scalar to every field and drops the metric name.
173///
174/// Same contract as [`map_math`], except that histogram samples are rejected.
175pub fn map_arithmetic(
176    schema: &SeriesSchema,
177    series: &Series,
178    op: ArithmeticOp,
179    scalar: ScalarOperand,
180) -> Result<Series> {
181    let mut output = map_float_fields(schema, series, |floats| op.apply(floats, scalar))?;
182    output.metric = drop_metric_name(&output.metric)?;
183    Ok(output)
184}
185
186/// Applies literal scalar arithmetic to float and histogram samples. Histograms support only
187/// `h * s`, `s * h` and `h / s`; under any other operator (`2 / h`, `h + 1`) the sample is dropped,
188/// as in Prometheus, and the second element reports that one was.
189pub(crate) fn map_arithmetic_literal(
190    schema: &SeriesSchema,
191    series: &Series,
192    op: ArithmeticOp,
193    scalar: ScalarOperand,
194) -> Result<(Series, bool)> {
195    validate_grid_series(schema, series)?;
196    if is_float_series(series) {
197        return Ok((map_arithmetic(schema, series, op, scalar)?, false));
198    }
199
200    let mut dropped_histogram = false;
201    let fields = series
202        .fields
203        .iter()
204        .map(|samples| {
205            let segments = samples
206                .segments()
207                .iter()
208                .map(|segment| {
209                    let (segment, dropped) = map_arithmetic_segment(segment, op, scalar)?;
210                    dropped_histogram |= dropped;
211                    Ok(segment)
212                })
213                .collect::<Result<Vec<_>>>()?;
214            Samples::try_from_chunks(segments).map_err(series_error)
215        })
216        .collect::<Result<Vec<_>>>()?;
217    let mut output = Series::try_new(
218        schema,
219        series.metric.clone(),
220        series.time.clone(),
221        SeriesFields::try_from_vec(fields).map_err(series_error)?,
222    )
223    .map_err(series_error)?;
224    output.metric = drop_metric_name(&output.metric)?;
225    Ok((output, dropped_histogram))
226}
227
228fn map_arithmetic_segment(
229    samples: &Samples,
230    op: ArithmeticOp,
231    scalar: ScalarOperand,
232) -> Result<(Samples, bool)> {
233    let mut floats = Float64Builder::with_capacity(samples.len());
234    let mut indices = UInt32Builder::with_capacity(samples.len());
235    let mut histograms = HistogramBatchBuilder::new();
236
237    let mut dropped_histogram = false;
238    for index in 0..samples.len() {
239        match samples.sample(index) {
240            SampleRef::Missing => {
241                floats.append_null();
242                indices.append_null();
243            }
244            SampleRef::Float(value) => {
245                let result = match scalar {
246                    ScalarOperand::Left(left) => op.calculate(left, value),
247                    ScalarOperand::Right(right) => op.calculate(value, right),
248                };
249                floats.append_value(result);
250                indices.append_null();
251            }
252            SampleRef::Histogram(view) => {
253                floats.append_null();
254                let histogram_result = match (op, scalar) {
255                    (ArithmeticOp::Multiply, ScalarOperand::Left(factor))
256                    | (ArithmeticOp::Multiply, ScalarOperand::Right(factor)) => {
257                        let mut histogram = FloatHistogram::try_from_view(&view)?;
258                        histogram.mul(factor);
259                        Some(histogram)
260                    }
261                    (ArithmeticOp::Divide, ScalarOperand::Right(divisor)) => {
262                        let mut histogram = FloatHistogram::try_from_view(&view)?;
263                        histogram.div(divisor);
264                        Some(histogram)
265                    }
266                    // Scalar / histogram and all other histogram operators drop this position.
267                    _ => None,
268                };
269                if let Some(mut histogram) = histogram_result {
270                    histogram.compact();
271                    let index = histogram.push_to(&mut histograms)?;
272                    indices.append_value(index);
273                } else {
274                    dropped_histogram = true;
275                    indices.append_null();
276                }
277            }
278        }
279    }
280
281    let histogram_samples =
282        HistogramSamples::try_new(indices.finish(), histograms.finish().map_err(series_error)?)
283            .map_err(series_error)?;
284    let samples =
285        Samples::try_from_mixed(floats.finish(), histogram_samples).map_err(series_error)?;
286    Ok((samples, dropped_histogram))
287}
288
289/// An unlabelled constant over exactly `range`; the schema must have one field.
290pub fn constant_series(schema: &SeriesSchema, range: GridRange, scalar: f64) -> Result<Series> {
291    let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
292        scalar;
293        range.len()
294    ])));
295    Series::try_new(
296        schema,
297        SeriesLabels::try_new(None, vec![]).map_err(series_error)?,
298        TimeAxis::Grid(range),
299        fields,
300    )
301    .map_err(series_error)
302}
303
304/// `pi()` over `range`.
305pub fn map_pi(schema: &SeriesSchema, range: GridRange) -> Result<Series> {
306    constant_series(schema, range, PI)
307}
308
309fn map_float_fields(
310    schema: &SeriesSchema,
311    series: &Series,
312    map: impl Fn(&Float64Array) -> Float64Array,
313) -> Result<Series> {
314    validate_float_series(schema, series)?;
315    let fields = series
316        .fields
317        .iter()
318        .map(|samples| map_samples(samples, &map))
319        .collect::<Result<Vec<_>>>()?;
320    let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
321    Series::try_new(schema, series.metric.clone(), series.time.clone(), fields)
322        .map_err(series_error)
323}
324
325/// Drops `__name__`, `__type__` and `__unit__`, as Prometheus `DropReserved(schema.IsMetadataLabel)`
326/// does. Empty values are dropped too: Prometheus has no empty labels, and keeping them would hide
327/// a same-labelset collision from the caller.
328pub(crate) fn drop_metric_name(metric: &SeriesLabels) -> Result<SeriesLabels> {
329    let tags = metric.tags();
330    let reject = |label: &Label| {
331        label.value.is_empty() || matches!(label.name.as_ref(), "__type__" | "__unit__")
332    };
333    let Some(first) = tags.iter().position(reject) else {
334        let mut result = metric.clone();
335        result.remove("__name__");
336        return Ok(result);
337    };
338
339    let mut kept = tags[..first].to_vec();
340    kept.extend(
341        tags[first + 1..]
342            .iter()
343            .filter(|label| !reject(label))
344            .cloned(),
345    );
346    SeriesLabels::try_new(None, kept).map_err(series_error)
347}
348
349/// Drops labels with empty values, which Prometheus treats as absent.
350pub(crate) fn drop_empty_labels(metric: &SeriesLabels) -> Result<SeriesLabels> {
351    let name = metric.name().filter(|name| !name.is_empty()).map(Arc::from);
352    rebuild_labels(metric, name, |_| true)
353}
354
355fn rebuild_labels(
356    metric: &SeriesLabels,
357    name: Option<Arc<str>>,
358    keep: impl Fn(&str) -> bool,
359) -> Result<SeriesLabels> {
360    let tags = metric
361        .tags()
362        .iter()
363        .filter(|label| !label.value.is_empty() && keep(&label.name))
364        .cloned()
365        .collect();
366    SeriesLabels::try_new(name, tags).map_err(series_error)
367}
368
369impl MathOp {
370    fn apply(self, floats: &Float64Array) -> Float64Array {
371        floats.unary(|sample| self.calculate(sample))
372    }
373
374    pub(crate) fn calculate(self, v: f64) -> f64 {
375        match self {
376            Self::Exp => v.exp(),
377            Self::Ln => v.ln(),
378            Self::Log2 => v.log2(),
379            Self::Log10 => v.log10(),
380            Self::Sin => v.sin(),
381            Self::Cos => v.cos(),
382            Self::Tan => v.tan(),
383            Self::Asin => v.asin(),
384            Self::Acos => v.acos(),
385            Self::Atan => v.atan(),
386            Self::Sinh => v.sinh(),
387            Self::Cosh => v.cosh(),
388            Self::Tanh => v.tanh(),
389            Self::Asinh => v.asinh(),
390            Self::Acosh => v.acosh(),
391            Self::Atanh => v.atanh(),
392            // Prometheus' operation order, which rounds differently from to_degrees/to_radians.
393            Self::Deg => v * 180.0 / PI,
394            Self::Rad => v * PI / 180.0,
395            // Zeros and NaN are returned unchanged, so -0 keeps its sign.
396            Self::Sgn => {
397                if v < 0.0 {
398                    -1.0
399                } else if v > 0.0 {
400                    1.0
401                } else {
402                    v
403                }
404            }
405            Self::Clamp { min, max } => go_max(min, go_min(max, v)),
406            Self::ClampMin { min } => go_max(min, v),
407            Self::ClampMax { max } => go_min(max, v),
408            Self::Abs => v.abs(),
409            Self::Ceil => v.ceil(),
410            Self::Floor => v.floor(),
411            Self::Sqrt => v.sqrt(),
412            Self::Round { nearest } => Round::round_to_nearest(v, nearest),
413            Self::Date(function) => function.of_seconds(v),
414        }
415    }
416
417    /// Prometheus returns an empty vector when `max < min`; NaN bounds do not compare.
418    fn is_empty_clamp(self) -> bool {
419        match self {
420            Self::Clamp { min, max } => max < min,
421            _ => false,
422        }
423    }
424}
425
426/// Go `math.Max`: +Inf wins over NaN, and +0 over -0.
427fn go_max(x: f64, y: f64) -> f64 {
428    if x == f64::INFINITY || y == f64::INFINITY {
429        f64::INFINITY
430    } else if x.is_nan() || y.is_nan() {
431        f64::NAN
432    } else if x == 0.0 && x == y {
433        if x.is_sign_negative() { y } else { x }
434    } else if x > y {
435        x
436    } else {
437        y
438    }
439}
440
441/// Go `math.Min`: -Inf wins over NaN, and -0 over +0.
442fn go_min(x: f64, y: f64) -> f64 {
443    if x == f64::NEG_INFINITY || y == f64::NEG_INFINITY {
444        f64::NEG_INFINITY
445    } else if x.is_nan() || y.is_nan() {
446        f64::NAN
447    } else if x == 0.0 && x == y {
448        if x.is_sign_negative() { x } else { y }
449    } else if x < y {
450        x
451    } else {
452        y
453    }
454}
455
456impl ArithmeticOp {
457    /// Evaluates `left op right`; constant folding uses it too. `^` and `atan2` use the platform
458    /// math library and can differ from Go for subnormal or extreme operands.
459    #[inline]
460    pub fn calculate(self, left: f64, right: f64) -> f64 {
461        match self {
462            Self::Add => left + right,
463            Self::Subtract => left - right,
464            Self::Multiply => left * right,
465            Self::Divide => left / right,
466            Self::Modulo => left % right,
467            Self::Power => left.powf(right),
468            Self::Atan2 => left.atan2(right),
469        }
470    }
471
472    fn apply(self, floats: &Float64Array, scalar: ScalarOperand) -> Float64Array {
473        match scalar {
474            ScalarOperand::Left(scalar) => floats.unary(|sample| self.calculate(scalar, sample)),
475            ScalarOperand::Right(scalar) => floats.unary(|sample| self.calculate(sample, scalar)),
476        }
477    }
478}
479
480fn map_samples(samples: &Samples, map: &impl Fn(&Float64Array) -> Float64Array) -> Result<Samples> {
481    let chunks = samples
482        .segments()
483        .iter()
484        .map(|segment| map_float_segment(segment, map))
485        .collect::<Result<Vec<_>>>()?;
486    Samples::try_from_chunks(chunks).map_err(series_error)
487}
488
489fn map_float_segment(
490    segment: &Samples,
491    map: &impl Fn(&Float64Array) -> Float64Array,
492) -> Result<Samples> {
493    let Some(DenseSamplesRef::Float(floats)) = segment.dense() else {
494        return Err(DataFusionError::NotImplemented(
495            "Series operators support only float samples; histogram/mixed samples are not supported"
496                .into(),
497        ));
498    };
499    Ok(Samples::from_float(map(floats)))
500}
501
502fn series_error(error: datatypes::error::Error) -> DataFusionError {
503    DataFusionError::External(Box::new(error))
504}
505
506/// Checks `series` against `schema` and its grid, and rejects any non-float sample. Returns the
507/// axis, which may skip positions, so callers traverse it rather than assume a contiguous range.
508pub(crate) fn validate_float_series<'a>(
509    schema: &SeriesSchema,
510    series: &'a Series,
511) -> Result<&'a TimeAxis> {
512    let time = validate_grid_series(schema, series)?;
513    if !is_float_series(series) {
514        return Err(DataFusionError::NotImplemented(
515            "Series operators support only float samples; histogram/mixed samples are not supported"
516                .into(),
517        ));
518    }
519    Ok(time)
520}
521
522pub(crate) fn is_float_series(series: &Series) -> bool {
523    series.fields.iter().all(|field| {
524        field
525            .segments()
526            .iter()
527            .all(|segment| matches!(segment.dense(), Some(DenseSamplesRef::Float(_))))
528    })
529}
530
531/// Checks `series` against `schema` and its evaluation grid, whatever its sample types.
532pub(crate) fn validate_grid_series<'a>(
533    schema: &SeriesSchema,
534    series: &'a Series,
535) -> Result<&'a TimeAxis> {
536    let time = &series.time;
537    if time.grid().is_none() {
538        return Err(DataFusionError::Execution(
539            "Series operators require an evaluated grid time axis".into(),
540        ));
541    }
542    Series::try_new(
543        schema,
544        series.metric.clone(),
545        series.time.clone(),
546        series.fields.clone(),
547    )
548    .map_err(series_error)?;
549    Ok(time)
550}
551
552/// A sample of a series accepted by [`validate_float_series`].
553fn float_sample(sample: SampleRef<'_>) -> Option<f64> {
554    match sample {
555        SampleRef::Float(sample) => Some(sample),
556        SampleRef::Missing => None,
557        _ => unreachable!("validated as float"),
558    }
559}
560
561impl PartialEq for MathOp {
562    fn eq(&self, o: &Self) -> bool {
563        match (self, o) {
564            (Self::Round { nearest: a }, Self::Round { nearest: b }) => a.to_bits() == b.to_bits(),
565            (Self::Clamp { min: a, max: b }, Self::Clamp { min: c, max: d }) => {
566                a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits()
567            }
568            (Self::ClampMin { min: a }, Self::ClampMin { min: b })
569            | (Self::ClampMax { max: a }, Self::ClampMax { max: b }) => a.to_bits() == b.to_bits(),
570            (Self::Date(a), Self::Date(b)) => a == b,
571            _ => std::mem::discriminant(self) == std::mem::discriminant(o),
572        }
573    }
574}
575impl Eq for MathOp {}
576impl std::hash::Hash for MathOp {
577    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
578        std::mem::discriminant(self).hash(h);
579        match self {
580            Self::Round { nearest: x } | Self::ClampMin { min: x } | Self::ClampMax { max: x } => {
581                x.to_bits().hash(h)
582            }
583            Self::Clamp { min, max } => {
584                min.to_bits().hash(h);
585                max.to_bits().hash(h)
586            }
587            Self::Date(d) => d.hash(h),
588            _ => (),
589        }
590    }
591}