feat(promql): add evaluated series math kernels

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
(cherry picked from commit 93108f3a78)
This commit is contained in:
Lei, HUANG
2026-10-19 15:40:58 +08:00
committed by discord9
parent 50002c6830
commit 7ddf0ef1bc
3 changed files with 43 additions and 60 deletions
+2 -3
View File
@@ -95,9 +95,8 @@ impl Round {
}
}
/// Follows Prometheus `funcRound`: multiplying by the inverse of `nearest` and dividing by it
/// again (not `/ nearest` then `* nearest`) can move a `floor` result by a whole step.
/// `nearest == 0` gives NaN; with a positive `nearest`, ties round towards +Inf.
/// Matches the ordinary PromQL UDF, including NaN for `nearest == 0`.
/// With a positive `nearest`, ties round towards +Inf.
pub(crate) fn round_to_nearest(value: f64, nearest: f64) -> f64 {
let inverse = 1.0 / nearest;
(value * inverse + 0.5).floor() / inverse
+5 -25
View File
@@ -22,7 +22,6 @@ mod tests;
use datafusion::error::{DataFusionError, Result};
use datatypes::arrow::array::Float64Array;
use datatypes::series::MetricName;
use datatypes::series::samples::{DenseSamplesRef, Samples, Series, SeriesFields, SeriesSchema};
use datatypes::series::time::TimeAxis;
@@ -43,8 +42,7 @@ pub enum MathOp {
Round { nearest: f64 },
}
/// Applies float math to every field of one evaluated series and drops the metric name, like
/// Prometheus' `simpleFloatFunc`.
/// Applies float math to every field of one evaluated series, preserving its labels.
///
/// The explicit schema and actual grid range are preserved. Fields are processed in their own
/// chunk boundaries, without expanding to the full grid or densifying chunked samples. Missing
@@ -55,10 +53,6 @@ pub enum MathOp {
/// Raw time axes and histogram/mixed segments are rejected. Unsupported query types must be
/// admitted to the ordinary path before execution; this function neither falls back nor returns
/// partial results.
///
/// Distinct inputs can share a label set once the name is dropped. Merging them, or failing
/// when both have a value at one step, is left to the caller (Prometheus
/// `mergeSeriesWithSameLabelset`).
pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Series> {
if !matches!(series.time, TimeAxis::Grid(_)) {
return Err(DataFusionError::Execution(
@@ -71,24 +65,10 @@ pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Se
.map(|samples| map_samples(samples, op))
.collect::<Result<Vec<_>>>()?;
let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
let metric = drop_metric_name(&series.metric)?;
Series::try_new(schema, metric, series.time.clone(), fields).map_err(series_error)
}
/// Prometheus `DropReserved(schema.IsMetadataLabel)` drops the type and unit labels with the
/// name. Empty values are dropped too: Prometheus has no empty labels, and keeping them would
/// hide a same-labelset collision from the caller.
pub(crate) fn drop_metric_name(metric: &MetricName) -> Result<MetricName> {
// One rebuild: removing labels one by one copies the label array each time.
let tags = metric
.tags()
.iter()
.filter(|label| {
!label.value.is_empty() && !matches!(label.name.as_ref(), "__type__" | "__unit__")
})
.cloned()
.collect();
MetricName::try_new(None, tags).map_err(series_error)
// Ordinary math calls preserve the metric name (unlike binary arithmetic): the HTTP
// adapter's collect_metric_names follows Call arguments. Keep that compatibility here.
Series::try_new(schema, series.metric.clone(), series.time.clone(), fields)
.map_err(series_error)
}
impl MathOp {
+36 -32
View File
@@ -16,6 +16,7 @@ use std::sync::Arc;
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
use datafusion::functions::math;
use datafusion_common::ScalarValue;
use datafusion_common::config::ConfigOptions;
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
use datatypes::arrow::array::{AsArray, UInt32Array};
@@ -31,8 +32,6 @@ use datatypes::series::{Label, MetricName};
use super::*;
use crate::functions::IeeeSqrt;
mod prometheus;
fn schema(names: &[&str]) -> SeriesSchema {
SeriesSchema {
fields: names
@@ -217,9 +216,10 @@ fn short_multifield_slices_keep_absolute_grid_and_labels() {
));
assert_eq!(output.time.timestamp(0), Some(4500));
assert_eq!(output.time.timestamp(2), Some(5500));
// Prometheus drops the name; main keeps it because its HTTP adapter follows Call arguments.
assert_eq!(output.metric.name(), None);
assert_eq!(output.metric.tags(), &input.metric.tags()[1..]);
// Ordinary math calls retain the input metric name: collect_metric_names follows Call
// arguments, and the Prometheus response adapter emits it. Binary arithmetic differs.
assert_eq!(output.metric.name(), Some("requests"));
assert_eq!(output.metric.tags(), input.metric.tags());
assert_eq!(input.metric.name(), Some("requests"));
assert_floats(
input.fields.get(0).unwrap(),
@@ -393,16 +393,19 @@ fn mismatched_schema_and_mutated_field_lengths_return_typed_errors() {
}
fn ordinary_math(op: MathOp, input: Float64Array) -> Float64Array {
// Calibration against main's UDFs, whose values agree with Prometheus for these functions;
// the Prometheus engine's own results are checked in `prometheus`.
// The ordinary planner's UDFs are the compatibility oracle, independent of the native
// dispatcher. Keep these aligned with PromPlanner::create_function_expr.
let number_rows = input.len();
let args = vec![ColumnarValue::Array(Arc::new(input))];
let mut args = vec![ColumnarValue::Array(Arc::new(input))];
let udf = match op {
MathOp::Abs => math::abs(),
MathOp::Ceil => math::ceil(),
MathOp::Floor => math::floor(),
MathOp::Sqrt => Arc::new(IeeeSqrt::scalar_udf()),
MathOp::Round { .. } => unreachable!("round is checked against Prometheus fixtures"),
MathOp::Round { nearest } => {
args.push(ColumnarValue::Scalar(ScalarValue::Float64(Some(nearest))));
Arc::new(Round::scalar_udf())
}
};
let arg_fields = args
.iter()
@@ -449,7 +452,7 @@ fn float_boundary_samples() -> Float64Array {
}
#[test]
fn math_matches_main_udfs_across_float_boundaries() {
fn math_matches_existing_udfs_across_float_and_round_boundaries() {
let input = float_boundary_samples();
let mut schema = schema(&["dense", "chunked"]);
let grid_len = u64::try_from(input.len() + 6).unwrap();
@@ -468,37 +471,38 @@ fn math_matches_main_udfs_across_float_boundaries() {
Samples::try_from_chunks(chunks).unwrap(),
],
);
// Round shares its calculation with the UDF; the Prometheus fixtures check it instead.
let cases = [MathOp::Abs, MathOp::Ceil, MathOp::Floor, MathOp::Sqrt];
let cases = [MathOp::Abs, MathOp::Ceil, MathOp::Floor, MathOp::Sqrt]
.into_iter()
.chain(
[
1.0,
0.0,
-0.0,
0.001,
0.1,
105.0,
-0.5,
f64::MIN_POSITIVE,
f64::from_bits(1),
f64::MAX,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
]
.into_iter()
.map(|nearest| MathOp::Round { nearest }),
);
for op in cases {
let output = map_math(&schema, &series, op).unwrap();
let expected = ordinary_math(op, input.clone()).iter().collect::<Vec<_>>();
for field in output.fields.iter() {
assert_floats(field, &expected);
}
assert_eq!(output.metric.name(), None);
assert_eq!(output.metric.tags(), &series.metric.tags()[1..]);
assert_eq!(output.metric.name(), series.metric.name());
assert_eq!(output.metric.tags(), series.metric.tags());
let TimeAxis::Grid(range) = output.time else {
panic!("lost grid axis")
};
assert_eq!((range.start(), range.len()), (5, input.len()));
}
}
#[test]
fn math_drops_reserved_metadata_and_empty_labels_with_the_name() {
let schema = schema(&["value"]);
let mut input = series(&schema, 0, vec![floats(&[Some(-1.0)])]);
for label in ["__type__", "__unit__", "__other__"] {
input.metric.set(label, "x".into()).unwrap();
}
let output = map_math(&schema, &input, MathOp::Abs).unwrap();
let names = output
.metric
.tags()
.iter()
.map(|label| label.name.as_ref())
.collect::<Vec<_>>();
assert_eq!(output.metric.name(), None);
assert_eq!(names, ["__other__", "host"]);
}