refactor(promql): define each duplicated native rule once (#10748)

- Go math.Max/Min: ScalarFunction::apply calls map's go_max/go_min.
- kahan_inc: the aggregate kernel uses functions::kahan_inc.
- Range function names: RangeFunction::name() and without_arguments()
  replace the tables in display, range_eval/histogram, the native
  compiler and the golden test.
- by/without to kernel grouping: Grouping::{labels, names, kernel}
  replace the conversions in native aggregate, execute and plan.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
dennis zhuang
2026-11-30 10:32:49 +00:00
committed by GitHub
parent 9fc061d125
commit 7b60bb66e7
11 changed files with 134 additions and 232 deletions
+1 -13
View File
@@ -38,6 +38,7 @@ use datatypes::series::histogram::{
use datatypes::series::samples::{SampleRef, Samples, Series, SeriesFields, SeriesSchema};
use datatypes::series::time::{GridSpan, TimeAxis};
use crate::functions::kahan_inc;
use crate::go_format::format_float_f;
use crate::grid_series::{GridSeriesBuilder, external};
use crate::histogram_eval::float_histogram::FloatHistogram;
@@ -1807,16 +1808,3 @@ fn update_avg(words: &mut [f64], sample: f64) {
let q = (count - 1.0) / count;
(words[2], words[1]) = kahan_inc(sample / count, q * words[2], q * words[1]);
}
/// Prometheus `kahansum.Inc`, with the Neumaier swap.
fn kahan_inc(inc: f64, sum: f64, compensation: f64) -> (f64, f64) {
let t = sum + inc;
let compensation = if t.is_infinite() {
0.0
} else if sum.abs() >= inc.abs() {
compensation + ((sum - t) + inc)
} else {
compensation + ((inc - t) + sum)
};
(t, compensation)
}
+2 -1
View File
@@ -43,8 +43,9 @@ use crate::aggregate::{
AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, HistogramAccumulator,
HistogramEvidence, LabelKey, accumulator_bytes, block_bytes, btree_backing_bytes, count_series,
evidence_summary, finish_groups, finish_groups_budgeted, hash_map_backing_bytes,
histogram_backing_bytes, kahan_inc, label_key, metric_bytes, next_hash_capacity, state_seen,
histogram_backing_bytes, label_key, metric_bytes, next_hash_capacity, state_seen,
};
use crate::functions::kahan_inc;
use crate::map::validate_float_series;
/// A component of [`AccumulatorState`].
+5 -22
View File
@@ -21,8 +21,8 @@ use datatypes::series::time::TimeAxis;
use crate::grid_series::GridSeriesBuilder;
use crate::map::{
ArithmeticOp, Comparison, MathOp, drop_metric_name, float_sample, validate_float_series,
validate_grid_series,
ArithmeticOp, Comparison, MathOp, drop_metric_name, float_sample, go_max, go_min,
validate_float_series, validate_grid_series,
};
/// A time-varying, unlabelled single-field scalar, with explicit operand direction.
@@ -93,27 +93,10 @@ pub(crate) enum ScalarFunction {
}
impl ScalarFunction {
/// Go's `math.Max` / `math.Min`: an infinity of the function's own sign wins over NaN, NaN
/// over any other value, and `+0` is greater than `-0`. Symmetric in its arguments.
pub(crate) fn apply(self, a: f64, b: f64) -> f64 {
let (wins, signed_zero_wins) = match self {
Self::MaxOf => (f64::INFINITY, false),
Self::MinOf => (f64::NEG_INFINITY, true),
};
if a == wins || b == wins {
wins
} else if a.is_nan() || b.is_nan() {
f64::NAN
} else if a == 0.0 && a == b {
if a.is_sign_negative() == signed_zero_wins {
a
} else {
b
}
} else if (a > b) == (self == Self::MaxOf) {
a
} else {
b
match self {
Self::MaxOf => go_max(a, b),
Self::MinOf => go_min(a, b),
}
}
}
+12 -26
View File
@@ -35,7 +35,7 @@ use datatypes::series::samples::{FieldSpec, Series, SeriesSchema};
use datatypes::series::time::{EvalGrid, GridRange, TimeAxis, union_positions};
use crate::aggregate::{
AggregateOp, FloatAggregator, FloatMerger, Grouping, HistogramEvidence, HistogramSamples,
AggregateOp, FloatAggregator, FloatMerger, HistogramEvidence, HistogramSamples,
aggregate_quantile, histogram_samples, validate_aggregate_series,
};
use crate::evaluated::EvaluatedChunk;
@@ -46,8 +46,7 @@ use crate::native::execute::{
unbilled_tables,
};
use crate::native::plan::{
AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, Grouping as BoundGrouping,
aggregate_state_binding,
AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, aggregate_state_binding,
};
use crate::native::state::{
StateChunk, state_bytes, state_chunk_from_partial, state_row_from_frame_row,
@@ -201,21 +200,14 @@ impl AggregateRuntime {
computed: false,
});
}
let name_count = match &op.group {
BoundGrouping::By(labels) | BoundGrouping::Without(labels) => labels.len(),
};
let name_bytes = name_count.saturating_mul(std::mem::size_of::<&str>());
let name_bytes = op
.group
.labels()
.len()
.saturating_mul(std::mem::size_of::<&str>());
buffer.grow(name_bytes)?;
let names: Vec<&str> = match &op.group {
BoundGrouping::By(labels) | BoundGrouping::Without(labels) => {
labels.iter().map(|label| label.as_ref()).collect()
}
};
let grouping = match &op.group {
BoundGrouping::By(_) => Grouping::By(&names),
BoundGrouping::Without(_) => Grouping::Without(&names),
};
let name_bytes = names.len().saturating_mul(std::mem::size_of::<&str>());
let names = op.group.names();
let grouping = op.group.kernel(&names);
let initial = FloatAggregator::try_new_budgeted(&schema, kind, grouping, |bytes| {
buffer.resize(bytes.saturating_add(name_bytes))
})?;
@@ -634,15 +626,8 @@ impl AggregateRuntime {
})
.saturating_add(workspace);
buffer.resize(held.saturating_add(queue_bytes))?;
let names: Vec<&str> = match &self.op.group {
BoundGrouping::By(labels) | BoundGrouping::Without(labels) => {
labels.iter().map(|label| label.as_ref()).collect()
}
};
let grouping = match &self.op.group {
BoundGrouping::By(_) => Grouping::By(&names),
BoundGrouping::Without(_) => Grouping::Without(&names),
};
let names = self.op.group.names();
let grouping = self.op.group.kernel(&names);
let output = aggregate_quantile(&self.schema, &input.series, parameter, grouping)
.map_err(|error| folded_chunk(&self.describe(), error))?;
drop(names);
@@ -783,6 +768,7 @@ mod tests {
use datatypes::series::time::{EvalGrid, GridSpec};
use super::*;
use crate::native::plan::Grouping as BoundGrouping;
fn schema() -> Arc<SeriesSchema> {
Arc::new(SeriesSchema {
+5 -26
View File
@@ -336,35 +336,14 @@ fn window(op: &BoundWindow) -> String {
/// The PromQL name of a range function, with the constant argument it was bound to.
fn function(function: RangeFunction) -> String {
let name = function.name();
match function {
RangeFunction::Rate => "rate".to_string(),
RangeFunction::Increase => "increase".to_string(),
RangeFunction::Delta => "delta".to_string(),
RangeFunction::Irate => "irate".to_string(),
RangeFunction::Idelta => "idelta".to_string(),
RangeFunction::AvgOverTime => "avg_over_time".to_string(),
RangeFunction::MinOverTime => "min_over_time".to_string(),
RangeFunction::MaxOverTime => "max_over_time".to_string(),
RangeFunction::SumOverTime => "sum_over_time".to_string(),
RangeFunction::CountOverTime => "count_over_time".to_string(),
RangeFunction::LastOverTime => "last_over_time".to_string(),
RangeFunction::PresentOverTime => "present_over_time".to_string(),
RangeFunction::StddevOverTime => "stddev_over_time".to_string(),
RangeFunction::StdvarOverTime => "stdvar_over_time".to_string(),
RangeFunction::QuantileOverTime(quantile) => format!("quantile_over_time {quantile}"),
RangeFunction::Resets => "resets".to_string(),
RangeFunction::Changes => "changes".to_string(),
RangeFunction::Deriv => "deriv".to_string(),
RangeFunction::PredictLinear(seconds) => format!("predict_linear {seconds}"),
RangeFunction::QuantileOverTime(quantile) => format!("{name} {quantile}"),
RangeFunction::PredictLinear(seconds) => format!("{name} {seconds}"),
RangeFunction::DoubleExponentialSmoothing { smoothing, trend } => {
format!("double_exponential_smoothing {smoothing} {trend}")
format!("{name} {smoothing} {trend}")
}
RangeFunction::FirstOverTime => "first_over_time".to_string(),
RangeFunction::MadOverTime => "mad_over_time".to_string(),
RangeFunction::TsOfFirstOverTime => "ts_of_first_over_time".to_string(),
RangeFunction::TsOfLastOverTime => "ts_of_last_over_time".to_string(),
RangeFunction::TsOfMinOverTime => "ts_of_min_over_time".to_string(),
RangeFunction::TsOfMaxOverTime => "ts_of_max_over_time".to_string(),
_ => name.to_string(),
}
}
+4 -20
View File
@@ -1331,15 +1331,8 @@ impl VectorRuntime {
_ => None,
};
if let Some(group) = bound_grouping {
let names: Vec<&str> = match group {
Grouping::By(names) | Grouping::Without(names) => {
names.iter().map(AsRef::as_ref).collect()
}
};
let grouping = match group {
Grouping::By(_) => aggregate::Grouping::By(&names),
Grouping::Without(_) => aggregate::Grouping::Without(&names),
};
let names = group.names();
let grouping = group.kernel(&names);
match &op {
BoundVectorOp::CountValues { label, .. } => {
aggregate::validate_count_values(&schema, label, grouping)?
@@ -1556,17 +1549,8 @@ fn vector_series_with_k(
collector,
),
BoundVectorOp::CountValues { label, group } => {
let (by, labels) = match group {
Grouping::By(labels) => (true, labels),
Grouping::Without(labels) => (false, labels),
};
let labels: Vec<&str> = labels.iter().map(|label| &**label).collect();
let grouping = if by {
aggregate::Grouping::By(&labels)
} else {
aggregate::Grouping::Without(&labels)
};
aggregate::count_values(schema, series, label, grouping)
let names = group.names();
aggregate::count_values(schema, series, label, group.kernel(&names))
}
BoundVectorOp::Absent { labels } => Ok(select::absent(schema, series, labels.clone())?
.into_iter()
+27 -22
View File
@@ -792,6 +792,28 @@ pub enum Grouping {
Without(Arc<[Arc<str>]>),
}
impl Grouping {
/// The labels listed in `by(...)` or `without(...)`.
pub(crate) fn labels(&self) -> &[Arc<str>] {
match self {
Grouping::By(labels) | Grouping::Without(labels) => labels,
}
}
/// [`Self::labels`] borrowed as the names [`Self::kernel`] takes.
pub(crate) fn names(&self) -> Vec<&str> {
self.labels().iter().map(AsRef::as_ref).collect()
}
/// This grouping in the kernel's form, over `names` from [`Self::names`].
pub(crate) fn kernel<'a>(&self, names: &'a [&'a str]) -> crate::aggregate::Grouping<'a> {
match self {
Grouping::By(_) => crate::aggregate::Grouping::By(names),
Grouping::Without(_) => crate::aggregate::Grouping::Without(names),
}
}
}
/// An aggregate bound to its kind, grouping and stage.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
pub struct BoundAggregate {
@@ -1738,13 +1760,9 @@ fn vector_op_supported(schema: &SeriesSchema, op: &BoundVectorOp) -> bool {
grouping_supported(schema, group)
}
BoundVectorOp::CountValues { label, group } => {
let names = group_names(group);
crate::aggregate::validate_count_values(
schema,
label.as_ref(),
kernel_grouping(group, &names),
)
.is_ok()
let names = group.names();
crate::aggregate::validate_count_values(schema, label.as_ref(), group.kernel(&names))
.is_ok()
}
BoundVectorOp::LimitRatio { .. }
| BoundVectorOp::Sort(_)
@@ -1755,21 +1773,8 @@ fn vector_op_supported(schema: &SeriesSchema, op: &BoundVectorOp) -> bool {
/// The grouping check `FloatAggregator::try_new_budgeted` and `VectorRuntime::try_new` run.
fn grouping_supported(schema: &SeriesSchema, group: &Grouping) -> bool {
let names = group_names(group);
crate::aggregate::validate_vector_grouping(schema, kernel_grouping(group, &names)).is_ok()
}
fn group_names(group: &Grouping) -> Vec<&str> {
match group {
Grouping::By(names) | Grouping::Without(names) => names.iter().map(AsRef::as_ref).collect(),
}
}
fn kernel_grouping<'a>(group: &Grouping, names: &'a [&'a str]) -> crate::aggregate::Grouping<'a> {
match group {
Grouping::By(_) => crate::aggregate::Grouping::By(names),
Grouping::Without(_) => crate::aggregate::Grouping::Without(names),
}
let names = group.names();
crate::aggregate::validate_vector_grouping(schema, group.kernel(&names)).is_ok()
}
/// The [`check_modifier`](crate::range_eval::check_modifier) rule
+63
View File
@@ -69,6 +69,69 @@ impl RangeFunction {
!matches!(self, Self::LastOverTime | Self::FirstOverTime)
}
/// The PromQL name of this function.
pub(crate) fn name(self) -> &'static str {
match self {
Self::Rate => "rate",
Self::Increase => "increase",
Self::Delta => "delta",
Self::Irate => "irate",
Self::Idelta => "idelta",
Self::AvgOverTime => "avg_over_time",
Self::MinOverTime => "min_over_time",
Self::MaxOverTime => "max_over_time",
Self::SumOverTime => "sum_over_time",
Self::CountOverTime => "count_over_time",
Self::LastOverTime => "last_over_time",
Self::PresentOverTime => "present_over_time",
Self::StddevOverTime => "stddev_over_time",
Self::StdvarOverTime => "stdvar_over_time",
Self::QuantileOverTime(_) => "quantile_over_time",
Self::Resets => "resets",
Self::Changes => "changes",
Self::Deriv => "deriv",
Self::PredictLinear(_) => "predict_linear",
Self::DoubleExponentialSmoothing { .. } => "double_exponential_smoothing",
Self::FirstOverTime => "first_over_time",
Self::MadOverTime => "mad_over_time",
Self::TsOfFirstOverTime => "ts_of_first_over_time",
Self::TsOfLastOverTime => "ts_of_last_over_time",
Self::TsOfMinOverTime => "ts_of_min_over_time",
Self::TsOfMaxOverTime => "ts_of_max_over_time",
}
}
/// The function `name` denotes when it takes no argument besides the range vector.
pub fn without_arguments(name: &str) -> Option<Self> {
[
Self::Rate,
Self::Increase,
Self::Delta,
Self::Irate,
Self::Idelta,
Self::AvgOverTime,
Self::MinOverTime,
Self::MaxOverTime,
Self::SumOverTime,
Self::CountOverTime,
Self::LastOverTime,
Self::PresentOverTime,
Self::StddevOverTime,
Self::StdvarOverTime,
Self::Resets,
Self::Changes,
Self::Deriv,
Self::FirstOverTime,
Self::MadOverTime,
Self::TsOfFirstOverTime,
Self::TsOfLastOverTime,
Self::TsOfMinOverTime,
Self::TsOfMaxOverTime,
]
.into_iter()
.find(|function| function.name() == name)
}
/// Whether a window holding native histograms can answer with one; every other function
/// reduces it to a float.
pub(crate) fn yields_histograms(self) -> bool {
+11 -46
View File
@@ -76,7 +76,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: encountered a mix of float and native histogram samples",
function_name(function)
function.name()
),
);
}
@@ -99,10 +99,7 @@ pub(super) fn evaluate(
{
record_info(
collector,
format!(
"{}: ignored native histogram samples",
function_name(function)
),
format!("{}: ignored native histogram samples", function.name()),
);
}
let float = |value: f64| Some(GridSample::Float(value));
@@ -163,7 +160,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: native histogram counter reset hints contradict",
function_name(function)
function.name()
),
);
}
@@ -175,7 +172,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: dropped native histogram range with incompatible schemas",
function_name(function)
function.name()
),
);
}
@@ -184,7 +181,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: reconciled native histograms with different custom buckets",
function_name(function)
function.name()
),
);
}
@@ -231,7 +228,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: dropped native histogram range with incompatible schemas",
function_name(function)
function.name()
),
);
return Ok(None);
@@ -267,7 +264,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: dropped native histogram range with incompatible schemas",
function_name(function)
function.name()
),
);
return Ok(None);
@@ -295,7 +292,7 @@ pub(super) fn evaluate(
collector,
format!(
"{}: dropped native histogram range with incompatible schemas",
function_name(function)
function.name()
),
);
}
@@ -306,38 +303,6 @@ pub(super) fn evaluate(
})
}
fn function_name(function: RangeFunction) -> &'static str {
use RangeFunction::*;
match function {
Rate => "rate",
Increase => "increase",
Delta => "delta",
Irate => "irate",
Idelta => "idelta",
AvgOverTime => "avg_over_time",
MinOverTime => "min_over_time",
MaxOverTime => "max_over_time",
SumOverTime => "sum_over_time",
CountOverTime => "count_over_time",
LastOverTime => "last_over_time",
PresentOverTime => "present_over_time",
StddevOverTime => "stddev_over_time",
StdvarOverTime => "stdvar_over_time",
QuantileOverTime(_) => "quantile_over_time",
Resets => "resets",
Changes => "changes",
Deriv => "deriv",
PredictLinear(_) => "predict_linear",
DoubleExponentialSmoothing { .. } => "double_exponential_smoothing",
FirstOverTime => "first_over_time",
MadOverTime => "mad_over_time",
TsOfFirstOverTime => "ts_of_first_over_time",
TsOfLastOverTime => "ts_of_last_over_time",
TsOfMinOverTime => "ts_of_min_over_time",
TsOfMaxOverTime => "ts_of_max_over_time",
}
}
fn record_warning(collector: Option<&PromqlAnnotationCollector>, message: String) {
if let Some(collector) = collector {
collector.record_warning(message);
@@ -389,7 +354,7 @@ fn record_histogram_flavor_warning(
collector,
format!(
"{}: native histogram input should be a {expected} histogram",
function_name(function)
function.name()
),
);
}
@@ -410,7 +375,7 @@ fn record_histogram_pair_annotations(
collector,
format!(
"{}: reconciled native histograms with different custom buckets",
function_name(function)
function.name()
),
);
}
@@ -465,7 +430,7 @@ fn record_mixed_last_two(
collector,
format!(
"{}: encountered a mix of float and native histogram samples in the last two points",
function_name(function)
function.name()
),
);
}
+2 -24
View File
@@ -2899,36 +2899,14 @@ fn rejects_input_of_the_other_kind() {
/// The range function a golden fixture names, with its constant arguments.
fn range_function(name: &str, params: &[f64]) -> RangeFunction {
match name {
"rate" => RangeFunction::Rate,
"increase" => RangeFunction::Increase,
"delta" => RangeFunction::Delta,
"irate" => RangeFunction::Irate,
"idelta" => RangeFunction::Idelta,
"avg_over_time" => RangeFunction::AvgOverTime,
"min_over_time" => RangeFunction::MinOverTime,
"max_over_time" => RangeFunction::MaxOverTime,
"sum_over_time" => RangeFunction::SumOverTime,
"count_over_time" => RangeFunction::CountOverTime,
"last_over_time" => RangeFunction::LastOverTime,
"present_over_time" => RangeFunction::PresentOverTime,
"stddev_over_time" => RangeFunction::StddevOverTime,
"stdvar_over_time" => RangeFunction::StdvarOverTime,
"quantile_over_time" => RangeFunction::QuantileOverTime(params[0]),
"resets" => RangeFunction::Resets,
"changes" => RangeFunction::Changes,
"deriv" => RangeFunction::Deriv,
"predict_linear" => RangeFunction::PredictLinear(params[0]),
"double_exponential_smoothing" => RangeFunction::DoubleExponentialSmoothing {
smoothing: params[0],
trend: params[1],
},
"first_over_time" => RangeFunction::FirstOverTime,
"mad_over_time" => RangeFunction::MadOverTime,
"ts_of_first_over_time" => RangeFunction::TsOfFirstOverTime,
"ts_of_last_over_time" => RangeFunction::TsOfLastOverTime,
"ts_of_min_over_time" => RangeFunction::TsOfMinOverTime,
"ts_of_max_over_time" => RangeFunction::TsOfMaxOverTime,
other => panic!("unknown function {other}"),
other => RangeFunction::without_arguments(other)
.unwrap_or_else(|| panic!("unknown function {other}")),
}
}
+2 -32
View File
@@ -2118,7 +2118,7 @@ impl RangeSignature {
}
/// The signature of the range function `name`, or `None` when there is no range kernel for it.
/// Functions with constants are listed here; the rest come from [`range_function`].
/// Functions with constants are listed here; the rest come from [`RangeFunction::without_arguments`].
fn range_signature(name: &str) -> Option<RangeSignature> {
match name {
"quantile_over_time" => Some(RangeSignature::ConstantBeforeSelector(
@@ -2130,7 +2130,7 @@ fn range_signature(name: &str) -> Option<RangeSignature> {
"double_exponential_smoothing" => Some(RangeSignature::TwoConstantsAfterSelector(
|smoothing, trend| RangeFunction::DoubleExponentialSmoothing { smoothing, trend },
)),
_ => range_function(name).map(RangeSignature::Selector),
_ => RangeFunction::without_arguments(name).map(RangeSignature::Selector),
}
}
@@ -2395,36 +2395,6 @@ pub(crate) fn constant_value(expr: &PromExpr) -> Option<f64> {
}
}
/// The range function a PromQL name denotes, or `None` when this compiler has no kernel for it.
fn range_function(name: &str) -> Option<RangeFunction> {
match name {
"rate" => Some(RangeFunction::Rate),
"increase" => Some(RangeFunction::Increase),
"delta" => Some(RangeFunction::Delta),
"irate" => Some(RangeFunction::Irate),
"idelta" => Some(RangeFunction::Idelta),
"avg_over_time" => Some(RangeFunction::AvgOverTime),
"min_over_time" => Some(RangeFunction::MinOverTime),
"max_over_time" => Some(RangeFunction::MaxOverTime),
"sum_over_time" => Some(RangeFunction::SumOverTime),
"count_over_time" => Some(RangeFunction::CountOverTime),
"last_over_time" => Some(RangeFunction::LastOverTime),
"present_over_time" => Some(RangeFunction::PresentOverTime),
"stddev_over_time" => Some(RangeFunction::StddevOverTime),
"stdvar_over_time" => Some(RangeFunction::StdvarOverTime),
"resets" => Some(RangeFunction::Resets),
"changes" => Some(RangeFunction::Changes),
"deriv" => Some(RangeFunction::Deriv),
"first_over_time" => Some(RangeFunction::FirstOverTime),
"mad_over_time" => Some(RangeFunction::MadOverTime),
"ts_of_first_over_time" => Some(RangeFunction::TsOfFirstOverTime),
"ts_of_last_over_time" => Some(RangeFunction::TsOfLastOverTime),
"ts_of_min_over_time" => Some(RangeFunction::TsOfMinOverTime),
"ts_of_max_over_time" => Some(RangeFunction::TsOfMaxOverTime),
_ => None,
}
}
/// The expression inside any number of parentheses.
fn unparen(mut expr: &PromExpr) -> &PromExpr {
while let PromExpr::Paren(paren) = expr {