chore: merge narthex into feat/narthex-label-node

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

# Conflicts:
#	src/promql/src/native/execute/tests.rs
#	src/query/src/promql/native_compile.rs
#	src/query/src/promql/native_compile/tests.rs
This commit is contained in:
Dennis Zhuang
2026-10-23 00:04:30 +08:00
10 changed files with 818 additions and 80 deletions
+31 -20
View File
@@ -97,7 +97,17 @@ pub fn evaluate_histograms(
schema: &Arc<SeriesSchema>,
series: &[Series],
) -> Result<Vec<Series>> {
let mut groups: HashMap<LabelSet, Group<'_>> = 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<LabelSet, usize> = HashMap::new();
let mut groups: Vec<Group<'_>> = 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<f64>, &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
+34 -1
View File
@@ -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::<Vec<_>>()
.join(", ")
}
/// A grouping as `by [labels]` or `without [labels]`.
fn grouping(group: &Grouping) -> String {
match group {
+19 -1
View File
@@ -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<EvalGrid> {
@@ -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 {
+156 -46
View File
@@ -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<SeriesSchema>,
series: Vec<Series>,
) -> Result<Vec<Series>> {
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::<f64>())
} 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::<f64>()));
}
BoundVectorOp::Histogram(_) => {
let rows: usize = series.iter().map(|item| item.time.len()).sum();
let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
let row = std::mem::size_of::<(f64, f64)>() + fields * std::mem::size_of::<f64>();
let per_series = std::mem::size_of::<(f64, &Series)>()
+ fields * std::mem::size_of::<RowCursor<'_>>();
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::<f64>();
@@ -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<InstantRuntime>,
@@ -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<Series>) -> 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<Series>, 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 {
+280
View File
@@ -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<dyn MemoryPool>) -> NodeRuntime {
pool,
),
queued: VecDeque::new(),
queued_tables: 0,
instant: None,
window: None,
map: None,
@@ -501,6 +504,7 @@ fn binary_runtime(pool: &Arc<dyn MemoryPool>, schema: &Arc<SeriesSchema>) -> 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<String> = 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::<Vec<_>>());
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<usize> = 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]
+16 -3
View File
@@ -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.
+35 -3
View File
@@ -424,20 +424,30 @@ pub fn absent_labels(matchers: &[LabelMatcher]) -> Result<MetricName> {
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<Series>,
) -> Result<Vec<Series>> {
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<Option<Series>> {
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);
+45
View File
@@ -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<usize> = 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
+157 -3
View File
@@ -27,6 +27,9 @@
//! double_exponential_smoothing(<matrix>, <constant>, <constant>)
//! e.g. double_exponential_smoothing(x[5m], .5, .1)
//! <math function>(<expression>[, <constant>]*) e.g. abs(rate(x[5m])), clamp_min(x, 0)
//! <sort>(<expression>[, <string>]*) e.g. sort_desc(x), sort_by_label(x, "job")
//! absent(<expression>) e.g. absent(x{job="a"})
//! <histogram>(<constant>+, <expression>) e.g. histogram_quantile(0.9, rate(x[5m]))
//! <label function>(<expression>, <string>*) e.g. label_replace(x, "a", "$1", "b", "(.*)")
//! <expression> <operator> <constant> e.g. x * 100, x > bool 0
//! <constant> <operator> <expression> e.g. 1 / x, 0 < x
@@ -120,18 +123,21 @@ 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::histogram_eval::HistogramFunction;
use promql::map::{ArithmeticOp, ComparisonOp, MathOp};
use promql::map_label::LabelRewrite;
use promql::map_time::DateFunction;
use promql::native::plan::{
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar,
BoundWindow, Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType,
BoundVectorOp, BoundWindow, Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType,
};
use promql::range_eval::{RangeFunction, RangeWindow, subquery_grid};
use promql::select::{LabelMatcher, MatchOp, SortOrder, absent_labels};
use promql::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
use promql_parser::label::MatchOp as ParserMatchOp;
use promql_parser::parser::token::TokenType;
use promql_parser::parser::value::ValueType;
use promql_parser::parser::{
@@ -163,7 +169,10 @@ const SUPPORTED: &str = "a selector — `x`, optionally with an `offset` — a r
`count`, `min`, `max`, `group`, `stddev`, `stdvar` and \
`quantile(<constant>, <expression>)` — over any of them, optionally \
grouped by `by` or `without` as in `avg by(job)(rate(x[5m]) * 100)`; a \
range function's own constants sit where that function takes them, before \
sort, `absent` or `histogram_quantile` / `histogram_fraction` over any of \
them (`sort_desc(x)`, `absent(x{job=\"a\"})`, \
`histogram_quantile(0.9, rate(x[5m]))`); a range function's own \
constants sit where that function takes them, before \
the matrix for `quantile_over_time(0.9, x[5m])` and after it for \
`predict_linear(x[5m], 300)` and \
`double_exponential_smoothing(x[5m], 0.5, 0.1)`";
@@ -586,6 +595,9 @@ fn compile_call(context: &Context, call: &Call) -> Result<NativeNode> {
if let Some(signature) = range_signature(func.name) {
return window_call(context, func.name, signature, &args.args);
}
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
// vector to map, and the rejection names the name rather than describing a vector they never
@@ -682,6 +694,148 @@ fn map_call(context: &Context, name: &str, op: MapOp, vector: &PromExpr) -> Resu
})
}
/// 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: BoundVectorOp,
vector: &PromExpr,
) -> Result<NativeNode> {
if vector.value_type() != ValueType::Vector {
return Err(not_implemented(&format!(
"a call to `{name}` whose vector 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::Vector {
input: Box::new(input),
op,
},
output,
})
}
/// The vector operation a sort, `absent` or a classic histogram function binds, and the vector it reads,
/// or `None` when `name` is none of them.
fn vector_op<'a>(
name: &str,
arguments: &'a [Box<PromExpr>],
) -> Result<Option<(BoundVectorOp, &'a PromExpr)>> {
let order = match name {
"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((BoundVectorOp::Histogram(function), vector)));
}
"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((BoundVectorOp::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::<Result<Vec<_>>>()?;
if name == "sort_by_label" {
SortOrder::ByLabel(labels)
} else {
SortOrder::ByLabelDesc(labels)
}
}
};
Ok(Some((BoundVectorOp::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<MetricName> {
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::<Vec<_>>();
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
+45 -3
View File
@@ -940,9 +940,9 @@ fn an_unsupported_shape_is_rejected_and_names_what_it_found() {
// A function with no kernel. `predict_linear` used to stand here as the parameterised case
// and is now bound, so what is left is a name this compiler has no kernel for at all.
(
eval_stmt("absent(x)"),
"absent(x)",
"a call to `absent`, which has no native kernel",
eval_stmt("timestamp(x)"),
"timestamp(x)",
"a call to `timestamp`, which has no native kernel",
),
];
@@ -3682,6 +3682,48 @@ fn a_subquery_grid_holds_every_sample_its_windows_read() {
}
}
/// The sorts, `absent` and the classic histogram functions bind a vector operation 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 whole_vector_functions_bind_a_vector_operation() {
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"}"#),
(
"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 {
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 Vector {op}"), "`{query}`");
}
}
/// `label_replace` and `label_join` bind their label change into a map over the vector they are
/// given, with the strings the call wrote.
#[test]