fix(promql): follow Prometheus for reserved labels and histogram points in map math

Two review findings, both about what `map_math` does that Prometheus
`simpleFloatFunc` does not.

It kept `__name__`, `__type__` and `__unit__` on its output. Prometheus drops
them (`DropReserved`, `DropName`), and keeping them is observable:
`abs(last_over_time({__name__=~"a|b"}[5m]))` returned two series where
Prometheus rejects the result because after dropping the name both share a
label set. The metric is now stripped of the reserved labels. Two inputs that
differ only in those labels therefore reach a caller with the same label set,
so the docs say the caller runs `merge_same_labelset`, as the label-rewriting
kernels already require.

It also rejected any field holding a native histogram with `NotImplemented`.
Prometheus maps the float points and skips the histogram ones, and the sample
types are not known at planning time -- `abs(rate(native_histogram[5m]))` only
turns out to hold histograms after evaluation -- so rejecting returned nothing
where Prometheus returns the float points or no series. `map_math` now returns
`Result<Option<Series>>` and takes the shape `map_date` already uses: a fast
path over dense float segments, otherwise a per-point pass through
`GridSeriesBuilder` that skips histograms and reports `None` when no value
survives. The arithmetic itself is one `apply(op, value)`, so the two paths
cannot drift.

Tests now pin the corrected behaviour instead of the old: the name is asserted
dropped (with a `__type__`/`__unit__` case the review pointed out was missing),
histogram points are asserted skipped rather than fatal, and an all-missing
input returns `None`.

Signed-off-by: discord9 <discord9@users.noreply.github.com>
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
discord9
2026-10-19 15:40:58 +08:00
parent 7ddf0ef1bc
commit 09d0fc4b19
2 changed files with 199 additions and 91 deletions
+99 -54
View File
@@ -20,12 +20,16 @@
#[cfg(test)]
mod tests;
use std::sync::Arc;
use datafusion::error::{DataFusionError, Result};
use datatypes::arrow::array::Float64Array;
use datatypes::series::samples::{DenseSamplesRef, Samples, Series, SeriesFields, SeriesSchema};
use datatypes::series::samples::{
DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
};
use datatypes::series::time::TimeAxis;
use crate::functions::Round;
use crate::grid_series::{GridSeriesBuilder, METADATA_LABELS};
/// Float math supported by the evaluated-series kernel.
#[derive(Clone, Copy, Debug)]
@@ -42,66 +46,107 @@ pub enum MathOp {
Round { nearest: f64 },
}
/// Applies float math to every field of one evaluated series, preserving its labels.
/// Applies float math to every field of one evaluated series.
///
/// 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
/// samples stay missing; ordinary NaNs remain values. An empty or all-missing input is valid.
/// This follows Prometheus `simpleFloatFunc`: the metadata labels (`__name__`, `__type__`,
/// `__unit__`) are dropped and only float samples are mapped. Histogram samples are skipped
/// rather than rejected, because a field's sample types are known only at run time
/// (`abs(rate(native_histogram[5m]))` holds histograms only after evaluation); the result is
/// `None` when no float value survives.
///
/// The explicit schema and actual grid range are preserved, except that trailing and leading
/// rows without any value are trimmed when histograms leave holes. Fields are processed in their
/// own chunk boundaries, without expanding to the full grid or densifying chunked samples.
/// Missing samples stay missing; ordinary NaNs remain values.
///
/// Dropping the reserved labels means two input series that differ only in them now share a
/// label set, which Prometheus rejects for one vector. Callers must run
/// [`merge_same_labelset`](crate::grid_series::merge_same_labelset) on the results, as the
/// planning/output layer does for other label-rewriting kernels.
///
/// Eval must resolve raw staleness before calling this kernel. Evaluated samples use validity,
/// not NaN payloads, for missingness: arithmetic can produce the reserved stale bit pattern too.
/// 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.
pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Series> {
if !matches!(series.time, TimeAxis::Grid(_)) {
/// Raw time axes are rejected.
pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Option<Series>> {
let TimeAxis::Grid(range) = &series.time else {
return Err(DataFusionError::Execution(
"Map math requires an evaluated grid time axis".into(),
));
}
let fields = series
.fields
.iter()
.map(|samples| map_samples(samples, op))
.collect::<Result<Vec<_>>>()?;
let fields = SeriesFields::try_from_vec(fields).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 {
fn apply(self, floats: &Float64Array) -> Float64Array {
match self {
Self::Abs => floats.unary(f64::abs),
Self::Ceil => floats.unary(f64::ceil),
Self::Floor => floats.unary(f64::floor),
Self::Sqrt => floats.unary(f64::sqrt),
Self::Round { nearest } => {
floats.unary(|sample| Round::round_to_nearest(sample, nearest))
}
}
}
}
fn map_samples(samples: &Samples, op: MathOp) -> Result<Samples> {
let chunks = samples
.segments()
.iter()
.map(|segment| map_float_segment(segment, op))
.collect::<Result<Vec<_>>>()?;
Samples::try_from_chunks(chunks).map_err(series_error)
}
fn map_float_segment(segment: &Samples, op: MathOp) -> Result<Samples> {
let Some(DenseSamplesRef::Float(floats)) = segment.dense() else {
return Err(DataFusionError::NotImplemented(
"Map math supports only float samples; histogram/mixed samples are not supported"
.into(),
));
};
Ok(Samples::from_float(op.apply(floats)))
let mut metric = series.metric.clone();
metric.remove_all(&METADATA_LABELS);
let all_floats = series.fields.iter().all(|samples| {
samples
.segments()
.iter()
.all(|segment| matches!(segment.dense(), Some(DenseSamplesRef::Float(_))))
});
if all_floats {
// Dense floats can still be entirely null. Prometheus emits no series then, and the
// per-point path below reports the same input as `None`.
if !series
.fields
.iter()
.any(|samples| samples.segments().iter().any(has_float_value))
{
return Ok(None);
}
let fields = series
.fields
.iter()
.map(|samples| {
let segments = samples
.segments()
.iter()
.map(|segment| {
let Some(DenseSamplesRef::Float(floats)) = segment.dense() else {
unreachable!("checked above");
};
Samples::from_float(floats.unary(|value| apply(op, value)))
})
.collect();
Samples::try_from_chunks(segments).map_err(series_error)
})
.collect::<Result<Vec<_>>>()?;
let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
return Series::try_new(schema, metric, series.time.clone(), fields)
.map(Some)
.map_err(series_error);
}
// Histogram samples leave holes, which may move the ends of the series.
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
let mut values = vec![None; series.fields.len()];
for row in 0..range.len() {
for (value, samples) in values.iter_mut().zip(series.fields.iter()) {
*value = match samples.sample(row) {
SampleRef::Float(sample) => Some(apply(op, sample)),
SampleRef::Missing | SampleRef::Histogram(_) => None,
};
}
builder.push(range.start() + row, &values)?;
}
builder.finish(metric)
}
/// The float math `op` applies to one value.
fn apply(op: MathOp, value: f64) -> f64 {
match op {
MathOp::Abs => value.abs(),
MathOp::Ceil => value.ceil(),
MathOp::Floor => value.floor(),
MathOp::Sqrt => value.sqrt(),
MathOp::Round { nearest } => Round::round_to_nearest(value, nearest),
}
}
/// Whether `segment` holds a float value; every segment is dense here.
fn has_float_value(segment: &Samples) -> bool {
let Some(DenseSamplesRef::Float(floats)) = segment.dense() else {
return false;
};
floats.iter().any(|value| value.is_some())
}
fn series_error(error: datatypes::error::Error) -> DataFusionError {
+100 -37
View File
@@ -19,7 +19,7 @@ use datafusion::functions::math;
use datafusion_common::ScalarValue;
use datafusion_common::config::ConfigOptions;
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
use datatypes::arrow::array::{AsArray, UInt32Array};
use datatypes::arrow::array::{AsArray, Float64Array, UInt32Array};
use datatypes::arrow::buffer::NullBuffer;
use datatypes::arrow::datatypes::{DataType, Field, Float64Type};
use datatypes::series::histogram::{
@@ -180,7 +180,7 @@ fn math_preserves_missing_and_uses_ieee_float_semantics() {
),
];
for (op, expected) in cases {
let output = map_math(&schema, &input, op).unwrap();
let output = map_math(&schema, &input, op).unwrap().unwrap();
let expected = expected
.into_iter()
.map(Some)
@@ -191,7 +191,7 @@ fn math_preserves_missing_and_uses_ieee_float_semantics() {
}
#[test]
fn short_multifield_slices_keep_absolute_grid_and_labels() {
fn short_multifield_slices_keep_absolute_grid_and_drop_metadata() {
let schema = schema(&["left", "right"]);
let first = floats(&[Some(99.0), Some(-1.2), None, Some(-3.2), Some(99.0)]);
let second = floats(&[Some(99.0), Some(4.8), Some(-0.0), None, Some(99.0)]);
@@ -205,7 +205,7 @@ fn short_multifield_slices_keep_absolute_grid_and_labels() {
.unwrap(),
];
let input = series(&schema, 7, fields);
let output = map_math(&schema, &input, MathOp::Floor).unwrap();
let output = map_math(&schema, &input, MathOp::Floor).unwrap().unwrap();
let TimeAxis::Grid(range) = &output.time else {
panic!("lost grid axis")
};
@@ -216,9 +216,8 @@ 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));
// 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"));
// Prometheus `simpleFloatFunc` drops the metric name, and only the ordinary labels survive.
assert_eq!(output.metric.name(), None);
assert_eq!(output.metric.tags(), input.metric.tags());
assert_eq!(input.metric.name(), Some("requests"));
assert_floats(
@@ -250,7 +249,40 @@ fn short_multifield_slices_keep_absolute_grid_and_labels() {
}
#[test]
fn empty_and_all_missing_ranges_are_not_expanded() {
fn metadata_labels_are_dropped_like_prometheus_simple_float_func() {
let schema = schema(&["value"]);
let base = series(&schema, 3, vec![floats(&[Some(-3.0), Some(4.0)])]);
let metric = MetricName::try_new(
Some("requests".into()),
vec![
Label {
name: "__type__".into(),
value: "gauge".into(),
},
Label {
name: "__unit__".into(),
value: "seconds".into(),
},
Label {
name: "host".into(),
value: "a".into(),
},
],
)
.unwrap();
let input = Series::try_new(&schema, metric, base.time.clone(), base.fields.clone()).unwrap();
let output = map_math(&schema, &input, MathOp::Abs).unwrap().unwrap();
// `DropReserved` with `DropName`: all three reserved labels go, ordinary labels stay.
assert_eq!(output.metric.name(), None);
assert_eq!(output.metric.get("__type__"), None);
assert_eq!(output.metric.get("__unit__"), None);
assert_eq!(output.metric.get("host"), Some("a"));
assert_eq!(output.metric.tags().len(), 1);
assert_floats(output.fields.get(0).unwrap(), &[Some(3.0), Some(4.0)]);
}
#[test]
fn empty_and_all_missing_ranges_return_no_series() {
let schema = schema(&["value"]);
// Empty at grid end, one missing point, and a longer all-missing range.
for (start, len) in [(64, 0), (9, 1), (2, 4)] {
@@ -262,14 +294,16 @@ fn empty_and_all_missing_ranges_are_not_expanded() {
MathOp::Sqrt,
MathOp::Round { nearest: 0.0 },
] {
let output = map_math(&schema, &input, op).unwrap();
let TimeAxis::Grid(range) = &output.time else {
panic!("lost grid axis")
};
assert_eq!((range.start(), range.len()), (start, len));
assert_floats(output.fields.get(0).unwrap(), &vec![None; len]);
// No point survives, so there is no series to return, as for the builder-based
// kernels; the input range is neither kept nor expanded.
assert!(map_math(&schema, &input, op).unwrap().is_none());
}
}
// NaN is a value: only absent samples make the whole series disappear.
let nan = series(&schema, 2, vec![floats(&[Some(f64::NAN)])]);
let output = map_math(&schema, &nan, MathOp::Abs).unwrap().unwrap();
assert_floats(output.fields.get(0).unwrap(), &[Some(f64::NAN)]);
}
#[test]
@@ -285,7 +319,7 @@ fn evaluated_missingness_depends_on_validity_not_nan_payloads() {
Some(NullBuffer::from(vec![false, true, true])),
))],
);
let output = map_math(&schema, &input, MathOp::Abs).unwrap();
let output = map_math(&schema, &input, MathOp::Abs).unwrap().unwrap();
assert_floats(
output.fields.get(0).unwrap(),
&[None, Some(ordinary_nan), Some(1.0)],
@@ -299,12 +333,12 @@ fn evaluated_missingness_depends_on_validity_not_nan_payloads() {
// must not reinterpret that computed value as a missing sample or reject the evaluated input.
let negative_nan = f64::from_bits(PROMETHEUS_STALE_NAN_BITS | (1_u64 << 63));
let input = series(&schema, 1, vec![floats(&[Some(negative_nan)])]);
let absolute = map_math(&schema, &input, MathOp::Abs).unwrap();
let absolute = map_math(&schema, &input, MathOp::Abs).unwrap().unwrap();
let SampleRef::Float(computed_nan) = absolute.fields.get(0).unwrap().sample(0) else {
panic!("lost computed NaN")
};
assert_eq!(computed_nan.to_bits(), PROMETHEUS_STALE_NAN_BITS);
let rounded = map_math(&schema, &absolute, MathOp::Ceil).unwrap();
let rounded = map_math(&schema, &absolute, MathOp::Ceil).unwrap().unwrap();
assert_floats(rounded.fields.get(0).unwrap(), &[Some(f64::NAN)]);
}
@@ -333,29 +367,58 @@ fn histogram_batch() -> Arc<HistogramBatch> {
}
#[test]
fn histogram_and_mixed_fields_are_rejected_without_partial_success() {
fn histogram_and_mixed_points_are_skipped_instead_of_failing_the_series() {
let batch = histogram_batch();
let histogram = Samples::try_from_histogram(UInt32Array::from(vec![0]), batch.clone()).unwrap();
let null_histogram =
Samples::try_from_histogram(UInt32Array::from(vec![None]), batch.clone()).unwrap();
let one_field = schema(&["value"]);
// A field holding only histogram positions has no float to map, so the series disappears.
for only_histograms in [histogram.clone(), null_histogram] {
let input = series(&one_field, 2, vec![only_histograms]);
assert!(map_math(&one_field, &input, MathOp::Abs).unwrap().is_none());
}
// Prometheus `simpleFloatFunc` maps float points and silently skips histogram points. The
// skipped position becomes missing, which neither moves nor shrinks its neighbours.
let chunked = Samples::try_from_chunks(vec![
floats(&[Some(-1.0)]),
histogram.clone(),
floats(&[Some(-9.0)]),
])
.unwrap();
let mixed = Samples::try_from_mixed(
Float64Array::from(vec![Some(1.0), None]),
HistogramSamples::try_new(UInt32Array::from(vec![None, Some(0)]), batch.clone()).unwrap(),
Float64Array::from(vec![Some(-2.0), None, Some(-3.0)]),
HistogramSamples::try_new(UInt32Array::from(vec![None, Some(0), None]), batch.clone())
.unwrap(),
)
.unwrap();
let null_histogram = Samples::try_from_histogram(UInt32Array::from(vec![None]), batch).unwrap();
let chunks = Samples::try_from_chunks(vec![floats(&[Some(-1.0)]), histogram.clone()]).unwrap();
let schema = schema(&["float", "unsupported"]);
for unsupported in [histogram, mixed, null_histogram, chunks] {
let prefix = floats(&vec![Some(-2.0); unsupported.len()]);
let input = series(&schema, 2, vec![prefix, unsupported]);
assert!(matches!(
map_math(&schema, &input, MathOp::Abs),
Err(DataFusionError::NotImplemented(_))
));
assert_floats(
input.fields.get(0).unwrap(),
&vec![Some(-2.0); input.time.len()],
);
}
let two_fields = schema(&["chunked", "mixed"]);
let input = series(&two_fields, 4, vec![chunked, mixed]);
let output = map_math(&two_fields, &input, MathOp::Abs).unwrap().unwrap();
let TimeAxis::Grid(range) = &output.time else {
panic!("lost grid axis")
};
assert_eq!((range.start(), range.len()), (4, 3));
assert_floats(output.fields.get(0).unwrap(), &[Some(1.0), None, Some(9.0)]);
assert_floats(output.fields.get(1).unwrap(), &[Some(2.0), None, Some(3.0)]);
// A histogram-only field alongside a float field maps the floats and stays all-missing.
let two_fields = schema(&["float", "histogram"]);
let input = series(
&two_fields,
0,
vec![
floats(&[Some(-1.0), Some(-2.0), Some(-3.0)]),
Samples::try_from_histogram(UInt32Array::from(vec![0, 0, 0]), batch).unwrap(),
],
);
let output = map_math(&two_fields, &input, MathOp::Abs).unwrap().unwrap();
assert_floats(
output.fields.get(0).unwrap(),
&[Some(1.0), Some(2.0), Some(3.0)],
);
assert_floats(output.fields.get(1).unwrap(), &[None, None, None]);
}
#[test]
@@ -493,12 +556,12 @@ fn math_matches_existing_udfs_across_float_and_round_boundaries() {
.map(|nearest| MathOp::Round { nearest }),
);
for op in cases {
let output = map_math(&schema, &series, op).unwrap();
let output = map_math(&schema, &series, op).unwrap().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(), series.metric.name());
assert_eq!(output.metric.name(), None);
assert_eq!(output.metric.tags(), series.metric.tags());
let TimeAxis::Grid(range) = output.time else {
panic!("lost grid axis")