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