From 353149cf63dc60f244bf056c4db44655d2617495 Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 04:55:03 +0800 Subject: [PATCH 1/7] feat(promql): run sort and absent in the native select node Signed-off-by: Dennis Zhuang --- src/promql/src/native/display.rs | 28 +++++- src/promql/src/native/display/tests.rs | 20 +++- src/promql/src/native/execute.rs | 121 +++++++++++++++++++------ src/promql/src/native/execute/tests.rs | 109 ++++++++++++++++++++++ src/promql/src/native/plan.rs | 10 +- src/promql/src/select.rs | 38 +++++++- src/promql/src/select/tests.rs | 45 +++++++++ 7 files changed, 338 insertions(+), 33 deletions(-) diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 35ccb27542f..2124f692aec 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -22,8 +22,8 @@ use std::fmt::{self, Write}; use std::sync::Arc; -use datatypes::series::SeriesOrdering; use datatypes::series::time::EvalGrid; +use datatypes::series::{MetricName, SeriesOrdering}; use crate::map::MathOp; use crate::native::metrics::{self, NodePath}; @@ -32,6 +32,7 @@ use crate::native::plan::{ NativeTree, NativeType, }; use crate::range_eval::RangeFunction; +use crate::select::SortOrder; use crate::vector_match::{BinaryOp, Cardinality, FillValues, MatchingLabels}; /// The header line of every tree. @@ -110,6 +111,15 @@ fn describe(node: &NativeNode) -> String { ), BoundSelect::LimitK { k, group } => format!("limitk {k} {}", grouping(group)), BoundSelect::LimitRatio { ratio } => format!("limit_ratio {ratio}"), + BoundSelect::Sort(order) => match order { + SortOrder::Asc => "sort".to_string(), + SortOrder::Desc => "sort_desc".to_string(), + SortOrder::ByLabel(labels) => format!("sort_by_label [{}]", label_list(labels)), + SortOrder::ByLabelDesc(labels) => { + format!("sort_by_label_desc [{}]", label_list(labels)) + } + }, + BoundSelect::Absent { labels } => format!("absent {{{}}}", label_pairs(labels)), }, NativeExpr::Aggregate { op, .. } => format!( "{} {} {}", @@ -255,6 +265,22 @@ fn binary_op(op: BinaryOp) -> &'static str { } } +/// The labels of `metric` as `name="value"` pairs, the metric name first. +fn label_pairs(metric: &MetricName) -> String { + metric + .name() + .map(|name| format!("__name__={name:?}")) + .into_iter() + .chain( + metric + .tags() + .iter() + .map(|tag| format!("{}={:?}", tag.name, tag.value)), + ) + .collect::>() + .join(", ") +} + /// A grouping as `by [labels]` or `without [labels]`. fn grouping(group: &Grouping) -> String { match group { diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 46e9098cf5f..d259ce28eee 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -14,9 +14,9 @@ use std::sync::Arc; -use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridSpec}; +use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::super::plan::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, @@ -24,6 +24,7 @@ use super::super::plan::{ }; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::select::SortOrder; use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; fn grid(start: i64, step: i64, len: u64) -> Arc { @@ -427,6 +428,23 @@ fn a_selection_names_its_binding() { BoundSelect::LimitRatio { ratio: -0.5 }, " root Select limit_ratio -0.5", ), + ( + BoundSelect::Sort(SortOrder::ByLabelDesc(vec!["job".into(), "le".into()])), + " root Select sort_by_label_desc [job, le]", + ), + ( + BoundSelect::Absent { + labels: MetricName::try_new( + None, + vec![Label { + name: "job".into(), + value: "x".into(), + }], + ) + .unwrap(), + }, + r#" root Select absent {job="x"}"#, + ), ]; for (op, line) in lines { let tree = NativeTree::try_new(NativeNode { diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 3e379c1bdb6..66b17c63f97 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -102,7 +102,7 @@ use crate::native::plan::{ BoundInstant, BoundSelect, Grouping, NativeExpr, NativeNode, NativeTree, }; use crate::range_eval::RangeEvaluator; -use crate::select; +use crate::select::{self, SortOrder}; use crate::vector_match::{ BinaryMatching, binary_vectors_with_reservation, validate_binary_operand, }; @@ -1835,15 +1835,15 @@ impl SelectRuntime { assembled.sort_by(|a, b| select::compare_labels(&a.metric, &b.metric)); } buffer.grow(selection_workspace_bytes( + &self.op, + &self.schema, &assembled, - self.schema.fields.len(), ))?; let metrics = Arc::clone(&buffer.metrics); let output = { let _timer = metrics.timer(); - select_series(&self.op, &self.schema, &assembled)? + select_series(&self.op, &self.schema, assembled)? }; - drop(assembled); self.input.release(); self.computed = true; Ok(Some(output)) @@ -1862,7 +1862,7 @@ fn select_overflow(path: &NodePath) -> DataFusionError { fn select_series( op: &BoundSelect, schema: &SeriesSchema, - series: &[Series], + series: Vec, ) -> Result> { let grouping = |group: &Grouping| match group { Grouping::By(labels) => select::Grouping::By(labels.to_vec()), @@ -1870,22 +1870,61 @@ fn select_series( }; match op { BoundSelect::TopK { k, top, group } => { - select::topk(*k, *top, &grouping(group), schema, series) + select::topk(*k, *top, &grouping(group), schema, &series) } - BoundSelect::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, series), - BoundSelect::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, series), + BoundSelect::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, &series), + BoundSelect::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, &series), + // A sort hands back the series it was given, rebuilding only those `sort` and `sort_desc` + // drop histogram samples from. + BoundSelect::Sort(order) => select::sort_instant(order, schema, series), + BoundSelect::Absent { labels } => Ok(select::absent(schema, &series, labels.clone())? + .into_iter() + .collect()), } } -/// A rough estimate of what a selection kernel allocates over `series`, beside the input it reads. +/// A rough estimate of what the selection `op` allocates over `series`, beside the input it reads. +/// Like [`merge_workspace_bytes`] it is not an allocation bound: vector slack and the hash table's +/// own layout are not measured. /// -/// Per row, the `(point, row)` a kept sample is recorded as, the candidate it is ranked as and the -/// value each field rebuilds it into; per series, its place in the label order and its group, its -/// label pairs in the group key, its cursor and the series and field descriptors of its result; and -/// the histograms `limitk` and `limit_ratio` copy into their results, at the widest histogram of -/// each field. Like [`merge_workspace_bytes`] it is not an allocation bound: vector slack and the -/// hash table's own layout are not measured. -fn selection_workspace_bytes(series: &[Series], fields: usize) -> usize { +/// - `topk`, `bottomk`, `limitk` and `limit_ratio`, per row: the `(point, row)` a kept sample is +/// recorded as, the candidate it is ranked as and the value each field rebuilds it into; per +/// series: its place in the label order and its group, its label pairs in the group key, its +/// cursor and the series and field descriptors of its result; and the histograms `limitk` and +/// `limit_ratio` copy into their results, at the widest histogram of each field. +/// - A sort: the value each series is keyed by, and the floats `sort` and `sort_desc` rebuild a +/// series into when it holds histograms; the label sorts move the series they were given. +/// - `absent`: a presence flag and a result value per grid point and field. +fn selection_workspace_bytes(op: &BoundSelect, schema: &SeriesSchema, series: &[Series]) -> usize { + let fields = schema.fields.len(); + match op { + BoundSelect::Sort(order) => { + let rebuilds = matches!(order, SortOrder::Asc | SortOrder::Desc); + return series.iter().fold(0usize, |total, item| { + let floats = if rebuilds + && item + .fields + .iter() + .any(|field| histogram_row_bytes(field).is_some()) + { + item.time.len().saturating_mul(std::mem::size_of::()) + } else { + 0 + }; + total + .saturating_add(std::mem::size_of::<(f64, Series)>()) + .saturating_add(floats) + }); + } + BoundSelect::Absent { .. } => { + let points = schema + .eval_grid + .as_ref() + .map_or(0, |grid| grid.timestamps().len()); + return points.saturating_mul(fields.saturating_mul(1 + std::mem::size_of::())); + } + BoundSelect::TopK { .. } | BoundSelect::LimitK { .. } | BoundSelect::LimitRatio { .. } => {} + } let row = std::mem::size_of::<(usize, usize)>() + std::mem::size_of::<(usize, usize, f64)>() + fields * std::mem::size_of::(); @@ -2326,7 +2365,7 @@ impl NodeRuntime { let Some(output) = output else { return Ok(()); }; - self.queue_results(output) + self.queue_results(output, false) } /// Retains one chunk of a selection's input, reserved for before it is retained, as @@ -2363,29 +2402,42 @@ impl NodeRuntime { /// Runs this node's selection kernel and queues the series it kept. fn compute_select(&mut self, path: &NodePath) -> Result<()> { - let output = { + let (output, shares_input) = { let select = self.select.as_mut().ok_or_else(|| no_select(path))?; - select.compute(path, &mut self.buffer)? + let shares_input = matches!(select.op, BoundSelect::Sort(_)); + (select.compute(path, &mut self.buffer)?, shares_input) }; let Some(output) = output else { return Ok(()); }; - self.queue_results(output) + self.queue_results(output, shares_input) } /// Queues the series a kernel that reads its whole input produced, and settles the reservation /// on the queue. - fn queue_results(&mut self, output: Vec) -> Result<()> { + /// + /// `shares_input` says the series are the assembled input itself, as a sort hands it back: a + /// field there is one slice per input chunk of buffers and histogram tables the chunks shared, + /// so each series is measured the way the input was ([`operand_chunk_bytes`], each table billed + /// once) rather than by the allocations its slices belong to, which would count a buffer once + /// per chunk. + fn queue_results(&mut self, output: Vec, shares_input: bool) -> Result<()> { + let mut tables = HashSet::new(); // The results are queued the way a node that produces a chunk per input queues what it // hands on: the queue is the one source of chunk order and of the bytes queued chunks hold. let mut closed = 0usize; for series in output { // The kernel decided every point of a result series at once, so the one chunk it is // handed over as closes it. + let shared = shares_input.then(|| { + let (fresh, table_bytes) = unbilled_tables(&series, &tables); + tables.extend(fresh); + operand_chunk_bytes(&series).saturating_add(table_bytes) + }); let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?); // The result is already admitted, within the workspace reserved for the kernel. What the // queue keeps is the estimate of the chunk that holds it. - let bytes = chunk.bytes(); + let bytes = shared.unwrap_or_else(|| chunk.bytes()); self.queued.push_back((chunk, bytes)); closed += 1; } @@ -2792,9 +2844,16 @@ impl NativeExecutionState { "the selection at {path} does not produce samples" )) })?; - // `topk`, `bottomk` and `limitk` rank one value per sample, so their kernels - // take one field; `limit_ratio` keeps whole series and takes any number. - if !matches!(op, BoundSelect::LimitRatio { .. }) && schema.fields.len() != 1 { + // `topk`, `bottomk`, `limitk` and the value sorts read one value per sample, + // so their kernels take one field; the others keep or test whole samples and + // take any number. + let one_field = matches!( + op, + BoundSelect::TopK { .. } + | BoundSelect::LimitK { .. } + | BoundSelect::Sort(SortOrder::Asc | SortOrder::Desc) + ); + if one_field && schema.fields.len() != 1 { return Err(not_implemented("multi-field Select", &path)); } runtime.select = Some(SelectRuntime::new(op.clone(), schema)); @@ -2887,8 +2946,16 @@ impl NativeExecutionState { // A selection keeps samples of the series it read, so pieces of one label // set stay pieces: they hold disjoint points, so ranking them apart picks // what ranking the merged series would, and what is above treats them as - // it treats a map's. - holds_shared[index] = input_holds_shared; + // it treats a map's. `absent` is the exception: it answers with one series + // under the labels it was bound to. + let absent = matches!( + expr, + NativeExpr::Select { + op: BoundSelect::Absent { .. }, + .. + } + ); + holds_shared[index] = input_holds_shared && !absent; } NodeTag::Window => { let (drops_metric_name, input_schema) = match expr { diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index a9d762ad816..b77e35e5685 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -48,6 +48,7 @@ use crate::native::plan::{ BoundSelect, BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; +use crate::select::SortOrder; use crate::vector_match::{ BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, reset_visited_pairs, visited_pairs, @@ -6599,3 +6600,111 @@ fn a_binary_node_reads_what_a_selection_kept() { } assert_eq!(decided(&run(&mut execution)), vec![(1, Some(15.0))]); } + +/// `absent` answers where its input holds nothing, under the labels it was bound to, and answers +/// at every point when no series arrives at all. +#[test] +fn absent_answers_where_the_input_holds_nothing() { + let grid = grid(0, 60_000, 3); + let schema = evaluated_schema(Arc::clone(&grid)); + // What `absent_labels` derives from `up{job="x"}`: the name is not one of them. + let labels = MetricName::try_new( + None, + vec![Label { + name: "job".into(), + value: "x".into(), + }], + ) + .unwrap(); + let tree = NativeTree::try_new(select( + evaluated_input(Arc::clone(&grid)), + BoundSelect::Absent { + labels: labels.clone(), + }, + )) + .unwrap(); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("up", "y"), + 1, + vec![Some(0.0)], + true, + )) + .unwrap(); + let chunks = run(&mut execution); + assert_eq!(chunks.len(), 1); + assert_eq!(chunks[0].series.metric, labels); + assert_eq!(decided(&chunks), vec![(0, Some(1.0)), (2, Some(1.0))]); + + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(1.0)), (1, Some(1.0)), (2, Some(1.0))] + ); +} + +/// A sort orders the series of an instant result, and the node hands them over in that order. +#[test] +fn sort_desc_hands_over_series_in_value_order() { + let grid = grid(0, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(select( + evaluated_input(Arc::clone(&grid)), + BoundSelect::Sort(SortOrder::Desc), + )) + .unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (job, value) in [("b", 1.0), ("a", 3.0), ("c", 2.0)] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("m", job), + 0, + vec![Some(value)], + true, + )) + .unwrap(); + } + let jobs: Vec = run(&mut execution) + .iter() + .map(|chunk| chunk.series.metric.get("job").unwrap().to_string()) + .collect(); + assert_eq!(jobs, ["a", "c", "b"]); +} + +/// A sort hands back the assembled input, whose field is one slice per input chunk of one shared +/// buffer: it is queued at what the slices hold, as the input was retained, not at the buffer once +/// per chunk, which here would be ten times the input and more than the pool. +#[test] +fn a_sorted_series_is_queued_at_what_its_slices_hold() { + let points = 1_000; + let grid = grid(0, 60_000, points); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(select( + evaluated_input(Arc::clone(&grid)), + BoundSelect::Sort(SortOrder::ByLabel(vec!["job".into()])), + )) + .unwrap(); + let pool = bounded_pool(48 * 1024); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let values = Float64Array::from((0..points).map(|v| v as f64).collect::>()); + for start in (0..points as usize).step_by(100) { + execution + .push_evaluated(evaluated_array_chunk_of( + &schema, + named_metric("m", "a"), + start, + values.slice(start, 100), + start + 100 == points as usize, + )) + .unwrap(); + // The selection retains each chunk as it arrives, at what its slice holds. + assert!(execution.next_chunk().unwrap().is_none()); + } + let chunks = run(&mut execution); + assert_eq!(decided(&chunks).len(), points as usize); + assert_eq!(pool.reserved(), 0); +} diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 42bd6a0f892..8e827b78819 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -31,12 +31,13 @@ use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; -use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use datatypes::series::time::EvalGrid; +use datatypes::series::{MetricName, SeriesOrdering}; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::select::SortOrder; use crate::vector_match::BinaryMatching; /// What one node produces. @@ -236,6 +237,13 @@ pub enum BoundSelect { /// `limit_ratio`: the series whose label hash falls in the ratio; it keeps whole series, so it /// has no grouping. LimitRatio { ratio: f64 }, + /// `sort`, `sort_desc`, `sort_by_label` and `sort_by_label_desc`: the input's series in another + /// order, which only an instant result shows. `sort` and `sort_desc` also drop histogram + /// samples, in a range result too. + Sort(SortOrder), + /// `absent`: `1` under `labels` at every point where the input holds no sample. The labels are + /// what the compiler derives from the argument's matchers. + Absent { labels: MetricName }, } /// What a node computes. Every variant holds a bound operation, never a name to resolve. diff --git a/src/promql/src/select.rs b/src/promql/src/select.rs index 6645862e097..e88de344778 100644 --- a/src/promql/src/select.rs +++ b/src/promql/src/select.rs @@ -424,20 +424,30 @@ pub fn absent_labels(matchers: &[LabelMatcher]) -> Result { MetricName::try_new(None, labels).map_err(external) } -/// Orders the series of an instant result. A range result is returned unchanged: Prometheus -/// does not sort matrices. +/// Orders the series of an instant result. A range result keeps its order: Prometheus does not +/// sort matrices. +/// +/// `sort` and `sort_desc` drop histogram samples, in a range result too: Prometheus filters them +/// out at every step (`filterFloats`) before it sorts. The label sorts keep every sample. pub fn sort_instant( order: &SortOrder, schema: &SeriesSchema, mut series: Vec, ) -> Result> { let points = grid_points(schema, &series)?; + if matches!(order, SortOrder::Asc | SortOrder::Desc) { + single_field(schema, "sort")?; + let mut floats = Vec::with_capacity(series.len()); + for item in series { + floats.extend(float_samples(schema, item)?); + } + series = floats; + } if points != 1 { return Ok(series); } match order { SortOrder::Asc | SortOrder::Desc => { - single_field(schema, "sort")?; let mut keyed = Vec::with_capacity(series.len()); for item in series { let value = value_at(&item, 0)?; @@ -476,6 +486,28 @@ pub fn sort_instant( } } +/// `series` without its histogram samples, `None` when nothing else is left. One field, as `sort` +/// reads. +fn float_samples(schema: &SeriesSchema, series: Series) -> Result> { + let field = &series.fields.as_slice()[0]; + if !field + .iter() + .any(|sample| matches!(sample, SampleRef::Histogram(_))) + { + return Ok(Some(series)); + } + let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?; + let mut cursor = field.cursor(); + for (point, row) in series.time.positions() { + let value = match cursor.at(row).expect("the axis and the fields are aligned") { + SampleRef::Float(value) => Some(value), + SampleRef::Missing | SampleRef::Histogram(_) => None, + }; + builder.push(point, &[value])?; + } + builder.finish(series.metric) +} + /// Go's `math.NaN()` bit pattern, which Prometheus returns for an undefined scalar. const GO_NAN: f64 = f64::from_bits(0x7FF8_0000_0000_0001); diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index 4433020e2c2..b2492aba577 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -294,6 +294,51 @@ fn topk_skips_histogram_samples() { assert_eq!(kept[0].metric.name(), Some("b")); } +/// `sort` drops histogram samples at every step, as Prometheus' `filterFloats` does, while +/// `sort_by_label` keeps them. +#[test] +fn sort_drops_histogram_samples() { + let histogram = + OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"); + let mixed = |schema: &SeriesSchema, name: &str| { + let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone())).unwrap(); + builder + .push_samples( + 0, + &[Some(GridSample::Histogram(Box::new( + FloatHistogram::try_from_view(&histogram.view()).unwrap(), + )))], + ) + .unwrap(); + if schema.eval_grid.as_ref().unwrap().timestamps().len() > 1 { + builder + .push_samples(1, &[Some(GridSample::Float(2.0))]) + .unwrap(); + } + builder + .finish(metric(&format!("__name__={name}"))) + .unwrap() + .unwrap() + }; + + let instant = schema(1, 1); + let series = vec![ + mixed(&instant, "h"), + build(&instant, metric("__name__=f"), &vec![vec![Some(1.0)]]).unwrap(), + ]; + let sorted = sort_instant(&SortOrder::Asc, &instant, series.clone()).unwrap(); + assert_eq!(sorted.len(), 1); + assert_eq!(sorted[0].metric.name(), Some("f")); + let by_name = sort_instant(&SortOrder::ByLabel(names("__name__")), &instant, series).unwrap(); + assert_eq!(by_name.len(), 2); + + let range = schema(2, 1); + let sorted = sort_instant(&SortOrder::Desc, &range, vec![mixed(&range, "h")]).unwrap(); + assert_eq!(sorted.len(), 1); + let positions: Vec = sorted[0].time.positions().map(|(point, _)| point).collect(); + assert_eq!(positions, [1]); +} + /// A selection hands back the sample it selected, start timestamp included. /// /// `limitk` and `limit_ratio` choose samples rather than compute them, so a histogram that arrives From 3d19a1f3fc0837ffa2b68329b97782ade8af165a Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 05:12:13 +0800 Subject: [PATCH 2/7] feat(promql): compile sort and absent into the native select node Signed-off-by: Dennis Zhuang --- src/query/src/promql/native_compile.rs | 143 ++++++++++++++++++- src/query/src/promql/native_compile/tests.rs | 40 +++++- 2 files changed, 174 insertions(+), 9 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 56ea7445b76..f731c571427 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -23,11 +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. sort_desc(x), sort_by_label(x, "job") +//! absent() e.g. absent(x{job="a"}) //! ``` //! //! 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 -//! `` → `Map` (a pointwise math function over what its argument evaluates to). A +//! `` → `Map` (a pointwise math function over what its argument evaluates to), and +//! `` → `Select` (a sort or `absent`, which read the whole vector). 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 @@ -53,19 +56,22 @@ use std::sync::Arc; use std::time::Duration; use datafusion::error::{DataFusionError, Result}; -use datatypes::series::SeriesOrdering; use datatypes::series::samples::SeriesSchema; use datatypes::series::time::{EvalGrid, GridSpec}; +use datatypes::series::{MetricName, SeriesOrdering}; use promql::map::{ArithmeticOp, MathOp}; use promql::native::plan::{ - BoundInput, BoundInstant, BoundMap, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, + BoundInput, BoundInstant, BoundMap, BoundSelect, BoundWindow, NativeExpr, NativeNode, + NativeTree, NativeType, }; use promql::range_eval::{RangeFunction, RangeWindow}; +use promql::select::{LabelMatcher, MatchOp, SortOrder, absent_labels}; +use promql_parser::label::MatchOp as ParserMatchOp; use promql_parser::parser::token::TokenType; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ AtModifier, Call, EvalStmt, Expr as PromExpr, MatrixSelector, NumberLiteral, Offset, - VectorSelector, token, + StringLiteral, VectorSelector, token, }; use crate::promql::label_values::signed_millis_since_epoch; @@ -73,9 +79,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 — \ `([])`, with its constants in front of \ - the selector as in `quantile_over_time(0.9, x[5m])` — or a math 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 function, \ + a sort or `absent` 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. /// @@ -167,6 +174,9 @@ fn compile_call(context: &Context, call: &Call) -> Result { if let Some(signature) = range_signature(func.name) { return window_call(context, func.name, signature, &args.args); } + if let Some((op, vector)) = select_op(func.name, &args.args)? { + return select_call(context, func.name, op, vector); + } // The name is looked up before the call's arguments are read, so a name this compiler has no // kernel for is refused as such whichever arguments it was given: `pi()` and `time()` have no // vector to map, and the rejection names the name rather than describing a vector they never @@ -247,6 +257,125 @@ fn map_call(context: &Context, name: &str, op: MathOp, vector: &PromExpr) -> Res }) } +/// Wraps the selection `op` over the value of `vector`, which keeps its type as a map does. +fn select_call( + context: &Context, + name: &str, + op: BoundSelect, + vector: &PromExpr, +) -> Result { + if vector.value_type() != ValueType::Vector { + return Err(not_implemented(&format!( + "a call to `{name}` whose first argument is `{vector}`, which is a {}, where the \ + function takes a vector", + vector.value_type() + ))); + } + let input = compile_expr(context, vector)?; + let output = input.output.clone(); + Ok(NativeNode { + expr: NativeExpr::Select { + input: Box::new(input), + op, + }, + output, + }) +} + +/// The selection a sort or `absent` binds, and the vector it reads, or `None` when `name` is +/// neither. +fn select_op<'a>( + name: &str, + arguments: &'a [Box], +) -> Result> { + let order = match name { + "sort" => Some(SortOrder::Asc), + "sort_desc" => Some(SortOrder::Desc), + "sort_by_label" | "sort_by_label_desc" => None, + "absent" => { + let [vector] = arguments else { + return Err(not_implemented(&format!( + "a call to `absent` with {} argument(s)", + arguments.len() + ))); + }; + let labels = absent_labels_of(vector)?; + return Ok(Some((BoundSelect::Absent { labels }, vector))); + } + _ => return Ok(None), + }; + let Some((vector, strings)) = arguments.split_first() else { + return Err(not_implemented(&format!( + "a call to `{name}` with no argument" + ))); + }; + let order = match order { + Some(order) if strings.is_empty() => order, + Some(_) => { + return Err(not_implemented(&format!( + "a call to `{name}` with {} argument(s)", + arguments.len() + ))); + } + None => { + let labels = strings + .iter() + .map(|argument| match unparen(argument) { + PromExpr::StringLiteral(StringLiteral { val }) => Ok(Arc::from(val.as_str())), + other => Err(not_implemented(&format!( + "a call to `{name}` whose argument `{other}` is not a string literal" + ))), + }) + .collect::>>()?; + if name == "sort_by_label" { + SortOrder::ByLabel(labels) + } else { + SortOrder::ByLabelDesc(labels) + } + } + }; + Ok(Some((BoundSelect::Sort(order), vector))) +} + +/// The labels `absent(expr)` answers with, as Prometheus `createLabelsForAbsentFunction` derives +/// them: from the matchers of a vector selector, and none for any other expression. +/// +/// `__field__`, `__schema__` and `__database__` choose what is read rather than match a label, so +/// they are not labels of the answer, as in the existing planner. +fn absent_labels_of(expr: &PromExpr) -> Result { + let PromExpr::VectorSelector(selector) = unparen(expr) else { + return absent_labels(&[]); + }; + if !selector.matchers.or_matchers.is_empty() { + return Err(not_implemented(&format!( + "`absent` over `{selector}`, whose matchers are alternatives" + ))); + } + let matchers = selector + .matchers + .matchers + .iter() + .filter(|matcher| { + !matches!( + matcher.name.as_str(), + "__field__" | "__schema__" | "__database__" + ) + }) + .map(|matcher| LabelMatcher { + name: Arc::from(matcher.name.as_str()), + op: match matcher.op { + ParserMatchOp::Equal => MatchOp::Equal, + ParserMatchOp::NotEqual => MatchOp::NotEqual, + ParserMatchOp::Re(_) => MatchOp::Regex, + ParserMatchOp::NotRe(_) => MatchOp::NotRegex, + }, + value: Arc::from(matcher.value.as_str()), + matches_empty: matcher.is_match(""), + }) + .collect::>(); + absent_labels(&matchers) +} + /// Binds `function` over the range selector `vs[range]` into a window over the raw input. /// /// Both shapes reach this: the range, the offset, the anchor, the grid and the output are the same diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index f16bb74b072..f4d4b990d58 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -826,8 +826,8 @@ fn an_unsupported_shape_is_rejected_and_names_what_it_found() { "a call to `predict_linear`, which has no native kernel", ), ( - "absent(x)", - "a call to `absent`, which has no native kernel", + "scalar(x)", + "a call to `scalar`, which has no native kernel", ), // The two functions PromQL calls with no arguments at all: neither has a kernel, and the // rejection names the name rather than describing a vector they were never given. @@ -1159,3 +1159,39 @@ fn a_math_function_over_a_non_vector_argument_is_refused_and_names_it() { ); } } + +/// The sorts and `absent` bind a selection over the vector they are given. `absent` derives its +/// labels from the selector's matchers as Prometheus does: the first equality of a name sets the +/// label and any other matcher of it removes it, the matchers that accept a missing label read +/// last; `__name__` and the table-choosing matchers are not labels, and any expression other than +/// a selector answers without labels. +#[test] +fn sorts_and_absent_bind_a_selection() { + let cases = [ + ("sort(x)", "sort"), + ("sort_desc(rate(x[5m]))", "sort_desc"), + ( + r#"sort_by_label(x, "job", "le")"#, + "sort_by_label [job, le]", + ), + ( + r#"sort_by_label_desc(x, "job")"#, + "sort_by_label_desc [job]", + ), + ( + r#"absent(x{job="a", env=~"p.*", instance!="", __field__="v"})"#, + r#"absent {job="a"}"#, + ), + // `job!="b"` accepts a missing `job`, so it reads after `job="a"` and removes it. + (r#"absent(x{job!="b", job="a"})"#, "absent {}"), + (r#"absent({__name__="x", job="a"})"#, r#"absent {job="a"}"#), + ("absent(rate(x[5m]))", "absent {}"), + ]; + for (query, op) in cases { + 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 Select {op}"), "`{query}`"); + } +} From 8bc2c8aa55520846ae5a12713b88611a58f0289a Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 05:26:27 +0800 Subject: [PATCH 3/7] feat(promql): run histogram_quantile and histogram_fraction in the native select node Signed-off-by: Dennis Zhuang --- src/promql/src/histogram_eval.rs | 52 +++++++---- src/promql/src/native/display.rs | 7 ++ src/promql/src/native/execute.rs | 39 ++++++-- src/promql/src/native/execute/tests.rs | 97 ++++++++++++++++++++ src/promql/src/native/plan.rs | 9 +- src/query/src/promql/native_compile.rs | 40 ++++++-- src/query/src/promql/native_compile/tests.rs | 10 +- 7 files changed, 217 insertions(+), 37 deletions(-) diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index 4b7fdba6c54..c0df39c012c 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -69,7 +69,18 @@ pub fn evaluate_histograms( schema: &Arc, series: &[Series], ) -> Result> { - let mut groups: HashMap> = HashMap::new(); + // The groups in the order their first member arrived, so the result is in one order on every + // run, as `merge_same_labelset` keeps it. + let mut index: HashMap = HashMap::new(); + let mut groups: Vec> = Vec::new(); + let mut group_of = |metric: MetricName| { + let slot = *index.entry(label_set(&metric)).or_insert_with(|| { + groups.push(Group::new(metric)); + groups.len() - 1 + }); + slot + }; + let mut members: Vec<(usize, Option, &Series)> = Vec::new(); for series in series { grid_axis(series)?; if let Some(upper_bound) = series @@ -79,26 +90,27 @@ pub fn evaluate_histograms( { let mut metric = series.metric.clone(); metric.remove(BUCKET_LABEL); - groups - .entry(label_set(&metric)) - .or_insert_with(|| Group::new(metric)) - .classic - .push((upper_bound, series)); + members.push((group_of(metric), Some(upper_bound), series)); } if has_histograms(series) { - let metric = series.metric.clone(); - let group = groups - .entry(label_set(&metric)) - .or_insert_with(|| Group::new(metric)); - // A label set carries at most one native histogram series: a second one would - // overwrite the first and drop it from the result. - debug_assert!( - group.native.is_none(), - "one label set carries at most one native histogram series; a second one for \ - the same label set means the input handed one label set over as several \ - series, which a gap in the axis is there to avoid" - ); - group.native = Some(series); + members.push((group_of(series.metric.clone()), None, series)); + } + } + for (slot, upper_bound, series) in members { + let group = &mut groups[slot]; + match upper_bound { + Some(upper_bound) => group.classic.push((upper_bound, series)), + None => { + // A label set carries at most one native histogram series: a second one would + // overwrite the first and drop it from the result. + debug_assert!( + group.native.is_none(), + "one label set carries at most one native histogram series; a second one for \ + the same label set means the input handed one label set over as several \ + series, which a gap in the axis is there to avoid" + ); + group.native = Some(series); + } } } @@ -107,7 +119,7 @@ pub fn evaluate_histograms( let mut classic_buckets = Vec::new(); let mut native_buckets = Vec::new(); let mut values = vec![None; schema.fields.len()]; - for mut group in groups.into_values() { + for mut group in groups { // One builder serves every group, so each result series starts explicitly. builder.begin_series(); // The positions any member carries, merged once: the holes no member holds are never diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 2124f692aec..9fd4d98fa41 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -25,6 +25,7 @@ use std::sync::Arc; use datatypes::series::time::EvalGrid; use datatypes::series::{MetricName, SeriesOrdering}; +use crate::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::native::metrics::{self, NodePath}; use crate::native::plan::{ @@ -120,6 +121,12 @@ fn describe(node: &NativeNode) -> String { } }, BoundSelect::Absent { labels } => format!("absent {{{}}}", label_pairs(labels)), + BoundSelect::Histogram(HistogramFunction::Quantile(quantile)) => { + format!("histogram_quantile {quantile}") + } + BoundSelect::Histogram(HistogramFunction::Fraction { lower, upper }) => { + format!("histogram_fraction {lower} {upper}") + } }, NativeExpr::Aggregate { op, .. } => format!( "{} {} {}", diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 66b17c63f97..9616c248d33 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -94,6 +94,7 @@ use datatypes::series::{MetricName, SeriesOrdering}; use crate::grid_series::{ GridSample, GridSeriesBuilder, LabelSet, label_set, merge_same_labelset, owned, }; +use crate::histogram_eval::evaluate_histograms; use crate::instant_eval::select_instants; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; @@ -1861,7 +1862,7 @@ fn select_overflow(path: &NodePath) -> DataFusionError { /// Runs the kernel `op` binds over the whole input. fn select_series( op: &BoundSelect, - schema: &SeriesSchema, + schema: &Arc, series: Vec, ) -> Result> { let grouping = |group: &Grouping| match group { @@ -1877,6 +1878,12 @@ fn select_series( // A sort hands back the series it was given, rebuilding only those `sort` and `sort_desc` // drop histogram samples from. BoundSelect::Sort(order) => select::sort_instant(order, schema, series), + // The kernel groups bucket series by label set and takes one native histogram series per + // set, so pieces of one label set -- an empty tag and an absent one, or what a map folded + // -- are merged first, and two of them holding one point fail as they do elsewhere. + BoundSelect::Histogram(function) => { + evaluate_histograms(*function, schema, &merge_same_labelset(schema, series)?) + } BoundSelect::Absent { labels } => Ok(select::absent(schema, &series, labels.clone())? .into_iter() .collect()), @@ -1895,6 +1902,9 @@ fn select_series( /// - A sort: the value each series is keyed by, and the floats `sort` and `sort_desc` rebuild a /// series into when it holds histograms; the label sorts move the series they were given. /// - `absent`: a presence flag and a result value per grid point and field. +/// - `histogram_quantile` and `histogram_fraction`: the merge of label-set pieces before the kernel +/// ([`merge_workspace_bytes`]); per series, its group entry and label pairs and a cursor per +/// field; per row, the bucket it contributes and a result value per field. fn selection_workspace_bytes(op: &BoundSelect, schema: &SeriesSchema, series: &[Series]) -> usize { let fields = schema.fields.len(); match op { @@ -1923,6 +1933,22 @@ fn selection_workspace_bytes(op: &BoundSelect, schema: &SeriesSchema, series: &[ .map_or(0, |grid| grid.timestamps().len()); return points.saturating_mul(fields.saturating_mul(1 + std::mem::size_of::())); } + BoundSelect::Histogram(_) => { + let rows: usize = series.iter().map(|item| item.time.len()).sum(); + let label = std::mem::size_of::<(Arc, Arc)>(); + let row = std::mem::size_of::<(f64, f64)>() + fields * std::mem::size_of::(); + let per_series = std::mem::size_of::<(f64, &Series)>() + + fields * std::mem::size_of::>(); + return series.iter().fold( + merge_workspace_bytes(rows, series.len(), fields), + |total, item| { + total + .saturating_add(per_series) + .saturating_add((item.metric.tags().len() + 1).saturating_mul(label)) + .saturating_add(item.time.len().saturating_mul(row)) + }, + ); + } BoundSelect::TopK { .. } | BoundSelect::LimitK { .. } | BoundSelect::LimitRatio { .. } => {} } let row = std::mem::size_of::<(usize, usize)>() @@ -2946,16 +2972,17 @@ impl NativeExecutionState { // A selection keeps samples of the series it read, so pieces of one label // set stay pieces: they hold disjoint points, so ranking them apart picks // what ranking the merged series would, and what is above treats them as - // it treats a map's. `absent` is the exception: it answers with one series - // under the labels it was bound to. - let absent = matches!( + // it treats a map's. `absent` answers with one series under the labels it + // was bound to, and the histogram functions merge the label sets they + // answer with, so neither hands over pieces. + let whole = matches!( expr, NativeExpr::Select { - op: BoundSelect::Absent { .. }, + op: BoundSelect::Absent { .. } | BoundSelect::Histogram(_), .. } ); - holds_shared[index] = input_holds_shared && !absent; + holds_shared[index] = input_holds_shared && !whole; } NodeTag::Window => { let (drops_metric_name, input_schema) = match expr { diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index b77e35e5685..792ced48d15 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::HistogramFunction; use crate::instant_eval::select_instants; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; @@ -6708,3 +6709,99 @@ fn a_sorted_series_is_queued_at_what_its_slices_hold() { assert_eq!(decided(&chunks).len(), points as usize); assert_eq!(pool.reserved(), 0); } + +/// `histogram_quantile` reads a classic histogram from the bucket series that share its labels, +/// however they arrived, and answers under those labels without `le` and the name. +#[test] +fn histogram_quantile_reads_the_buckets_of_the_whole_vector() { + let grid = grid(0, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(select( + evaluated_input(Arc::clone(&grid)), + BoundSelect::Histogram(HistogramFunction::Quantile(0.5)), + )) + .unwrap(); + let bucket = |le: &str| { + MetricName::try_new( + Some("m".into()), + vec![ + Label { + name: "job".into(), + value: "a".into(), + }, + Label { + name: "le".into(), + value: le.into(), + }, + ], + ) + .unwrap() + }; + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (le, count) in [("+Inf", 2.0), ("1", 1.0)] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + bucket(le), + 0, + vec![Some(count)], + true, + )) + .unwrap(); + } + let chunks = run(&mut execution); + assert_eq!(chunks.len(), 1); + assert_eq!(chunks[0].series.metric.name(), None); + assert_eq!(chunks[0].series.metric.get("le"), None); + assert_eq!(chunks[0].series.metric.get("job"), Some("a")); + assert_eq!(decided(&chunks), vec![(0, Some(1.0))]); +} + +/// An empty tag and an absent one are one label set, so the two native histogram series below are +/// one series to `histogram_quantile`, answered at both of their points rather than one of them +/// dropped. +#[test] +fn histogram_quantile_reads_the_pieces_of_one_label_set_as_one_series() { + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(select( + evaluated_input(Arc::clone(&grid)), + BoundSelect::Histogram(HistogramFunction::Quantile(0.5)), + )) + .unwrap(); + let metric = |tags: &[(&str, &str)]| { + MetricName::try_new( + Some("m".into()), + tags.iter() + .map(|(name, value)| Label { + name: (*name).into(), + value: (*value).into(), + }) + .collect(), + ) + .unwrap() + }; + let table = histogram_table(2, 4); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (start, tags, index) in [ + (0, vec![("job", "a"), ("zone", "")], 0), + (1, vec![("job", "a")], 1), + ] { + execution + .push_evaluated(evaluated_histogram_chunk_of( + &schema, + metric(&tags), + start, + vec![Some(index)], + &table, + true, + )) + .unwrap(); + } + let chunks = run(&mut execution); + let positions: Vec = decided(&chunks) + .into_iter() + .filter_map(|(position, value)| value.map(|_| position)) + .collect(); + assert_eq!(positions, [0, 1]); +} diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 8e827b78819..92a816dc748 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -35,6 +35,7 @@ use datatypes::series::samples::{FieldSpec, SeriesSchema}; use datatypes::series::time::EvalGrid; use datatypes::series::{MetricName, SeriesOrdering}; +use crate::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; use crate::select::SortOrder; @@ -223,8 +224,9 @@ pub struct BoundAggregate { pub stage: AggregateStage, } -/// An operator that keeps some of the input's samples at each grid point, with their series' labels -/// and values: which samples it keeps depends on the whole vector at that point, not on one series. +/// An operator over the whole input vector at each grid point: one that keeps some of the input's +/// samples with their series' labels and values, orders the series, reports where none is present, +/// or reads a classic histogram from its bucket series. /// /// Its constants are bound here, as a window's are: a `k` or a ratio only known at run time has no /// field. @@ -244,6 +246,9 @@ pub enum BoundSelect { /// `absent`: `1` under `labels` at every point where the input holds no sample. The labels are /// what the compiler derives from the argument's matchers. Absent { labels: MetricName }, + /// `histogram_quantile` or `histogram_fraction`: each classic histogram is read from the bucket + /// series that share its labels, so this too reads the whole vector at a point. + Histogram(HistogramFunction), } /// What a node computes. Every variant holds a bound operation, never a name to resolve. diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index f731c571427..64cf5ca1b11 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -25,12 +25,14 @@ //! ([, ]*) e.g. abs(rate(x[5m])), clamp_min(x, 0) //! ([, ]*) e.g. sort_desc(x), sort_by_label(x, "job") //! absent() e.g. absent(x{job="a"}) +//! (+, ) e.g. histogram_quantile(0.9, rate(x[5m])) //! ``` //! //! 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 //! `` → `Map` (a pointwise math function over what its argument evaluates to), and -//! `` → `Select` (a sort or `absent`, which read the whole vector). A +//! `` → `Select` (a sort, `absent` or a classic histogram function, which read the +//! whole vector). 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 @@ -59,6 +61,7 @@ use datafusion::error::{DataFusionError, Result}; use datatypes::series::samples::SeriesSchema; use datatypes::series::time::{EvalGrid, GridSpec}; use datatypes::series::{MetricName, SeriesOrdering}; +use promql::histogram_eval::HistogramFunction; use promql::map::{ArithmeticOp, MathOp}; use promql::native::plan::{ BoundInput, BoundInstant, BoundMap, BoundSelect, BoundWindow, NativeExpr, NativeNode, @@ -80,9 +83,9 @@ use crate::promql::label_values::signed_millis_since_epoch; const SUPPORTED: &str = "a selector, a range function over a range selector — \ `([])`, with its constants in front of \ the selector as in `quantile_over_time(0.9, x[5m])` — or a math function, \ - a sort or `absent` 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]))`"; + a sort, `absent` or a histogram 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. /// @@ -266,7 +269,7 @@ fn select_call( ) -> Result { if vector.value_type() != ValueType::Vector { return Err(not_implemented(&format!( - "a call to `{name}` whose first argument is `{vector}`, which is a {}, where the \ + "a call to `{name}` whose vector argument is `{vector}`, which is a {}, where the \ function takes a vector", vector.value_type() ))); @@ -282,8 +285,8 @@ fn select_call( }) } -/// The selection a sort or `absent` binds, and the vector it reads, or `None` when `name` is -/// neither. +/// The selection a sort, `absent` or a classic histogram function binds, and the vector it reads, +/// or `None` when `name` is none of them. fn select_op<'a>( name: &str, arguments: &'a [Box], @@ -292,6 +295,29 @@ fn select_op<'a>( "sort" => Some(SortOrder::Asc), "sort_desc" => Some(SortOrder::Desc), "sort_by_label" | "sort_by_label_desc" => None, + "histogram_quantile" | "histogram_fraction" => { + let Some((vector, constants)) = arguments.split_last() else { + return Err(not_implemented(&format!( + "a call to `{name}` with no argument" + ))); + }; + let function = match constants { + [quantile] if name == "histogram_quantile" => { + HistogramFunction::Quantile(constant_argument(name, quantile, 0)?) + } + [lower, upper] if name == "histogram_fraction" => HistogramFunction::Fraction { + lower: constant_argument(name, lower, 0)?, + upper: constant_argument(name, upper, 1)?, + }, + _ => { + return Err(not_implemented(&format!( + "a call to `{name}` with {} argument(s)", + arguments.len() + ))); + } + }; + return Ok(Some((BoundSelect::Histogram(function), vector))); + } "absent" => { let [vector] = arguments else { return Err(not_implemented(&format!( diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index f4d4b990d58..f6991e29988 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -1160,13 +1160,14 @@ fn a_math_function_over_a_non_vector_argument_is_refused_and_names_it() { } } -/// The sorts and `absent` bind a selection over the vector they are given. `absent` derives its +/// The sorts, `absent` and the classic histogram functions bind a selection over the vector they +/// are given, the histogram functions with their constants folded. `absent` derives its /// labels from the selector's matchers as Prometheus does: the first equality of a name sets the /// label and any other matcher of it removes it, the matchers that accept a missing label read /// last; `__name__` and the table-choosing matchers are not labels, and any expression other than /// a selector answers without labels. #[test] -fn sorts_and_absent_bind_a_selection() { +fn whole_vector_functions_bind_a_selection() { let cases = [ ("sort(x)", "sort"), ("sort_desc(rate(x[5m]))", "sort_desc"), @@ -1185,6 +1186,11 @@ fn sorts_and_absent_bind_a_selection() { // `job!="b"` accepts a missing `job`, so it reads after `job="a"` and removes it. (r#"absent(x{job!="b", job="a"})"#, "absent {}"), (r#"absent({__name__="x", job="a"})"#, r#"absent {job="a"}"#), + ( + "histogram_quantile(1 - 0.1, rate(x[5m]))", + "histogram_quantile 0.9", + ), + ("histogram_fraction(0, 0.5, x)", "histogram_fraction 0 0.5"), ("absent(rate(x[5m]))", "absent {}"), ]; for (query, op) in cases { From 7e0325780eebaaf20fed13b3d5a403628a31cb86 Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 05:40:15 +0800 Subject: [PATCH 4/7] chore(promql): return the group slot directly Signed-off-by: Dennis Zhuang --- src/promql/src/histogram_eval.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index c0df39c012c..464fc0251cd 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -74,11 +74,10 @@ pub fn evaluate_histograms( let mut index: HashMap = HashMap::new(); let mut groups: Vec> = Vec::new(); let mut group_of = |metric: MetricName| { - let slot = *index.entry(label_set(&metric)).or_insert_with(|| { + *index.entry(label_set(&metric)).or_insert_with(|| { groups.push(Group::new(metric)); groups.len() - 1 - }); - slot + }) }; let mut members: Vec<(usize, Option, &Series)> = Vec::new(); for series in series { From b7dfb8ec3d36c351de8f4488ff3fef1bedf45079 Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 14:00:38 +0800 Subject: [PATCH 5/7] fix(promql): keep a shared histogram table charged until the last queued result leaves Signed-off-by: Dennis Zhuang --- src/promql/src/native/execute.rs | 40 ++++++++++---- src/promql/src/native/execute/tests.rs | 74 ++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 9 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 1c0596a1f73..b4147bdab6e 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -2114,6 +2114,10 @@ struct NodeRuntime { /// uses it for both. A chunk is measured once, as it enters, and the figure it was queued with /// is given back as it leaves, so neither the queue nor the handover walks it. queued: VecDeque<(NativeChunk, usize)>, + /// The histogram tables queued results share with each other, charged to the queue as a whole + /// rather than to one result: a table stays alive while any result referencing it is queued, + /// so its charge is given back when the queue empties, not when the first result leaves. + queued_tables: usize, /// What an instant node holds: the chunks of the series it is selecting, and, while it gathers /// that series, the workspace the gather reserved for. `None` for every other kind of node. instant: Option, @@ -2190,6 +2194,7 @@ impl NodeRuntime { // hold it. let _timer = metrics.timer(); self.buffer.shrink(bytes)?; + self.release_queued_tables()?; } metrics.record_output(1, values(&chunk)); // An evaluated chunk is addressed on its grid, so its decided positions are grid points; a @@ -2427,9 +2432,10 @@ impl NodeRuntime { /// /// `shares_input` says the series are the assembled input itself, as a sort hands it back: a /// field there is one slice per input chunk of buffers and histogram tables the chunks shared, - /// so each series is measured the way the input was ([`operand_chunk_bytes`], each table billed - /// once) rather than by the allocations its slices belong to, which would count a buffer once - /// per chunk. + /// so each series is measured the way the input was ([`operand_chunk_bytes`]) rather than by + /// the allocations its slices belong to, which would count a buffer once per chunk. The tables + /// are billed once, to the queue ([`NodeRuntime::queued_tables`]), since several results can + /// keep one alive. fn queue_results(&mut self, output: Vec, shares_input: bool) -> Result<()> { let mut tables = HashSet::new(); // The results are queued the way a node that produces a chunk per input queues what it @@ -2441,7 +2447,8 @@ impl NodeRuntime { let shared = shares_input.then(|| { let (fresh, table_bytes) = unbilled_tables(&series, &tables); tables.extend(fresh); - operand_chunk_bytes(&series).saturating_add(table_bytes) + self.queued_tables = self.queued_tables.saturating_add(table_bytes); + operand_chunk_bytes(&series) }); let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?); // The result is already admitted, within the workspace reserved for the kernel. What the @@ -2460,7 +2467,9 @@ impl NodeRuntime { let queued = self .queued .iter() - .fold(0usize, |total, (_, bytes)| total.saturating_add(*bytes)); + .fold(self.queued_tables, |total, (_, bytes)| { + total.saturating_add(*bytes) + }); self.buffer.resize(queued) } @@ -2622,9 +2631,19 @@ impl NodeRuntime { return Ok(None); }; self.buffer.shrink(bytes)?; + self.release_queued_tables()?; Ok(Some(chunk)) } + /// Gives back the shared tables' charge once no queued result references them. + fn release_queued_tables(&mut self) -> Result<()> { + if self.queued.is_empty() && self.queued_tables > 0 { + self.buffer + .shrink(std::mem::take(&mut self.queued_tables))?; + } + Ok(()) + } + /// Records what this node hands out under its output label set. /// /// A node that rewrites labels is where two input series become indistinguishable, so this is @@ -2666,6 +2685,7 @@ impl NodeRuntime { self.open_source_series = false; self.queued.clear(); self.queued.shrink_to_fit(); + self.queued_tables = 0; // The reservation is returned once, below, for everything this node still held. self.buffer.release(); } @@ -2757,6 +2777,7 @@ impl NativeExecutionState { let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), + queued_tables: 0, instant: None, window: None, map: None, @@ -2963,10 +2984,11 @@ impl NativeExecutionState { _ => None, }; let limitk = matches!(op, Some(BoundVectorOp::LimitK { .. })); - if limitk && input_holds_shared { - if let Some(vector) = runtimes[index].vector.as_mut() { - vector.merge_input = true; - } + if limitk + && input_holds_shared + && let Some(vector) = runtimes[index].vector.as_mut() + { + vector.merge_input = true; } let whole = limitk || matches!(op, Some(BoundVectorOp::Absent { .. })); holds_shared[index] = input_holds_shared && !whole; diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 4174e8da22b..bdc428aca96 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -479,6 +479,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { pool, ), queued: VecDeque::new(), + queued_tables: 0, instant: None, window: None, map: None, @@ -496,6 +497,7 @@ fn binary_runtime(pool: &Arc, schema: &Arc) -> Nod NodeRuntime { buffer: NodeBuffer::new(&NodePath::root(), Arc::new(NodeMetrics::default()), pool), queued: VecDeque::new(), + queued_tables: 0, instant: None, window: None, map: None, @@ -6705,3 +6707,75 @@ fn a_sorted_series_is_queued_at_what_its_slices_hold() { assert_eq!(decided(&chunks).len(), points as usize); assert_eq!(pool.reserved(), 0); } + +/// Two sorted results share one histogram table, so the table stays charged until the second one +/// leaves, not only until the first one does. +#[test] +fn a_table_shared_by_queued_results_stays_charged_until_the_last_leaves() { + let grid = grid(0, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::Sort(SortOrder::ByLabel(vec!["job".into()])), + )) + .unwrap(); + let table = histogram_table(2, 64); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + for (job, index) in [("a", 0), ("b", 1)] { + execution + .push_evaluated(evaluated_histogram_chunk_of( + &schema, + named_metric("m", job), + 0, + vec![Some(index)], + &table, + true, + )) + .unwrap(); + } + execution.end_of_input().unwrap(); + let first = execution.next_chunk().unwrap().expect("two sorted results"); + assert_eq!(first.series.metric.get("job"), Some("a")); + drop(first); + assert!(pool.reserved() >= histogram_table_bytes(&table)); + let second = execution.next_chunk().unwrap().expect("two sorted results"); + assert_eq!(second.series.metric.get("job"), Some("b")); + assert!(execution.next_chunk().unwrap().is_none()); + assert_eq!(pool.reserved(), 0); +} + +/// `limitk` takes the order a sort below it decided: `sort_desc` puts `{job="z"}` first, so it is +/// the one `limitk(1, ...)` keeps, although `{job="a"}` sorts first by label. +#[test] +fn limitk_keeps_the_order_a_sort_below_it_decided() { + let grid = grid(0, 60_000, 1); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(vector_op( + vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::Sort(SortOrder::Desc), + ), + BoundVectorOp::LimitK { + k: 1.0, + group: Grouping::By(Arc::from([])), + }, + )) + .unwrap(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + for (job, value) in [("a", 1.0), ("z", 2.0)] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("v", job), + 0, + vec![Some(value)], + true, + )) + .unwrap(); + } + assert_eq!( + decided_by_job(&run(&mut execution)), + vec![("z".to_string(), vec![(0, Some(2.0))])] + ); +} From abb55be608447de3d3050c0378536fcc8fa6b70a Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 14:05:38 +0800 Subject: [PATCH 6/7] refactor(promql): follow the Vector rename in the compiler Signed-off-by: Dennis Zhuang --- src/query/src/promql/native_compile.rs | 26 ++++++++++---------- src/query/src/promql/native_compile/tests.rs | 6 ++--- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index f731c571427..981fbff54bd 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -30,7 +30,7 @@ //! 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 //! `` → `Map` (a pointwise math function over what its argument evaluates to), and -//! `` → `Select` (a sort or `absent`, which read the whole vector). A +//! `` → `Vector` (a sort or `absent`, which read the whole vector). 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 @@ -61,7 +61,7 @@ use datatypes::series::time::{EvalGrid, GridSpec}; use datatypes::series::{MetricName, SeriesOrdering}; use promql::map::{ArithmeticOp, MathOp}; use promql::native::plan::{ - BoundInput, BoundInstant, BoundMap, BoundSelect, BoundWindow, NativeExpr, NativeNode, + BoundInput, BoundInstant, BoundMap, BoundVectorOp, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, }; use promql::range_eval::{RangeFunction, RangeWindow}; @@ -174,8 +174,8 @@ fn compile_call(context: &Context, call: &Call) -> Result { if let Some(signature) = range_signature(func.name) { return window_call(context, func.name, signature, &args.args); } - if let Some((op, vector)) = select_op(func.name, &args.args)? { - return select_call(context, func.name, op, vector); + if let Some((op, vector)) = vector_op(func.name, &args.args)? { + return vector_call(context, func.name, op, vector); } // The name is looked up before the call's arguments are read, so a name this compiler has no // kernel for is refused as such whichever arguments it was given: `pi()` and `time()` have no @@ -257,11 +257,11 @@ fn map_call(context: &Context, name: &str, op: MathOp, vector: &PromExpr) -> Res }) } -/// Wraps the selection `op` over the value of `vector`, which keeps its type as a map does. -fn select_call( +/// Wraps the vector operation `op` over the value of `vector`, which keeps its type as a map does. +fn vector_call( context: &Context, name: &str, - op: BoundSelect, + op: BoundVectorOp, vector: &PromExpr, ) -> Result { if vector.value_type() != ValueType::Vector { @@ -274,7 +274,7 @@ fn select_call( let input = compile_expr(context, vector)?; let output = input.output.clone(); Ok(NativeNode { - expr: NativeExpr::Select { + expr: NativeExpr::Vector { input: Box::new(input), op, }, @@ -282,12 +282,12 @@ fn select_call( }) } -/// The selection a sort or `absent` binds, and the vector it reads, or `None` when `name` is +/// The vector operation a sort or `absent` binds, and the vector it reads, or `None` when `name` is /// neither. -fn select_op<'a>( +fn vector_op<'a>( name: &str, arguments: &'a [Box], -) -> Result> { +) -> Result> { let order = match name { "sort" => Some(SortOrder::Asc), "sort_desc" => Some(SortOrder::Desc), @@ -300,7 +300,7 @@ fn select_op<'a>( ))); }; let labels = absent_labels_of(vector)?; - return Ok(Some((BoundSelect::Absent { labels }, vector))); + return Ok(Some((BoundVectorOp::Absent { labels }, vector))); } _ => return Ok(None), }; @@ -334,7 +334,7 @@ fn select_op<'a>( } } }; - Ok(Some((BoundSelect::Sort(order), vector))) + Ok(Some((BoundVectorOp::Sort(order), vector))) } /// The labels `absent(expr)` answers with, as Prometheus `createLabelsForAbsentFunction` derives diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index f4d4b990d58..53adbcb0ea1 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -1160,13 +1160,13 @@ fn a_math_function_over_a_non_vector_argument_is_refused_and_names_it() { } } -/// The sorts and `absent` bind a selection over the vector they are given. `absent` derives its +/// The sorts and `absent` bind a vector operation over the vector they are given. `absent` derives its /// labels from the selector's matchers as Prometheus does: the first equality of a name sets the /// label and any other matcher of it removes it, the matchers that accept a missing label read /// last; `__name__` and the table-choosing matchers are not labels, and any expression other than /// a selector answers without labels. #[test] -fn sorts_and_absent_bind_a_selection() { +fn sorts_and_absent_bind_a_vector_operation() { let cases = [ ("sort(x)", "sort"), ("sort_desc(rate(x[5m]))", "sort_desc"), @@ -1192,6 +1192,6 @@ fn sorts_and_absent_bind_a_selection() { .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 Select {op}"), "`{query}`"); + assert_eq!(root, format!(" root Vector {op}"), "`{query}`"); } } From f067b252da9097353a898c41523f8e9c84d60b1f Mon Sep 17 00:00:00 2001 From: Dennis Zhuang Date: Thu, 22 Oct 2026 18:31:31 +0800 Subject: [PATCH 7/7] fix(promql): read the grid length from its spec now that timestamps are deferred Signed-off-by: Dennis Zhuang --- src/promql/src/native/execute.rs | 7 +++---- src/promql/src/select/tests.rs | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 0251bcc2861..7046d675377 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -1948,10 +1948,9 @@ fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[S }); } BoundVectorOp::Absent { .. } => { - let points = schema - .eval_grid - .as_ref() - .map_or(0, |grid| grid.timestamps().len()); + let points = schema.eval_grid.as_ref().map_or(0, |grid| { + usize::try_from(grid.spec().len).unwrap_or(usize::MAX) + }); return points.saturating_mul(fields.saturating_mul(1 + std::mem::size_of::())); } BoundVectorOp::TopK { .. } diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index b2492aba577..c8d9d7e2366 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -310,7 +310,7 @@ fn sort_drops_histogram_samples() { )))], ) .unwrap(); - if schema.eval_grid.as_ref().unwrap().timestamps().len() > 1 { + if schema.eval_grid.as_ref().unwrap().spec().len > 1 { builder .push_samples(1, &[Some(GridSample::Float(2.0))]) .unwrap();