diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index 4b7fdba6c54..57803a5e757 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -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, series: &Series, ) -> Result> { - 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) -> Result { Ok(match self { Self::Count => h.count, diff --git a/src/promql/src/histogram_eval/tests.rs b/src/promql/src/histogram_eval/tests.rs index 258e747a4cb..07053a30367 100644 --- a/src/promql/src/histogram_eval/tests.rs +++ b/src/promql/src/histogram_eval/tests.rs @@ -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 { + 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()); +} diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index b5772a34513..b50737b46e0 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -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(), } } diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 633a2f65424..46415a850f2 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -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, chunk: &EvaluatedChunk, ops: &[MapOp], ) -> Result> { 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) } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index bea5c95408c..7e58e642451 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -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::>(); + 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] diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 00c01f4ddec..4b9f43e447e 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -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), } diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index a59ac520b83..08dd0b7228e 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -23,13 +23,14 @@ //! ([]) e.g. rate(x[5m]) //! (, []) e.g. quantile_over_time(0.9, x[5m]) //! ([, ]*) e.g. abs(rate(x[5m])), clamp_min(x, 0) +//! () e.g. histogram_count(x) //!