fix(promql): plan a float function over a split native histogram sum (#10663)

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>
This commit is contained in:
dennis zhuang
2026-11-27 09:19:22 +00:00
committed by GitHub
parent 34cddcabaa
commit 95e69f80c3
3 changed files with 156 additions and 13 deletions
+9 -13
View File
@@ -2341,18 +2341,8 @@ fn plan_split_aggregate(
value_schema: DFSchemaRef,
format: FusedOutputFormat,
) -> Result<FusedSeries> {
// The kind a value column carries is the state's own: a numeric fold publishes `Float64`, a
// native-histogram fold publishes the histogram value type. Reading it here keeps the layout and
// the schema it is checked against in one place.
let (state_accumulators, value_type) = match &partial.root().output {
NativeType::AggregateState(state) => (
state.accumulators.len(),
if state.kind.is_histogram() {
native_histogram_value_type().as_arrow_type()
} else {
ArrowDataType::Float64
},
),
let state_accumulators = match &partial.root().output {
NativeType::AggregateState(state) => state.accumulators.len(),
_ => {
return Err(DataFusionError::Plan(format!(
"the partial tree for `{promql}` does not produce aggregate state"
@@ -2360,10 +2350,16 @@ fn plan_split_aggregate(
.context(DataFusionPlanningSnafu);
}
};
// The value columns carry the kind the statement's root answers, which need not be the state's:
// `histogram_count` or `histogram_quantile` above the cut turns a merged histogram state into
// floats. The layout declares one kind for all of them, so either value type identifies them.
let histogram_type = native_histogram_value_type().as_arrow_type();
let values = value_schema
.fields()
.iter()
.filter(|field| field.data_type() == &value_type)
.filter(|field| {
field.data_type() == &ArrowDataType::Float64 || field.data_type() == &histogram_type
})
.count();
if values != state_accumulators {
return Err(DataFusionError::Plan(format!(
+27
View File
@@ -12845,6 +12845,33 @@ async fn a_histogram_sum_over_stable_keys_keeps_its_split() {
}
}
/// A float function above a split histogram fold publishes a float column: the state crossing the
/// boundary is a histogram, but the statement's value columns follow its root.
#[tokio::test]
async fn a_float_function_over_a_split_histogram_fold_publishes_floats() {
for query in [
"histogram_count(sum(some_metric))",
"histogram_quantile(0.9, sum(rate(some_metric[2m])))",
] {
let table_provider =
build_test_native_histogram_table_provider_with_stable_keys("some_metric").await;
let plan = build_native_fused_plan_with_provider(query, true, table_provider).await;
let display = plan.display_indent_schema().to_string();
let final_node = find_final_split(&plan)
.unwrap_or_else(|| panic!("{query} kept the existing plan: {display}"));
assert!(
partial_below(final_node).is_some(),
"{query} lost the partial half of its split: {display}"
);
let field = native_value_field(final_node, query);
assert_eq!(
&ArrowDataType::Float64,
field.data_type(),
"{query}: {display}"
);
}
}
#[tokio::test]
async fn histogram_statements_run_natively_until_an_aggregate_folds_them() {
// A bare scan drops nothing, and `last_over_time` keeps the metric name, so neither hands out a
+120
View File
@@ -4398,6 +4398,126 @@ async fn native_promql_kind_rules_match_legacy() {
);
}
/// A float function above a split `sum` over native histograms runs natively and answers what the
/// existing plan and Prometheus answer.
///
/// Both series put half of each sample in the schema-0 bucket `(0.5, 1]` and half in `(1, 2]`, and
/// `a` grows twice as fast as `b`. `histogram_count(sum(h))` is the summed count, `6 * (i + 1)` at
/// the `i`-th minute. The summed rate keeps the even split, so the 0.9 quantile is 80% into
/// `(1, 2]` on Prometheus' logarithmic interpolation: `2^0.8`.
#[tokio::test(flavor = "multi_thread")]
async fn native_promql_float_function_over_split_histogram_sum_matches_legacy() {
use api::greptime_proto::io::prometheus::write::v2::histogram::Count;
use api::greptime_proto::io::prometheus::write::v2::{BucketSpan, Histogram};
use axum::body::{Body, to_bytes};
use http::Request;
use prost::Message;
use servers::prom_remote_write::v2::test_util as remote_write_v2;
use servers::prom_store::snappy_compress;
use tower::ServiceExt;
common_telemetry::init_default_ut_logging();
let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
"native_promql_float_function_over_split_histogram_sum",
))
.await;
let instance = standalone.fe_instance().clone();
let server = crate::test_util::build_test_prom_server(instance.clone(), false, None).build();
let router = server.build(server.make_app()).unwrap();
for (job, per_bucket) in [("a", 2_u64), ("b", 1_u64)] {
let request = remote_write_v2::request_with_labels_and_histograms(
vec![("__name__", "split_hist"), ("job", job)],
(0..=5_u64)
.map(|step| {
let bucket = per_bucket * (step + 1);
Histogram {
timestamp: (step * 60_000) as i64,
count: Some(Count::CountInt(2 * bucket)),
sum: 3.0 * bucket as f64,
schema: 0,
positive_spans: vec![BucketSpan {
offset: 0,
length: 2,
}],
positive_deltas: vec![bucket as i64, 0],
..Default::default()
}
})
.collect(),
);
let response = router
.clone()
.oneshot(
Request::post("/v1/prometheus/write")
.header("Content-Encoding", "snappy")
.header(
"Content-Type",
"application/x-protobuf;proto=io.prometheus.write.v2.Request",
)
.body(Body::from(
snappy_compress(&request.encode_to_vec()).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
204,
"{:?}",
to_bytes(response.into_body(), usize::MAX).await.unwrap()
);
}
let quantile = 0.8_f64.exp2();
for (query, expected) in [
(
"histogram_count(sum(split_hist))",
vec![
(120_000, 18.0),
(180_000, 24.0),
(240_000, 30.0),
(300_000, 36.0),
],
),
(
"histogram_quantile(0.9, sum(rate(split_hist[2m])))",
vec![
(120_000, quantile),
(180_000, quantile),
(240_000, quantile),
(300_000, quantile),
],
),
] {
let sql = format!("TQL EVAL (120, 300, '60s') {query}");
observer.clear();
let native = native_timestamp_rows(native_tql_output(&instance, &sql, true).await).await;
let root = observer.root_plan();
assert!(
holds_split_merge(&root),
"{query} did not run as a native split: {}",
datafusion::physical_plan::displayable(root.as_ref()).indent(true)
);
observer.clear();
let legacy = native_timestamp_rows(native_tql_output(&instance, &sql, false).await).await;
assert!(
observer.fused().is_none(),
"{query} must keep the existing plan when the native route is off"
);
for rows in [&native, &legacy] {
assert_eq!(rows.len(), expected.len(), "{query}: {rows:?}");
for ((ts, value), (expected_ts, expected_value)) in rows.iter().zip(&expected) {
assert_eq!(ts, expected_ts, "{query}: {rows:?}");
assert!(
(value - expected_value).abs() < 1e-9,
"{query}: {rows:?}, expected {expected:?}"
);
}
}
}
}
/// How many rows `output` answers, whatever its columns hold.
async fn answer_rows(output: Output) -> usize {
let batches = match output.data {