diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index d38b860c99d..7b8668b5163 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -97,7 +97,17 @@ 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| { + *index.entry(label_set(&metric)).or_insert_with(|| { + groups.push(Group::new(metric)); + groups.len() - 1 + }) + }; + let mut members: Vec<(usize, Option, &Series)> = Vec::new(); for series in series { grid_axis(series)?; if let Some(upper_bound) = series @@ -107,26 +117,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); + } } } @@ -135,7 +146,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 207a36be9dd..7253c8676e3 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -22,9 +22,10 @@ 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::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::native::metrics::{self, NodePath}; use crate::native::plan::{ @@ -32,6 +33,7 @@ use crate::native::plan::{ NativeNode, 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 +112,21 @@ fn describe(node: &NativeNode) -> String { ), BoundVectorOp::LimitK { k, group } => format!("limitk {k} {}", grouping(group)), BoundVectorOp::LimitRatio { ratio } => format!("limit_ratio {ratio}"), + BoundVectorOp::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)) + } + }, + BoundVectorOp::Absent { labels } => format!("absent {{{}}}", label_pairs(labels)), + BoundVectorOp::Histogram(HistogramFunction::Quantile(quantile)) => { + format!("histogram_quantile {quantile}") + } + BoundVectorOp::Histogram(HistogramFunction::Fraction { lower, upper }) => { + format!("histogram_fraction {lower} {upper}") + } }, NativeExpr::Aggregate { op, .. } => format!( "{} {} [{}] {}", @@ -283,6 +300,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 cf39e413173..03319a0d943 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, @@ -25,6 +25,7 @@ use super::super::plan::{ use crate::map::MathOp; use crate::native::plan::MapOp; 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 { @@ -428,6 +429,23 @@ fn a_vector_operation_names_its_binding() { BoundVectorOp::LimitRatio { ratio: -0.5 }, " root Vector limit_ratio -0.5", ), + ( + BoundVectorOp::Sort(SortOrder::ByLabelDesc(vec!["job".into(), "le".into()])), + " root Vector sort_by_label_desc [job, le]", + ), + ( + BoundVectorOp::Absent { + labels: MetricName::try_new( + None, + vec![Label { + name: "job".into(), + value: "x".into(), + }], + ) + .unwrap(), + }, + r#" root Vector 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 e04ed6ad94e..31fbf028798 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -104,6 +104,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::{ ArithmeticOp, Comparison, ComparisonOp, ScalarOperand, drop_metric_name, map_arithmetic, @@ -116,7 +117,7 @@ use crate::native::plan::{ NativeType, }; use crate::range_eval::RangeEvaluator; -use crate::select; +use crate::select::{self, SortOrder}; use crate::vector_match::{ BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, binary_vectors_with_reservation, validate_binary_operand, @@ -1869,13 +1870,12 @@ impl VectorRuntime { } else { assembled }; - buffer.grow(vector_workspace_bytes(&assembled, self.schema.fields.len()))?; + buffer.grow(vector_workspace_bytes(&self.op, &self.schema, &assembled))?; let metrics = Arc::clone(&buffer.metrics); let output = { let _timer = metrics.timer(); - vector_series(&self.op, &self.schema, &assembled)? + vector_series(&self.op, &self.schema, assembled)? }; - drop(assembled); self.input.release(); self.computed = true; Ok(Some(output)) @@ -1893,8 +1893,8 @@ fn vector_overflow(path: &NodePath) -> DataFusionError { /// Runs the kernel `op` binds over the whole input. fn vector_series( op: &BoundVectorOp, - schema: &SeriesSchema, - series: &[Series], + schema: &Arc, + series: Vec, ) -> Result> { let grouping = |group: &Grouping| match group { Grouping::By(labels) => select::Grouping::By(labels.to_vec()), @@ -1902,22 +1902,87 @@ fn vector_series( }; match op { BoundVectorOp::TopK { k, top, group } => { - select::topk(*k, *top, &grouping(group), schema, series) + select::topk(*k, *top, &grouping(group), schema, &series) } - BoundVectorOp::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, series), - BoundVectorOp::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, series), + BoundVectorOp::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, &series), + BoundVectorOp::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. + BoundVectorOp::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. + BoundVectorOp::Histogram(function) => { + evaluate_histograms(*function, schema, &merge_same_labelset(schema, series)?) + } + BoundVectorOp::Absent { labels } => Ok(select::absent(schema, &series, labels.clone())? + .into_iter() + .collect()), } } -/// A rough estimate of what a vector kernel allocates over `series`, beside the input it reads. +/// A rough estimate of what the vector operation `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 vector_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. +/// - `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 vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[Series]) -> usize { + let fields = schema.fields.len(); + match op { + BoundVectorOp::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) + }); + } + BoundVectorOp::Absent { .. } => { + 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::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)) + }, + ); + } + BoundVectorOp::TopK { .. } + | BoundVectorOp::LimitK { .. } + | BoundVectorOp::LimitRatio { .. } => {} + } let row = std::mem::size_of::<(usize, usize)>() + std::mem::size_of::<(usize, usize, f64)>() + fields * std::mem::size_of::(); @@ -2178,6 +2243,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, @@ -2264,6 +2333,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 @@ -2510,7 +2580,7 @@ impl NodeRuntime { let Some(output) = output else { return Ok(()); }; - self.queue_results(output) + self.queue_results(output, false) } /// Retains one chunk of a vector node's input, reserved for before it is retained, as @@ -2547,29 +2617,44 @@ impl NodeRuntime { /// Runs this node's vector kernel and queues the series it kept. fn compute_vector(&mut self, path: &NodePath) -> Result<()> { - let output = { + let (output, shares_input) = { let vector = self.vector.as_mut().ok_or_else(|| no_vector(path))?; - vector.compute(path, &mut self.buffer)? + let shares_input = matches!(vector.op, BoundVectorOp::Sort(_)); + (vector.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`]) 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 // 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); + 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 // 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; } @@ -2583,7 +2668,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) } @@ -2745,9 +2832,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 @@ -2790,6 +2887,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(); } @@ -2884,6 +2982,7 @@ impl NativeExecutionState { let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), + queued_tables: 0, instant: None, window: None, map: None, @@ -2993,14 +3092,21 @@ impl NativeExecutionState { "the vector operation 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, BoundVectorOp::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, + BoundVectorOp::TopK { .. } + | BoundVectorOp::LimitK { .. } + | BoundVectorOp::Sort(SortOrder::Asc | SortOrder::Desc) + ); + if one_field && schema.fields.len() != 1 { return Err(not_implemented("multi-field Vector", &path)); } runtime.vector = Some(VectorRuntime::new(op.clone(), schema)); - // A selection keeps the labels of the series it keeps, so it keeps no ledger of - // what it handed out. + // A vector operation keeps the labels of the series it reads, or answers under + // label sets of its own, so it keeps no ledger of what it handed out. } NativeExpr::Scalar(_) | NativeExpr::Aggregate { .. } => { // A scalar holds nothing: what its consumer reads is the constant the node was @@ -3123,26 +3229,30 @@ impl NativeExecutionState { }; } NodeTag::Vector => { - // A selection keeps samples of the series it read, so pieces of one label + // Most vector operations keep samples of the series they 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. `limitk` is the exception: it counts series in input - // order, so it merges the pieces first and hands over whole series. - let limitk = matches!( - expr, - NativeExpr::Vector { - op: BoundVectorOp::LimitK { .. }, - .. - } - ); - if limitk && input_holds_shared { - if let Some(vector) = runtimes[index].vector.as_mut() { - vector.merge_input = true; - } - holds_shared[index] = false; - } else { - holds_shared[index] = input_holds_shared; + // it treats a map's. `absent` answers with one series under the labels it + // was bound to, the histogram functions merge the label sets they answer + // with, and `limitk` counts series in input order, so it merges the pieces + // first; none of them hands over pieces. + let op = match expr { + NativeExpr::Vector { op, .. } => Some(op), + _ => None, + }; + let limitk = matches!(op, Some(BoundVectorOp::LimitK { .. })); + 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 { .. } | BoundVectorOp::Histogram(_)) + ); + 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 00cfa1c1c7d..a2ec3e5769b 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::map_label::LabelRewrite; @@ -49,6 +50,7 @@ use crate::native::plan::{ BoundVectorOp, BoundWindow, Grouping, MapOp, 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, @@ -483,6 +485,7 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { pool, ), queued: VecDeque::new(), + queued_tables: 0, instant: None, window: None, map: None, @@ -501,6 +504,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, @@ -7428,6 +7432,282 @@ fn a_binary_node_reads_what_a_vector_node_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(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::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(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::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(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::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 vector node 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); +} + +/// 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))])] + ); +} + +/// `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(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::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(vector_op( + evaluated_input(Arc::clone(&grid)), + BoundVectorOp::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]); +} + /// `label_replace` runs in a map: each series is relabelled as it passes, and two series it gives /// one label set collide where both hold a value, as Prometheus' same-labelset check refuses. #[test] diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index fb6c6600aa0..10bc2db9611 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -31,13 +31,15 @@ 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::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::map_label::LabelRewrite; use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::select::SortOrder; use crate::vector_match::BinaryMatching; /// What one node produces. @@ -264,8 +266,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. @@ -278,6 +281,16 @@ pub enum BoundVectorOp { /// `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 }, + /// `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/promql/src/select.rs b/src/promql/src/select.rs index 05621b01a90..3d69f301edf 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..c8d9d7e2366 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().spec().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 diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 0040d8e7d43..e56380b6e03 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -27,6 +27,9 @@ //! double_exponential_smoothing(, , ) //! e.g. double_exponential_smoothing(x[5m], .5, .1) //! ([, ]*) 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])) //!