feat(promql): rate delta-marked native histograms natively (#10676)

* fix(promql): declare float columns for a float function over a split histogram sum

`histogram_count(sum(h))` and `histogram_quantile(0.9, sum(rate(h[2m])))`
over native histograms failed to plan on the native route: the split
counted the statement's value columns by the type of the exported state
(a histogram), while the columns carry the root's kind (Float), so it
counted zero and returned a plan error. Count value columns of either
value type; the layout declares one kind for all of them.

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

* feat(promql): pick OTLP delta math per series in native rate and increase

rate and increase over a table that carries otlp_aggregation_temporality
declined with delta_temporality_under_rate_or_increase. The existing
plan picks the math per series: a series marked "delta" holds
increments, so increase is the Kahan sum of the window and rate is
that sum over the range in seconds, while every other series keeps the
counter math.

A range evaluator of rate or increase over raw input now checks each
series' labels when it starts and evaluates a delta series with the
sum kernel, outside the batch path. A rate or increase that reads its
window directly is admitted; one that reads it through another
expression, a histogram field, or a range modifier still declines.

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

* test(promql): cover offset and @ for native delta rate and increase

Pins the delta sum against the existing plan when the window is moved by
`offset` or anchored by `@`, and puts the misplaced doc comments of
`kernel` and `root_subquery` back on their functions.

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

* feat(promql): rate delta-marked native histograms natively

`rate` and `increase` over a native histogram whose series carries the
OTLP delta temporality marker declined to the legacy plan. The legacy
plan sums the window only for float samples and rates a native histogram
as a counter whatever its marker says, so the native window already
answers the same thing: the delta kernel only ever reads floats.

The decline now applies to float selectors only, both for a call that
reads the selector through another expression and for a range modifier.

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

* test(promql): cover OTLP delta exponential histograms under native rate

The earlier case wrote counter-hinted histograms through remote write.
OTLP ingest stores a delta point as a gauge-hinted histogram whose start
timestamp is the previous point's end; rate and increase over that shape
now run natively and agree with the existing plan.

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

* fix(promql): sum delta-marked evaluated series under native rate and increase

A float derived from a delta-marked native histogram, such as
`increase(histogram_count(h)[2m:1m])`, keeps the OTLP temporality marker.
The existing plan picks the delta math off that marker and sums the
window, but the native window over an evaluated series always used
counter math, so the two routes disagreed (40 vs 55 in the new case).

Pick the delta kernel for an evaluated series the same way as for a raw
one. Histogram windows still go through the histogram rules, which
ignore the marker on both routes.

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

* refactor(query): drop the unreachable range-modifier delta decline

The native planner declined `rate`/`increase` over a delta-marked raw
input when its window carried an anchored or smoothed modifier. Nothing
in the query crate builds a `RangeModifier`, and promql-parser 0.10.0
does not parse either modifier, so the branch never ran.

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

* test(promql): pin absolute values for native OTLP delta histogram rates

The OTLP delta histogram test only compared the native route with the
existing plan. Also assert the values the Prometheus formulas give for
`histogram_count(increase(h[2m]))` (30 and 55) and for the subquery
over `histogram_count` (55).

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

* refactor(promql): decide batch eligibility for a delta window in one check

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

* feat(query): run delta-marked float subqueries under native rate and increase

`increase(m[2m:1m])` and `rate(m[3m:1m])` over a delta-marked float
series declined to the existing plan, because the native window over an
evaluated series used counter math. That window now picks the delta math
from the marker its series keeps, as the existing plan does, so the
decline and the `under_rate_or_increase` flag the selector walk carried
for it are removed.

The OTLP delta corpus test asserts both queries run natively, match the
existing plan, and sum the window's deltas (divided by the range for
`rate`).

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

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
dennis zhuang
2026-11-30 14:39:22 +00:00
committed by GitHub
parent b4f8bc2263
commit 007f9dea40
5 changed files with 349 additions and 149 deletions
+6 -2
View File
@@ -170,7 +170,7 @@ pub struct RangeEvaluator {
window: RangeWindow,
replay: Replay,
kernel: WindowKernel,
/// The kernel of `rate` or `increase` over a raw series marked as OTLP delta temporality, which
/// The kernel of `rate` or `increase` over a series marked as OTLP delta temporality, which
/// the existing plan picks per series: the sum of the window's increments, over the range for
/// `rate`. `None` for every other function.
delta_kernel: Option<WindowKernel>,
@@ -838,6 +838,10 @@ impl RangeEvaluator {
match &mut self.series {
None => {
self.output.begin_series();
// The existing plan reads the marker off whatever series reaches the window, so
// an evaluated series that kept it - a float derived from a delta histogram,
// say - is summed too.
let delta = self.delta_kernel.is_some() && is_delta_temporality(&series.metric);
self.series = Some(SeriesState {
primary_key: None,
metric: series.metric.clone(),
@@ -845,7 +849,7 @@ impl RangeEvaluator {
cursor: 0,
closing: false,
emitted_end: 0,
delta: false,
delta,
});
}
Some(state) => {
+21 -127
View File
@@ -30,7 +30,6 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE, MITO2_ENGINE};
use common_query::native_histogram::native_histogram_value_type;
use common_query::prelude::OTLP_AGGREGATION_TEMPORALITY_LABEL;
use common_query::series_frame::raw_series_frame_schema_with_ordering;
use common_telemetry::debug;
use datafusion::arrow::datatypes::DataType as ArrowDataType;
@@ -64,7 +63,6 @@ use promql::native::segment::{
pub(crate) use promql::native::segment::{
independent_scan_pair, is_empty_discovered_input, pointwise_operand,
};
use promql::range_eval::RangeFunction;
use promql_parser::label::{METRIC_NAME, MatchOp, Matcher, Matchers};
use promql_parser::parser::value::ValueType;
use promql_parser::parser::{
@@ -273,11 +271,9 @@ pub(crate) fn take_reported_unproved_labelset_check() -> Option<&'static str> {
impl PromPlanner {
/// Builds the scan of the one logical table the current context is bound to. The caller has
/// already preprocessed this selector's matchers and set the context to its table.
#[allow(clippy::too_many_arguments)]
async fn prepare_one_scan(
&mut self,
matchers: Matchers,
under_rate_or_increase: bool,
logical_scan_id: &mut Option<u32>,
logical_ids_differ: &mut bool,
statement_kind: &mut Option<FieldKind>,
@@ -294,16 +290,6 @@ impl PromPlanner {
if self.ctx.field_column_matcher.is_some() || fields.is_empty() {
return Ok(declined("field_selector_without_raw_series_equivalent"));
}
// Delta samples are increments: the existing planner sums them for `increase` and
// divides by the range for `rate`. A window over the raw samples does the same per series;
// decline when one of those calls reads this selector through another expression.
if tags
.iter()
.any(|tag| tag == OTLP_AGGREGATION_TEMPORALITY_LABEL)
&& under_rate_or_increase
{
return Ok(declined("delta_temporality_under_rate_or_increase"));
}
// Built by the existing path's method so both paths read the same columns.
let table_ref = self.table_ref()?;
let mut input = self.create_table_scan_plan(table_ref).await?;
@@ -732,7 +718,6 @@ impl PromPlanner {
if !collect_selectors_with_set_operations(
&stmt,
effective_expr,
false,
&mut selectors,
&mut set_operations,
) {
@@ -826,7 +811,7 @@ impl PromPlanner {
let mut logical_ids_differ = false;
// Selectors must agree on one field kind.
let mut statement_kind: Option<FieldKind> = None;
for (selector, under_rate_or_increase) in &selectors {
for selector in &selectors {
self.ctx = original_context.clone();
if !selector.matchers.or_matchers.is_empty() {
return Ok(declined("or_matchers_have_no_single_raw_scan"));
@@ -950,7 +935,6 @@ impl PromPlanner {
)) = self
.prepare_one_scan(
matchers.clone(),
*under_rate_or_increase,
&mut logical_scan_id,
&mut logical_ids_differ,
&mut statement_kind,
@@ -1065,7 +1049,6 @@ impl PromPlanner {
let Some(one) = self
.prepare_one_scan(
matchers,
*under_rate_or_increase,
&mut logical_scan_id,
&mut logical_ids_differ,
&mut statement_kind,
@@ -1139,7 +1122,7 @@ impl PromPlanner {
// `collect_selectors_with_set_operations`; a mismatch is an internal error.
let identities: Vec<(Option<String>, Matchers, i64, Option<i64>)> = selectors
.iter()
.map(|(selector, _)| {
.map(|selector| {
let offset_ms = selector
.offset
.as_ref()
@@ -1203,23 +1186,6 @@ impl PromPlanner {
))
.context(DataFusionPlanningSnafu);
}
// The per-series delta math is the float windows' own; a histogram window or a range
// modifier over a series that may carry the temporality marker keeps the existing plan.
let marked = |source: usize| {
prepared.get(source).is_some_and(|(_, _, _, _, tags, ..)| {
tags.iter()
.any(|tag| tag == OTLP_AGGREGATION_TEMPORALITY_LABEL)
})
};
if compiled.tree.root().any(&|node| {
matches!(&node.expr, NativeExpr::Window { input, op }
if matches!(op.function, RangeFunction::Rate | RangeFunction::Increase)
&& (statement_kind == Some(FieldKind::Histogram)
|| op.window.modifier.is_some())
&& matches!(&input.expr, NativeExpr::Input(input) if marked(input.source_index)))
}) {
return Ok(declined("delta_temporality_under_rate_or_increase"));
}
for (index, (compiled_input, (scan, _, _, time, _, _, _, _))) in
compiled.inputs.iter().zip(prepared.iter_mut()).enumerate()
{
@@ -1846,15 +1812,6 @@ fn epoch_millis(millis: i64) -> Option<SystemTime> {
}
}
/// Finds a range selector at the statement root, treating parentheses as transparent.
fn root_matrix_selector(expr: &PromExpr) -> Option<&MatrixSelector> {
match expr {
PromExpr::MatrixSelector(selector) => Some(selector),
PromExpr::Paren(paren) => root_matrix_selector(&paren.expr),
_ => None,
}
}
/// Finds a subquery at the statement root, treating parentheses as transparent.
fn root_subquery(expr: &PromExpr) -> Option<&SubqueryExpr> {
match expr {
@@ -2191,60 +2148,32 @@ struct SetOperation {
fn collect_selectors_with_set_operations<'a>(
stmt: &EvalStmt,
expr: &'a PromExpr,
under_rate_or_increase: bool,
out: &mut Vec<(Cow<'a, VectorSelector>, bool)>,
out: &mut Vec<Cow<'a, VectorSelector>>,
set_operations: &mut Vec<SetOperation>,
) -> bool {
match expr {
PromExpr::VectorSelector(selector) => {
out.push((Cow::Borrowed(selector), under_rate_or_increase))
}
PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => {
out.push((Cow::Borrowed(vs), under_rate_or_increase))
}
PromExpr::VectorSelector(selector) => out.push(Cow::Borrowed(selector)),
PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => out.push(Cow::Borrowed(vs)),
PromExpr::Paren(ParenExpr { expr }) => {
return collect_selectors_with_set_operations(
stmt,
expr,
under_rate_or_increase,
out,
set_operations,
);
return collect_selectors_with_set_operations(stmt, expr, out, set_operations);
}
PromExpr::Call(call) if call.func.name == "info" => {
let Ok(InfoInput { selector, .. }) = info_input(stmt, &call.args.args) else {
return false;
};
if !collect_selectors_with_set_operations(
stmt,
&call.args.args[0],
under_rate_or_increase,
out,
set_operations,
) {
if !collect_selectors_with_set_operations(stmt, &call.args.args[0], out, set_operations)
{
return false;
}
out.push((Cow::Owned(selector), under_rate_or_increase));
out.push(Cow::Owned(selector));
}
PromExpr::Binary(binary) => {
let lhs_start = out.len();
if !collect_selectors_with_set_operations(
stmt,
&binary.lhs,
under_rate_or_increase,
out,
set_operations,
) {
if !collect_selectors_with_set_operations(stmt, &binary.lhs, out, set_operations) {
return false;
}
let lhs_end = out.len();
if !collect_selectors_with_set_operations(
stmt,
&binary.rhs,
under_rate_or_increase,
out,
set_operations,
) {
if !collect_selectors_with_set_operations(stmt, &binary.rhs, out, set_operations) {
return false;
}
if binary.op.is_set_operator() {
@@ -2263,13 +2192,7 @@ fn collect_selectors_with_set_operations<'a>(
}
PromExpr::NumberLiteral(_) => return true,
PromExpr::Unary(unary) => {
return collect_selectors_with_set_operations(
stmt,
&unary.expr,
under_rate_or_increase,
out,
set_operations,
);
return collect_selectors_with_set_operations(stmt, &unary.expr, out, set_operations);
}
// The compiler binds the vector (last argument) before the parameters.
PromExpr::Call(call)
@@ -2278,21 +2201,10 @@ fn collect_selectors_with_set_operations<'a>(
let Some((vector, parameters)) = call.args.args.split_last() else {
return false;
};
return collect_selectors_with_set_operations(
stmt,
vector,
under_rate_or_increase,
out,
set_operations,
) && parameters.iter().all(|parameter| {
collect_selectors_with_set_operations(
stmt,
parameter,
under_rate_or_increase,
out,
set_operations,
)
});
return collect_selectors_with_set_operations(stmt, vector, out, set_operations)
&& parameters.iter().all(|parameter| {
collect_selectors_with_set_operations(stmt, parameter, out, set_operations)
});
}
PromExpr::Call(call) => {
if matches!(call.func.name, "label_replace" | "label_join") {
@@ -2306,23 +2218,12 @@ fn collect_selectors_with_set_operations<'a>(
&& collect_selectors_with_set_operations(
stmt,
&call.args.args[0],
under_rate_or_increase,
out,
set_operations,
);
}
for arg in &call.args.args {
// A window `rate` or `increase` reads straight off the raw samples picks the delta
// math per series itself; one read through another expression does not.
let reads_raw_window = root_matrix_selector(arg).is_some();
if !collect_selectors_with_set_operations(
stmt,
arg,
under_rate_or_increase
|| (matches!(call.func.name, "rate" | "increase") && !reads_raw_window),
out,
set_operations,
) {
if !collect_selectors_with_set_operations(stmt, arg, out, set_operations) {
return false;
}
}
@@ -2332,17 +2233,12 @@ fn collect_selectors_with_set_operations<'a>(
return collect_selectors_with_set_operations(
stmt,
&aggregate.expr,
under_rate_or_increase,
out,
set_operations,
) && match &aggregate.param {
Some(param) => collect_selectors_with_set_operations(
stmt,
param,
under_rate_or_increase,
out,
set_operations,
),
Some(param) => {
collect_selectors_with_set_operations(stmt, param, out, set_operations)
}
None => true,
};
}
@@ -2350,7 +2246,6 @@ fn collect_selectors_with_set_operations<'a>(
return collect_selectors_with_set_operations(
stmt,
&subquery.expr,
under_rate_or_increase,
out,
set_operations,
);
@@ -2616,13 +2511,12 @@ mod tests {
assert!(collect_selectors_with_set_operations(
&statement,
&expr,
false,
&mut selectors,
&mut Vec::new()
));
selectors
.iter()
.map(|(selector, _)| selector.name.clone().unwrap_or_default())
.map(|selector| selector.name.clone().unwrap_or_default())
.collect()
}
+34 -20
View File
@@ -5153,10 +5153,9 @@ async fn native_fused_or_matchers_fall_back() {
}
}
/// `rate` and `increase` over a table carrying the OTLP temporality marker run natively when they
/// read the raw window themselves: the window picks the delta math per series, as the existing
/// planner does. Read through another expression - here a subquery - the call has no raw window to
/// switch, and the statement keeps the existing plan.
/// `rate` and `increase` over a table carrying the OTLP temporality marker run natively, also
/// through a subquery: the window picks the delta math per series from the labels that reach it,
/// as the existing planner does.
#[tokio::test]
async fn native_fused_delta_temporality_rates_run_natively() {
for query in [
@@ -5167,6 +5166,8 @@ async fn native_fused_delta_temporality_rates_run_natively() {
"sum(rate(some_metric[5m]))",
"sum(increase(some_metric[5m]))",
"max_over_time(rate(some_metric[5m])[10m:1m])",
"rate((some_metric)[5m:1m])",
"increase(some_metric[5m:1m])",
] {
let plan = build_native_fused_plan_with_provider(
query,
@@ -5181,22 +5182,35 @@ async fn native_fused_delta_temporality_rates_run_natively() {
);
assert_eq!(take_reported_decline(), None, "`{query}`");
}
let query = "rate((some_metric)[5m:1m])";
let plan = build_native_fused_plan_with_provider(
query,
true,
native_engine_temporality_marker_provider().await,
)
.await;
assert!(
find_fused_series(&plan).is_none(),
"`{query}`: {}",
plan.display_indent()
);
assert_eq!(
take_reported_decline(),
Some("delta_temporality_under_rate_or_increase")
);
}
/// `rate` and `increase` over native histograms marked as delta temporality run natively.
///
/// The existing plan picks the delta math only for float samples and rates a native histogram as a
/// counter whatever its marker says, so a native histogram window ignores the marker too, even
/// through a subquery.
#[tokio::test]
async fn native_fused_delta_temporality_histogram_rates_run_natively() {
for query in [
"rate(some_metric[5m])",
"increase(some_metric[5m])",
"histogram_count(rate(some_metric[5m]))",
"sum(rate(some_metric[5m]))",
"rate((some_metric)[5m:1m])",
] {
let plan = build_native_fused_plan_with_provider(
query,
true,
build_test_native_histogram_table_provider_with_marker("some_metric", true).await,
)
.await;
assert!(
find_fused_series(&plan).is_some(),
"`{query}`: {}",
plan.display_indent()
);
assert_eq!(take_reported_decline(), None, "`{query}`");
}
}
/// A marker on an unrelated selector must not prevent a native binary.
+162
View File
@@ -3160,6 +3160,168 @@ async fn native_promql_delta_temporality_corpus_matches_legacy() {
let legacy = eval_text(collected(native_tql_output(&instance, sql, false).await).await);
assert_eq!(legacy, native, "{sql}");
}
// A subquery keeps the marker on its evaluated series, so the outer window sums the delta
// series' points in it: 20 + 15 at 120 and 180, and 10 + 20 + 15 over 180s for `rate`.
for (sql, expected) in [
(
"TQL EVAL (180, 180, '1m') increase(delta_temporality[2m:1m])",
[("delta", 35.0), ("single", 7.0)],
),
(
"TQL EVAL (180, 180, '1m') rate(delta_temporality[3m:1m])",
[("delta", 45.0 / 180.0), ("single", 7.0 / 180.0)],
),
] {
observer.clear();
let output = collected(native_tql_output(&instance, sql, true).await).await;
assert!(observer.fused().is_some(), "{sql} must run natively");
let native = eval_text_rows(output, ReportedName::Nothing);
let legacy = eval_text(collected(native_tql_output(&instance, sql, false).await).await);
assert_eq!(legacy, native, "{sql}");
for (series, value) in expected {
let line = native
.lines()
.find(|line| line.contains(&format!("| {series} |")))
.unwrap_or_else(|| panic!("{sql}: no `{series}` row in {native}"));
let actual = line.rsplit_once(" | ").unwrap().1.parse::<f64>().unwrap();
assert!((actual - value).abs() <= 1e-12, "{sql}: {native}");
}
}
}
/// `rate` and `increase` over OTLP delta exponential histograms run natively and answer what the
/// existing plan answers.
///
/// OTLP ingest stores each delta point as a gauge-hinted native histogram whose start timestamp is
/// the previous point's end, with the series marked `otlp_aggregation_temporality="delta"`. Both
/// routes rate those histograms the same way whatever the marker says, and sum a float derived
/// from them that keeps the marker.
#[tokio::test(flavor = "multi_thread")]
async fn native_promql_otlp_delta_histogram_rates_match_legacy() {
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
use otel_arrow_rust::proto::opentelemetry::metrics::v1::exponential_histogram_data_point::Buckets;
use otel_arrow_rust::proto::opentelemetry::metrics::v1::{
AggregationTemporality, ExponentialHistogram, ExponentialHistogramDataPoint, Metric,
ResourceMetrics, ScopeMetrics, metric,
};
use servers::query_handler::OpenTelemetryProtocolHandler;
use session::protocol_ctx::{OtlpMetricCtx, ProtocolCtx};
let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
"native_promql_otlp_delta_histogram_rates",
))
.await;
let instance = standalone.fe_instance().clone();
let mut ctx = QueryContext::with_db_name(None);
ctx.set_protocol_ctx(ProtocolCtx::OtlpMetric(OtlpMetricCtx {
with_metric_engine: true,
..Default::default()
}));
let data_points = [(60, 10), (120, 20), (180, 15), (240, 40)]
.into_iter()
.map(|(end, count)| ExponentialHistogramDataPoint {
start_time_unix_nano: (end - 60) * 1_000_000_000,
time_unix_nano: end * 1_000_000_000,
count,
sum: Some(count as f64 * 1.5),
zero_threshold: 0.001,
positive: Some(Buckets {
offset: 0,
bucket_counts: vec![count],
}),
..Default::default()
})
.collect();
let request = ExportMetricsServiceRequest {
resource_metrics: vec![ResourceMetrics {
scope_metrics: vec![ScopeMetrics {
metrics: vec![Metric {
name: "otlp_delta_h".into(),
data: Some(metric::Data::ExponentialHistogram(ExponentialHistogram {
aggregation_temporality: AggregationTemporality::Delta as i32,
data_points,
})),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
};
let outcome = instance
.metrics(request, Arc::new(ctx), None)
.await
.unwrap();
assert_eq!(
(outcome.accepted_data_points, outcome.rejected_data_points),
(4, 0)
);
let values = |text: &str| {
text.lines()
.filter_map(|line| line.rsplit_once(" | ")?.1.parse::<f64>().ok())
.collect::<Vec<_>>()
};
for (sql, expected) in [
(
"TQL EVAL (180, 240, '1m') histogram_count(increase(otlp_delta_h[2m]))",
[30.0, 55.0].as_slice(),
),
(
"TQL EVAL (240, 240, '1m') increase(histogram_count(otlp_delta_h)[2m:1m])",
[55.0].as_slice(),
),
] {
let native = eval_text_rows(
collected(native_tql_output(&instance, sql, true).await).await,
ReportedName::Nothing,
);
assert_eq!(values(&native), expected, "{sql}: {native}");
}
for sql in [
"TQL EVAL (240, 240, '1m') histogram_count(rate(otlp_delta_h[3m]))",
"TQL EVAL (240, 240, '1m') histogram_sum(increase(otlp_delta_h[3m]))",
"TQL EVAL (180, 240, '1m') histogram_count(increase(otlp_delta_h[2m]))",
"TQL EVAL (240, 240, '1m') histogram_count(rate(otlp_delta_h[2m] offset 1m))",
"TQL EVAL (240, 240, '1m') increase(histogram_count(otlp_delta_h)[2m:1m])",
"TQL EVAL (240, 240, '1m') rate(histogram_sum(otlp_delta_h)[3m:1m])",
] {
observer.clear();
let output = native_tql_output(&instance, sql, true).await;
let native = eval_text_rows(collected(output).await, ReportedName::Nothing);
assert!(observer.fused().is_some(), "{sql}");
let legacy = eval_text(collected(native_tql_output(&instance, sql, false).await).await);
// The two routes extrapolate in a different order, so the value may differ in its last
// digits; everything else is compared exactly.
let rows = |text: &str| {
text.lines()
.map(|line| {
let (labels, value) = line.rsplit_once(" | ").unwrap();
(labels.to_string(), value.parse::<f64>().ok())
})
.collect::<Vec<_>>()
};
let (native_rows, legacy_rows) = (rows(&native), rows(&legacy));
assert!(legacy_rows.len() > 1, "{sql} answers nothing: {legacy}");
assert_eq!(
native_rows.len(),
legacy_rows.len(),
"{sql}: {native} vs {legacy}"
);
for ((native_labels, native_value), (legacy_labels, legacy_value)) in
native_rows.iter().zip(&legacy_rows)
{
assert_eq!(native_labels, legacy_labels, "{sql}: {native} vs {legacy}");
match (native_value, legacy_value) {
(Some(native_value), Some(legacy_value)) => assert!(
(native_value - legacy_value).abs() <= 1e-12 * legacy_value.abs().max(1.0),
"{sql}: {native} vs {legacy}"
),
(native_value, legacy_value) => {
assert_eq!(native_value, legacy_value, "{sql}: {native} vs {legacy}")
}
}
}
}
}
/// `output` with its stream read here: [`eval_text_rows`] blocks on the stream, which inside this
+126
View File
@@ -46,6 +46,7 @@ use common_frontend::slow_query_event::{
};
use common_memory_manager::OnExhaustedPolicy;
use common_options::plugin_options::StandaloneFlag;
use common_query::prelude::{GREPTIME_TEMPORALITY_DELTA, OTLP_AGGREGATION_TEMPORALITY_LABEL};
use datafusion::common::{DFSchema, ToDFSchema};
use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
use datafusion::physical_plan::metrics::MetricValue;
@@ -204,6 +205,7 @@ macro_rules! http_tests {
test_remote_write_v2_histogram_avg_native_partitions,
test_remote_write_v2_histogram_multi_input_aggregate_native_route,
test_remote_write_v2_histogram_sum_incompatible_layouts_warns,
test_remote_write_v2_histogram_delta_temporality_native_route,
test_remote_write_v2_histogram_native_annotations,
test_remote_write_v2_histogram_native_arithmetic,
test_remote_write_v2_histogram_native_composition,
@@ -7866,6 +7868,130 @@ pub async fn test_remote_write_v2_histogram_sum_incompatible_layouts_warns(
);
}
/// `rate` and `increase` over a native histogram marked as OTLP delta temporality run natively and
/// answer what the existing path answers.
///
/// The existing path sums the window only for float samples; a native histogram is rated as a
/// counter whatever its marker says. So the marked series `job="d"` must answer the value the
/// existing path answers, which is what the unmarked series `job="c"` with the same samples
/// answers.
pub async fn test_remote_write_v2_histogram_delta_temporality_native_route(
store_type: StorageType,
) {
let observer = Arc::new(NativeFusedObserver::default());
let plugins = Plugins::default();
let wrapper: PhysicalPlanWrapperRef = observer.clone();
plugins.insert(wrapper);
let instance = tests_integration::standalone::GreptimeDbStandaloneBuilder::new(
"remote_write_v2_histogram_delta_temporality",
)
.with_default_store_type(store_type)
.with_query_options(QueryOptions {
experimental_native_promql: true,
..Default::default()
})
.with_plugin(plugins)
.build()
.await;
let server = build_test_prom_server(instance.fe_instance().clone(), false, None)
.with_greptime_config_options(instance.opts.datanode_options().to_toml().unwrap())
.build();
let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
let metric = "nh_delta";
for (timestamp, count, sum) in [(1_000, 2, 1.0), (31_000, 6, 3.0), (61_000, 10, 5.0)] {
write_native_histogram_sample(
&client,
&[
(prom_store::METRIC_NAME_LABEL, metric),
("job", "d"),
(
OTLP_AGGREGATION_TEMPORALITY_LABEL,
GREPTIME_TEMPORALITY_DELTA,
),
],
1,
vec![],
timestamp,
count,
sum,
)
.await;
write_native_histogram_sample(
&client,
&[(prom_store::METRIC_NAME_LABEL, metric), ("job", "c")],
1,
vec![],
timestamp,
count,
sum,
)
.await;
}
async fn query(client: &TestClient, promql: &str, native: bool) -> Value {
let hints = format!("query.experimental_native_promql={native}");
let response = client
.get(&format!(
"/v1/prometheus/api/v1/query?query={}&time=61",
encode(promql)
))
.header("x-greptime-hints", &hints)
.send()
.await;
assert_eq!(
response.status(),
StatusCode::OK,
"`{promql}` failed with {hints}"
);
let body: Value = response.json().await;
body["data"]["result"].clone()
}
for template in [
"rate(nh_delta{job=\"JOB\"}[1m])",
"increase(nh_delta{job=\"JOB\"}[2m])",
"histogram_count(increase(nh_delta{job=\"JOB\"}[2m]))",
"sum(rate(nh_delta{job=\"JOB\"}[2m]))",
"rate((nh_delta{job=\"JOB\"})[1m:30s])",
] {
let marked = template.replace("JOB", "d");
observer.clear();
let native = query(&client, &marked, true).await;
observer.take_all(&marked);
let legacy = query(&client, &marked, false).await;
assert_eq!(
1,
native.as_array().map_or(0, Vec::len),
"`{marked}` answers one series: {native}"
);
let value = |result: &Value| {
let sample = &result[0];
if sample["histogram"].is_null() {
sample["value"][1].clone()
} else {
sample["histogram"][1].clone()
}
};
// Values only: the existing path keeps `__name__` on a native histogram `rate`, which
// Prometheus drops, as this route does.
assert_eq!(
value(&legacy),
value(&native),
"`{marked}`: native and existing answers differ: {native} vs {legacy}"
);
assert!(
native[0]["metric"].get("__name__").is_none(),
"`{marked}` drops the metric name: {native}"
);
let cumulative = query(&client, &template.replace("JOB", "c"), true).await;
assert_eq!(
value(&cumulative),
value(&native),
"`{marked}` answers what the unmarked series does: {native} vs {cumulative}"
);
}
}
/// A tree that reads several native-histogram metrics and folds or reduces what it pairs runs
/// natively and answers what the existing path answers.
///