Skip to main content

promql/map/
comparison.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::Result;
18use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
19
20use crate::grid_series::GridSeriesBuilder;
21use crate::map::{ScalarOperand, drop_metric_name, validate_grid_series};
22
23/// IEEE comparisons: NaN only satisfies `NotEqual`, and signed zeros compare equal.
24#[derive(Clone, Copy, Debug)]
25pub enum ComparisonOp {
26    Equal,
27    NotEqual,
28    Less,
29    LessEqual,
30    Greater,
31    GreaterEqual,
32}
33
34/// Filter keeps the vector value and labels; bool emits 0/1 and drops the metric name.
35#[derive(Clone, Copy, Debug)]
36pub enum Comparison {
37    Filter(ComparisonOp),
38    Bool(ComparisonOp),
39}
40
41/// Compares a vector with a constant scalar, dropping the samples that have no comparison rather
42/// than failing the query.
43///
44/// Prometheus compares float samples only: a histogram has no ordering against a scalar, so the
45/// position it holds answers nothing. The existing planner says so with an info and answers no
46/// value there (`NativeHistogramDrop`, `prom_token_to_binary_expr_builder` in
47/// `query::promql::planner`), which is the behaviour mirrored here. The second element of the
48/// answer reports whether a histogram was dropped, so the caller can record that info once per
49/// chunk instead of once per position.
50///
51/// The literal form of a filter: `None` still means nothing passed, so the caller hands on no
52/// value for this chunk.
53pub fn map_compare_literal(
54    schema: &Arc<SeriesSchema>,
55    series: &Series,
56    comparison: Comparison,
57    scalar: ScalarOperand,
58) -> Result<(Option<Series>, bool)> {
59    // Whatever kinds the fields carry: a histogram position is dropped, not rejected, so the axis
60    // and the schema are checked without requiring float samples.
61    let time = validate_grid_series(schema, series)?;
62    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
63    let mut dropped_histogram = false;
64    let mut fields = series
65        .fields
66        .iter()
67        .map(|field| field.iter())
68        .collect::<Vec<_>>();
69    let mut row = Vec::with_capacity(fields.len());
70    for (position, _) in time.positions() {
71        row.clear();
72        for field in &mut fields {
73            row.push(match field.next().expect("validated length") {
74                SampleRef::Float(sample) => {
75                    let (left, right) = match scalar {
76                        ScalarOperand::Left(scalar) => (scalar, sample),
77                        ScalarOperand::Right(scalar) => (sample, scalar),
78                    };
79                    comparison.apply(left, right, sample)
80                }
81                SampleRef::Histogram(_) => {
82                    dropped_histogram = true;
83                    None
84                }
85                SampleRef::Missing => None,
86            });
87        }
88        builder.push(position, &row)?;
89    }
90    let metric = if matches!(comparison, Comparison::Bool(_)) {
91        drop_metric_name(&series.metric)?
92    } else {
93        series.metric.clone()
94    };
95    Ok((builder.finish(metric)?, dropped_histogram))
96}
97
98impl Comparison {
99    /// The output for one `left op right` pair, where `vector` is the vector operand's value.
100    pub(crate) fn apply(self, left: f64, right: f64, vector: f64) -> Option<f64> {
101        match self {
102            Self::Filter(op) => op.apply(left, right).then_some(vector),
103            Self::Bool(op) => Some(f64::from(op.apply(left, right))),
104        }
105    }
106}
107
108impl std::fmt::Display for Comparison {
109    /// The operator as the query wrote it, which is how the existing planner names it in the info
110    /// it records for a dropped histogram sample.
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        let op = match self {
113            Self::Filter(op) | Self::Bool(op) => op,
114        };
115        f.write_str(match op {
116            ComparisonOp::Equal => "==",
117            ComparisonOp::NotEqual => "!=",
118            ComparisonOp::Less => "<",
119            ComparisonOp::LessEqual => "<=",
120            ComparisonOp::Greater => ">",
121            ComparisonOp::GreaterEqual => ">=",
122        })
123    }
124}
125
126impl ComparisonOp {
127    /// Whether `left op right` holds, by the same IEEE rules the kernels use.
128    ///
129    /// Public because a compiler that folds a constant comparison has to fold it with the same
130    /// answer the kernel would compute: NaN satisfies only `NotEqual`, and signed zeros compare
131    /// equal. Defining the six rules a second time is how the folded number and the evaluated one
132    /// would start to disagree.
133    #[inline]
134    pub fn apply(self, left: f64, right: f64) -> bool {
135        match self {
136            Self::Equal => left == right,
137            Self::NotEqual => left != right,
138            Self::Less => left < right,
139            Self::LessEqual => left <= right,
140            Self::Greater => left > right,
141            Self::GreaterEqual => left >= right,
142        }
143    }
144}