feat(promql): compile and run native histogram functions as map operations

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
Dennis Zhuang
2026-10-22 04:04:31 +08:00
parent 0efeae0f1d
commit cc62f32b4a
8 changed files with 239 additions and 42 deletions
+13 -1
View File
@@ -44,6 +44,7 @@ use crate::go_sort;
use crate::grid_series::{
GridSeriesBuilder, LabelSet, METADATA_LABELS, label_set, merge_same_labelset,
};
use crate::map::validate_grid_series;
const BUCKET_LABEL: &str = "le";
@@ -249,7 +250,7 @@ pub fn map_native_histogram(
schema: &Arc<SeriesSchema>,
series: &Series,
) -> Result<Option<Series>> {
grid_axis(series)?;
validate_grid_series(schema, series)?;
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
let mut buckets = Vec::new();
let mut values = vec![None; schema.fields.len()];
@@ -279,6 +280,17 @@ pub fn map_native_histogram(
}
impl NativeHistogramFunction {
/// The PromQL name of the function.
pub fn name(self) -> &'static str {
match self {
Self::Count => "histogram_count",
Self::Sum => "histogram_sum",
Self::Avg => "histogram_avg",
Self::StdDev => "histogram_stddev",
Self::StdVar => "histogram_stdvar",
}
}
fn apply(self, h: &HistogramView<'_>, buckets: &mut Vec<native::NativeBucket>) -> Result<f64> {
Ok(match self {
Self::Count => h.count,
+30
View File
@@ -838,3 +838,33 @@ fn native_histogram_functions_keep_the_runs_of_a_sparse_series() {
);
}
}
/// A series that does not fit the schema is refused, as `map_math` refuses it, rather than read
/// with one cursor per schema field.
#[test]
fn native_histogram_functions_refuse_a_series_that_does_not_fit_the_schema() {
use crate::grid_series::reference::mixed_series;
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 2).unwrap()).unwrap());
let fields = |names: &[&str]| -> Arc<SeriesSchema> {
Arc::new(SeriesSchema {
fields: names
.iter()
.map(|name| FieldSpec {
name: Arc::from(*name),
})
.collect(),
eval_grid: Some(grid.clone()),
})
};
let text = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///";
let input = mixed_series(
&fields(&["value"]),
&Labels::new(),
&Points::new(),
&BTreeMap::from([(0, text.to_string())]),
)
.unwrap();
let wider = fields(&["value", "other"]);
assert!(map_native_histogram(NativeHistogramFunction::Count, &wider, &input).is_err());
}
+1
View File
@@ -204,6 +204,7 @@ fn function(function: RangeFunction) -> String {
fn map_op(op: &MapOp) -> String {
match op {
MapOp::Math(op) => math_op(op),
MapOp::Histogram(function) => function.name().to_string(),
MapOp::Label(rewrite) => rewrite.to_string(),
}
}
+40 -31
View File
@@ -92,6 +92,7 @@ use datatypes::series::{MetricName, SeriesOrdering};
use crate::grid_series::{
GridSample, GridSeriesBuilder, LabelSet, label_set, merge_same_labelset, owned,
};
use crate::histogram_eval::map_native_histogram;
use crate::instant_eval::select_instants;
use crate::map::{drop_metric_name, map_math};
use crate::native::batch::EvaluatedChunk;
@@ -3407,44 +3408,52 @@ impl NativeExecutor {
/// Maps one chunk with `ops`, keeping its axis and its closing.
///
/// Mapping is point-wise over valued positions: a float chunk keeps the rows it came with, and a
/// chunk holding native histograms loses the rows only histograms filled, as math skips them; a
/// position no field fills is not a row of any chunk, and mapping does not invent one. `None` means
/// the operation emptied every position, which yields no chunk at all
/// unless this chunk closed its series: a closing chunk is still handed over, holding no position,
/// because a consumer tells "nothing more here" from "no more input" by that chunk alone.
/// Mapping is point-wise over valued positions: a float chunk keeps the rows it came with under
/// math, a chunk holding native histograms loses the rows only histograms filled, as math skips
/// them, and a histogram function keeps only the rows histograms filled; a position no field fills
/// is not a row of any chunk, and mapping does not invent one. `None` means the operation emptied
/// every position, which yields no chunk at all unless this chunk closed its series: a closing
/// chunk is still handed over, holding no position, because a consumer tells "nothing more here"
/// from "no more input" by that chunk alone.
fn map_chunk(
schema: &SeriesSchema,
schema: &Arc<SeriesSchema>,
chunk: &EvaluatedChunk,
ops: &[MapOp],
) -> Result<Option<EvaluatedChunk>> {
let mut series = chunk.series.clone();
for (index, op) in ops.iter().enumerate() {
match op {
MapOp::Label(rewrite) => rewrite.apply(&mut series.metric)?,
MapOp::Math(math) => match map_math(schema, &series, *math)? {
Some(mapped) => series = mapped,
// `clamp` with `max < min` is the empty vector, and math skips native histograms,
// so a series without a float value has none left: every position it held was
// decided and holds no value now, so there is no row to hand over.
None => {
if !chunk.is_last {
return Ok(None);
}
// The closing chunk names the series the map would have produced, so the
// operations not run still decide its labels.
let mut metric = series.metric;
for op in &ops[index..] {
match op {
MapOp::Label(rewrite) => rewrite.apply(&mut metric)?,
MapOp::Math(_) => metric = drop_metric_name(&metric)?,
}
}
let empty = no_row_series(schema, &series.time, metric)?;
return EvaluatedChunk::try_new(empty, true).map(Some);
}
},
let mapped = match op {
MapOp::Label(rewrite) => {
rewrite.apply(&mut series.metric)?;
continue;
}
MapOp::Math(math) => map_math(schema, &series, *math)?,
MapOp::Histogram(function) => map_native_histogram(*function, schema, &series)?,
};
if let Some(mapped) = mapped {
series = mapped;
continue;
}
// `clamp` with `max < min` is the empty vector, math skips native histograms and a
// histogram function skips floats, so a series left without a value of the kind the
// operation reads has none left: every position it held was decided and holds no value
// now, so there is no row to hand over.
if !chunk.is_last {
return Ok(None);
}
// The closing chunk names the series the map would have produced, so the operations not
// run still decide its labels.
let mut metric = series.metric;
for op in &ops[index..] {
match op {
MapOp::Label(rewrite) => rewrite.apply(&mut metric)?,
MapOp::Math(_) => metric = drop_metric_name(&metric)?,
// `simpleHistogramFunc` drops only the name, not the type and unit.
MapOp::Histogram(_) => metric.remove("__name__"),
}
}
let empty = no_row_series(schema, &series.time, metric)?;
return EvaluatedChunk::try_new(empty, true).map(Some);
}
EvaluatedChunk::try_new(series, chunk.is_last).map(Some)
}
+89
View File
@@ -40,6 +40,7 @@ use super::{
};
use crate::evaluated::EvaluatedChunk;
use crate::grid_series::merge_same_labelset;
use crate::histogram_eval::NativeHistogramFunction;
use crate::instant_eval::select_instants;
use crate::map::MathOp;
use crate::map_label::LabelRewrite;
@@ -6504,6 +6505,94 @@ fn an_emptied_closing_chunk_carries_the_labels_of_the_whole_chain() {
assert_eq!(closing.series.metric.get("both"), Some("-y"));
}
/// A histogram function maps only the positions native histograms hold, dropping the float one
/// between them, and drops the name.
#[test]
fn a_histogram_function_maps_the_histogram_positions() {
let grid = grid(0, 60_000, 3);
let mut builder = HistogramBatchBuilder::new();
let first = push_histogram(&mut builder, 2);
let second = push_histogram(&mut builder, 5);
let table = builder.finish().unwrap();
let histogram = |index| {
Samples::try_from_histogram(UInt32Array::from(vec![index]), Arc::clone(&table)).unwrap()
};
let field = Samples::try_from_chunks(vec![
histogram(first),
Samples::from_float(Float64Array::from(vec![7.0])),
histogram(second),
])
.unwrap();
let series = Series {
metric: named_metric("a", "x"),
time: TimeAxis::Grid(GridRange::try_new(Arc::clone(&grid), 0, 3).unwrap()),
fields: SeriesFields::try_from_vec(vec![field]).unwrap(),
};
let tree = NativeTree::try_new(map_ops(
evaluated_input(Arc::clone(&grid)),
vec![MapOp::Histogram(NativeHistogramFunction::Count)],
))
.unwrap();
let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new());
execution
.push_evaluated(EvaluatedChunk::try_new(series, true).unwrap())
.unwrap();
let chunks = run(&mut execution);
let [chunk] = chunks.as_slice() else {
panic!("expected one chunk, got {}", chunks.len());
};
assert_eq!(chunk.series.metric.name(), None);
assert_eq!(chunk.series.metric.get("job"), Some("x"));
let positions = chunk
.series
.time
.positions()
.map(|(position, _)| position)
.collect::<Vec<_>>();
assert_eq!(positions, vec![0, 2]);
assert_eq!(sample_values(chunk), vec![Some(2.0), Some(5.0)]);
}
/// A histogram function over a closing float chunk empties it, and the closing chunk is named as
/// Prometheus' `simpleHistogramFunc` names its output: without `__name__` but with `__type__`,
/// which math functions drop.
#[test]
fn a_histogram_function_names_an_emptied_closing_chunk_like_its_kernel() {
let grid = grid(0, 60_000, 2);
let schema = evaluated_schema(Arc::clone(&grid));
let metric = MetricName::try_new(
Some("a".into()),
vec![Label {
name: "__type__".into(),
value: "histogram".into(),
}],
)
.unwrap();
let tree = NativeTree::try_new(map_ops(
evaluated_input(Arc::clone(&grid)),
vec![MapOp::Histogram(NativeHistogramFunction::Sum)],
))
.unwrap();
let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new());
execution
.push_evaluated(evaluated_chunk_of(
&schema,
metric,
0,
vec![Some(1.0), Some(2.0)],
true,
))
.unwrap();
let chunks = run(&mut execution);
let [closing] = chunks.as_slice() else {
panic!("expected one closing chunk, got {}", chunks.len());
};
assert!(closing.is_last);
assert_eq!(closing.series.time.len(), 0);
assert_eq!(closing.series.metric.name(), None);
assert_eq!(closing.series.metric.get("__type__"), Some("histogram"));
}
/// A label change reads no value, so a map of label changes alone hands histogram samples and
/// holes over as they came, where a math function would drop them.
#[test]
+5 -2
View File
@@ -35,6 +35,7 @@ use datatypes::series::SeriesOrdering;
use datatypes::series::samples::{FieldSpec, SeriesSchema};
use datatypes::series::time::EvalGrid;
use crate::histogram_eval::NativeHistogramFunction;
use crate::map::MathOp;
use crate::map_label::LabelRewrite;
use crate::range_eval::{RangeFunction, RangeWindow};
@@ -178,11 +179,13 @@ pub struct BoundMap {
pub ops: Arc<[MapOp]>,
}
/// One operation of a map, applied to each series on its own: math over its values, or a change
/// of its labels. Either can give two series one label set, which is why both live in a map.
/// One operation of a map, applied to each series on its own: math over its float values, a
/// function of its native histograms, or a change of its labels. Each can give two series one label
/// set, which is why all live in a map.
#[derive(Clone, Debug)]
pub enum MapOp {
Math(MathOp),
Histogram(NativeHistogramFunction),
Label(Arc<LabelRewrite>),
}
+38 -8
View File
@@ -23,13 +23,14 @@
//! <range function>(<selector>[<range>]) e.g. rate(x[5m])
//! <range function>(<constant>, <selector>[<range>]) e.g. quantile_over_time(0.9, x[5m])
//! <math function>(<expression>[, <constant>]*) e.g. abs(rate(x[5m])), clamp_min(x, 0)
//! <histogram function>(<expression>) e.g. histogram_count(x)
//! <label function>(<expression>, <string>*) e.g. label_replace(x, "a", "$1", "b", "(.*)")
//! ```
//!
//! which become `Input` (raw samples) → `Instant` (the last sample within the statement's lookback),
//! `Input` (raw samples) → `Window` (the range function over the statement's grid) and
//! `<expression>` → `Map` (a pointwise math function or label change over what its argument
//! evaluates to). A
//! `<expression>` → `Map` (a pointwise math function, native histogram function or label change
//! over what its argument evaluates to). A
//! selector may carry `offset` in either selection shape and, in the window shape, an `@` anchor.
//! Everything else is a [`DataFusionError::NotImplemented`] that names what was found and quotes the
//! shapes above, because rejecting a query the compiler does not understand is the only honest
@@ -60,6 +61,7 @@ use datafusion::error::{DataFusionError, Result};
use datatypes::series::SeriesOrdering;
use datatypes::series::samples::SeriesSchema;
use datatypes::series::time::{EvalGrid, GridSpec};
use promql::histogram_eval::NativeHistogramFunction;
use promql::map::{ArithmeticOp, MathOp};
use promql::map_label::LabelRewrite;
use promql::map_time::DateFunction;
@@ -80,9 +82,10 @@ use crate::promql::label_values::signed_millis_since_epoch;
/// The shapes this compiler accepts, quoted in every rejection.
const SUPPORTED: &str = "a selector, a range function over a range selector — \
`<range function>(<selector>[<range>])`, with its constants in front of \
the selector as in `quantile_over_time(0.9, x[5m])` — or a math or label \
function over any of them, as in `abs(rate(x[5m]))`: for example `x`, \
`rate(x[5m])`, `quantile_over_time(0.9, x[5m])` or `abs(rate(x[5m]))`";
the selector as in `quantile_over_time(0.9, x[5m])` — or a math, native \
histogram or label function over any of them, as in \
`abs(rate(x[5m]))`: for example `x`, `rate(x[5m])`, \
`quantile_over_time(0.9, x[5m])` or `abs(rate(x[5m]))`";
/// Compiles `stmt` into a tree that reads `input` and evaluates the statement's expression over it.
///
@@ -162,8 +165,8 @@ fn compile_expr(context: &Context, expr: &PromExpr) -> Result<NativeNode> {
}
}
/// Compiles a call: a range function opens a window over the selector it is given, and a math or
/// label function maps the value of its first argument.
/// Compiles a call: a range function opens a window over the selector it is given, and a math,
/// native histogram or label function maps the value of its first argument.
///
/// The name lists are disjoint, and a range function is decided first because it binds its own
/// window rather than its argument's value. A name in neither list is refused here, which is where
@@ -181,6 +184,16 @@ fn compile_call(context: &Context, call: &Call) -> Result<NativeNode> {
if let Some((op, vector)) = math_op(func.name, &args.args)? {
return map_call(context, func.name, MapOp::Math(op), vector);
}
if let Some(function) = histogram_function(func.name) {
let [vector] = args.args.as_slice() else {
return Err(not_implemented(&format!(
"a call to `{}` with {} argument(s), where it takes its vector",
func.name,
args.args.len()
)));
};
return map_call(context, func.name, MapOp::Histogram(function), vector);
}
if let Some((rewrite, vector)) = label_rewrite(func.name, &args.args)? {
return map_call(context, func.name, MapOp::Label(Arc::new(rewrite)), vector);
}
@@ -224,7 +237,8 @@ fn window_call(
window_selection(context, function, vs, range)
}
/// Wraps `op` over the value of `vector`, which is the first argument of a math or label function.
/// Wraps `op` over the value of `vector`, which is the first argument of a math, native histogram
/// or label function.
///
/// The output is the input's own type: a pointwise function moves no value to another grid point
/// and reports one value per field it was given, so the map's schema is the input's allocation
@@ -659,6 +673,22 @@ fn math_op<'a>(
Ok(Some((op, vector)))
}
/// The native histogram function `name` denotes, or `None` when it is not one.
///
/// These read only native histogram samples and drop the float ones, as Prometheus'
/// `simpleHistogramFunc` does; `histogram_quantile` and `histogram_fraction` also read classic
/// bucket series and are not listed.
fn histogram_function(name: &str) -> Option<NativeHistogramFunction> {
match name {
"histogram_count" => Some(NativeHistogramFunction::Count),
"histogram_sum" => Some(NativeHistogramFunction::Sum),
"histogram_avg" => Some(NativeHistogramFunction::Avg),
"histogram_stddev" => Some(NativeHistogramFunction::StdDev),
"histogram_stdvar" => Some(NativeHistogramFunction::StdVar),
_ => None,
}
}
/// The label change `label_replace` or `label_join` makes, and the vector it is made to, or `None`
/// when `name` is neither.
///
@@ -1195,6 +1195,29 @@ fn label_functions_bind_their_change_into_a_map() {
}
}
/// The native histogram functions bind their kernel into a map over the vector they are given.
#[test]
fn histogram_functions_bind_their_kernel_into_a_map() {
for name in [
"histogram_count",
"histogram_sum",
"histogram_avg",
"histogram_stddev",
"histogram_stdvar",
] {
let query = format!("{name}(x)");
let tree = compile(
&eval_stmt(&query),
raw_schema(),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`{query}` was refused: {error}"));
let display = tree.to_string();
let root = display.lines().nth(1).expect("a compiled tree has a root");
assert_eq!(root, format!(" root Map {name}"), "`{query}`");
}
}
/// An invalid regular expression fails the statement, as it fails Prometheus' evaluation, rather
/// than being left to another path that would fail it the same way.
#[test]