From c573f9e87cadb6b7e45f52b35f960359a6f2e5d8 Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Mon, 30 Nov 2026 11:56:24 +0000 Subject: [PATCH] feat(promql): answer integer fields natively as Float64 (#10668) * feat(promql): answer integer fields natively as Float64 The native PromQL route declined statements whose legacy plan publishes an integer field's own type (bare selectors, sum over integers, count, count_values) with `field_keeps_its_own_type`. In Prometheus every sample is a float64, and the raw series scan already casts numeric fields to Float64, so the native route now answers these shapes with Float64 values instead of declining. Integer samples are cast before any fold, so a sum of integers beyond 2^53 follows float64 arithmetic, as Prometheus does. Signed-off-by: Dennis Zhuang * test(promql): check the existing plan sums the large integers exactly Signed-off-by: Dennis Zhuang --------- Signed-off-by: Dennis Zhuang --- src/promql/AGENTS.md | 6 +- src/query/src/promql/planner/native.rs | 186 ++------------------- src/query/src/promql/planner/test.rs | 114 ++++--------- tests-integration/src/tests/promql_test.rs | 182 +++++++++----------- tests-integration/tests/http.rs | 12 ++ 5 files changed, 138 insertions(+), 362 deletions(-) diff --git a/src/promql/AGENTS.md b/src/promql/AGENTS.md index 08f7638a91d..891fe19f269 100644 --- a/src/promql/AGENTS.md +++ b/src/promql/AGENTS.md @@ -41,8 +41,10 @@ aggregate on each scan partition is globally complete. The native `timestamp` operation evaluates on its input grid. A tree without a source (a literal, `time()`, `vector(s)`) is materialized on its bound grid -without a scan. Native `count` produces Float64 values, unlike the legacy -PromQL path's Int64 count. Native SQL/TQL output is not necessarily +without a scan. Native answers every numeric field as Float64, as a Prometheus +sample is a float64: integer samples are cast before any fold, and a bare +selector, `sum` or `count` publishes Float64 where the legacy path keeps the +field's integer type or builds Int64. Native SQL/TQL output is not necessarily schema-identical to legacy output. The native tree and its compiler describe the implemented model, not the whole diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index a74e39d4c4a..faf10b8db2d 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -66,7 +66,6 @@ pub(crate) use promql::native::segment::{ }; use promql::range_eval::RangeFunction; use promql_parser::label::{METRIC_NAME, MatchOp, Matcher, Matchers}; -use promql_parser::parser::token; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, SubqueryExpr, VectorSelector, @@ -279,8 +278,6 @@ impl PromPlanner { &mut self, matchers: Matchers, under_rate_or_increase: bool, - // Decides whether the existing plan reports a numeric field as `Float64`. - statement_expr: &PromExpr, logical_scan_id: &mut Option, logical_ids_differ: &mut bool, statement_kind: &mut Option, @@ -398,24 +395,14 @@ impl PromPlanner { let split_series = !table_meta .partition_column_names() .all(|column| tags.iter().any(|tag| tag == column)); - // Every field must read as one kind: `Float64` or the native histogram struct. The raw scan - // casts numeric fields to `Float64`, but the existing plan keeps a numeric field's own type - // for shapes that do not cast (a bare selector, `sum` of integers, `count`); those decline - // so the output column type does not change. - let mut keeps_its_own_type = false; + // Every field must read as one kind: `Float64` or the native histogram struct; any other + // type, or a statement whose fields disagree, keeps the existing plan. The raw scan casts + // numeric fields to `Float64`, and the answer publishes `Float64` even where the existing + // plan keeps the field's own type, as in the Prometheus data model. let read_types = fields .iter() - .map(|field| { - Self::field_column_type(input.schema(), field).map(|data_type| { - keeps_its_own_type |= is_raw_numeric(data_type) - && !publishes_float_values(statement_expr, data_type); - read_field_type(data_type, statement_expr) - }) - }) + .map(|field| Self::field_column_type(input.schema(), field).map(read_field_type)) .collect::>(); - if keeps_its_own_type { - return Ok(declined("field_keeps_its_own_type")); - } let Some(field_kind) = uniform_field_kind(read_types.iter().map(|data_type| data_type.as_ref())) else { @@ -964,7 +951,6 @@ impl PromPlanner { .prepare_one_scan( matchers.clone(), *under_rate_or_increase, - &stmt.expr, &mut logical_scan_id, &mut logical_ids_differ, &mut statement_kind, @@ -1080,7 +1066,6 @@ impl PromPlanner { .prepare_one_scan( matchers, *under_rate_or_increase, - &stmt.expr, &mut logical_scan_id, &mut logical_ids_differ, &mut statement_kind, @@ -2415,12 +2400,12 @@ fn supports_native_raw_series(engine: &str) -> bool { matches!(engine, MITO_ENGINE | MITO2_ENGINE | METRIC_ENGINE) } -/// The type the raw series scan hands one field of `statement` to the fused node as. +/// The type the raw series scan hands one field to the fused node as. /// -/// A numeric field reads as `Float64` only where the existing plan also publishes `Float64` -/// ([`publishes_float_values`]); any other type is returned unchanged for the field-kind guard. -fn read_field_type(data_type: &ArrowDataType, statement: &PromExpr) -> ArrowDataType { - if is_raw_numeric(data_type) && publishes_float_values(statement, data_type) { +/// The type the raw scan hands over for a field: `Float64` for a numeric one; any other type is +/// returned unchanged for the field-kind guard. +fn read_field_type(data_type: &ArrowDataType) -> ArrowDataType { + if is_raw_numeric(data_type) { ArrowDataType::Float64 } else { data_type.clone() @@ -2446,157 +2431,6 @@ fn is_raw_numeric(data_type: &ArrowDataType) -> bool { ) } -/// The range functions whose existing-plan UDF (`promql::functions`) returns `Float64` for any -/// numeric window, so `rate(integer_field[5m])` publishes `Float64`. -const FLOAT_ANSWERING_RANGE_FUNCTIONS: &[&str] = &[ - "avg_over_time", - "changes", - "count_over_time", - "delta", - "deriv", - "double_exponential_smoothing", - "holt_winters", - "idelta", - "increase", - "irate", - "last_over_time", - "max_over_time", - "min_over_time", - "predict_linear", - "present_over_time", - "quantile_over_time", - "rate", - "resets", - "stddev_over_time", - "stdvar_over_time", - "sum_over_time", -]; - -/// The type class the existing planner publishes for one expression over one field. Not a boolean -/// because `sum` keeps an integer's type but widens `Float32` to `Float64`. -#[derive(Clone, Copy, PartialEq, Eq)] -enum PublishedValues { - Float64, - /// `Float16` or `Float32`. - NarrowFloat, - /// Any signed or unsigned integer. - Integer, - /// A type or shape not modeled here; never admitted. - Other, -} - -/// Whether the existing planner publishes a `Float64` for `field_type` under `statement`. -/// -/// Anything not proved is `false`, which declines. Proved, with the existing planner's deciding -/// site: -/// -/// - arithmetic: `PromPlanner::prom_token_to_binary_expr_builder` wraps operands in `cast_float`, -/// unless an operand folds before the cast ([`folds_before_cast`]), -/// - `min`/`max` (`Extremum`) and `avg`, `stddev`, `stdvar`, `quantile`, `group` -/// (`PromPlanner::create_numeric_aggregate_expr`) return `Float64`, -/// - `sum` returns `Float64` for float input and the input type for integers, -/// - [`FLOAT_ANSWERING_RANGE_FUNCTIONS`]. -/// -/// Parentheses, subqueries and the selecting aggregates publish their input's class; a bare -/// selector publishes the field's own type. Not proved: `count`/`count_values` (`Int64`), math and -/// label functions, `-x`, comparisons and set operations. -fn publishes_float_values(statement: &PromExpr, field_type: &ArrowDataType) -> bool { - published_values(statement, field_type) == PublishedValues::Float64 -} - -/// The class [`publishes_float_values`] reads: what the existing plan publishes for `statement`. -fn published_values(statement: &PromExpr, field_type: &ArrowDataType) -> PublishedValues { - match statement { - PromExpr::Paren(ParenExpr { expr }) => published_values(expr, field_type), - PromExpr::Subquery(SubqueryExpr { expr, .. }) => published_values(expr, field_type), - PromExpr::VectorSelector(_) | PromExpr::MatrixSelector(_) => field_values(field_type), - // Comparisons and set operations are not modeled. - PromExpr::Binary(binary) => { - let arithmetic = matches!( - binary.op.id(), - token::T_ADD - | token::T_SUB - | token::T_MUL - | token::T_DIV - | token::T_MOD - | token::T_POW - | token::T_ATAN2 - ); - if !arithmetic - || folds_before_cast(&binary.lhs, field_type) - || folds_before_cast(&binary.rhs, field_type) - { - PublishedValues::Other - } else { - PublishedValues::Float64 - } - } - PromExpr::Aggregate(aggregate) => match aggregate.op.id() { - token::T_MIN - | token::T_MAX - | token::T_AVG - | token::T_STDDEV - | token::T_STDVAR - | token::T_QUANTILE - | token::T_GROUP => PublishedValues::Float64, - token::T_SUM => match published_values(&aggregate.expr, field_type) { - PublishedValues::Float64 | PublishedValues::NarrowFloat => PublishedValues::Float64, - PublishedValues::Integer => PublishedValues::Integer, - PublishedValues::Other => PublishedValues::Other, - }, - token::T_COUNT | token::T_COUNT_VALUES => PublishedValues::Integer, - token::T_TOPK | token::T_BOTTOMK | token::T_LIMITK | token::T_LIMIT_RATIO => { - published_values(&aggregate.expr, field_type) - } - _ => PublishedValues::Other, - }, - PromExpr::Call(call) => { - if FLOAT_ANSWERING_RANGE_FUNCTIONS.contains(&call.func.name) { - PublishedValues::Float64 - } else { - PublishedValues::Other - } - } - _ => PublishedValues::Other, - } -} - -/// Whether `statement` folds samples into a non-float before an arithmetic `cast_float` reaches -/// them. -/// -/// The existing plan then folds exactly (`sum` of `Int64` adds integers) while the raw scan casts -/// first; integers above `2^53` can answer differently, so `sum(integer_field) * 1` declines. -fn folds_before_cast(statement: &PromExpr, field_type: &ArrowDataType) -> bool { - match statement { - PromExpr::Paren(ParenExpr { expr }) => folds_before_cast(expr, field_type), - PromExpr::Subquery(SubqueryExpr { expr, .. }) => folds_before_cast(expr, field_type), - PromExpr::Binary(binary) => { - folds_before_cast(&binary.lhs, field_type) || folds_before_cast(&binary.rhs, field_type) - } - PromExpr::Unary(unary) => folds_before_cast(&unary.expr, field_type), - PromExpr::Aggregate(_) => !publishes_float_values(statement, field_type), - // Selectors, literals and calls hand over single samples; nothing folds before the cast. - _ => false, - } -} - -/// What a bare selector over a field of this type publishes. -fn field_values(field_type: &ArrowDataType) -> PublishedValues { - match field_type { - ArrowDataType::Float64 => PublishedValues::Float64, - ArrowDataType::Float16 | ArrowDataType::Float32 => PublishedValues::NarrowFloat, - ArrowDataType::Int8 - | ArrowDataType::Int16 - | ArrowDataType::Int32 - | ArrowDataType::Int64 - | ArrowDataType::UInt8 - | ArrowDataType::UInt16 - | ArrowDataType::UInt32 - | ArrowDataType::UInt64 => PublishedValues::Integer, - _ => PublishedValues::Other, - } -} - /// Recognizes the metric logical-table scan emitted by `create_table_scan_plan` and returns the /// physical scan, its `__table_id = ` predicate, and the id. fn metric_scan_and_table_id( diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 9069a6a6e57..f3f9d40c770 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -5065,64 +5065,29 @@ async fn native_fused_unsupported_field_type_falls_back() { } } -/// A numeric field the raw scan casts is admitted only under the shapes whose existing plan -/// publishes a `Float64` for it too. +/// A numeric field is answered as `Float64` whatever the shape of the statement. /// -/// The scan hands the node a `Float64` (`series_scan/raw.rs` casts every numeric field), while the -/// fused node declares one `Float64` value column per field. The existing planner publishes that same -/// float for an arithmetic argument, for `min`/`max`/`avg`/`stddev`/`stdvar`/`quantile`/`group` and for -/// a range function, but copies the field's own type through a bare selector, `sum` over an integer, -/// `count`, `count_values`, `abs` and the other math functions. Admission therefore follows the shape, -/// and a shape whose existing plan publishes the field's own type keeps that plan. +/// The raw scan casts every numeric field to `Float64`, and a Prometheus sample is a `float64`, so the +/// route publishes a float where the existing plan copies the field's own type: a bare selector, `sum` +/// over an integer, `count`, `count_values`, a math function, a negation and a comparison. #[tokio::test] -async fn native_fused_numeric_field_admission_follows_the_shape() { +async fn native_fused_numeric_fields_answer_float64() { use ConcreteDataType as Dt; - for (field_type, query, admitted) in [ - // A bare selector reports the field's own type, so it keeps the existing plan. - (Dt::int64_datatype(), "some_metric", false), - (Dt::float32_datatype(), "some_metric", false), - (Dt::uint64_datatype(), "some_metric", false), - // Arithmetic casts both operands, so the answer is a float under either route. - (Dt::int64_datatype(), "some_metric * 2", true), - (Dt::int64_datatype(), "some_metric + some_metric", true), - (Dt::float32_datatype(), "some_metric * 2", true), - (Dt::uint64_datatype(), "some_metric + some_metric", true), - // An aggregate whose UDAF answers a float for every numeric input. - (Dt::int64_datatype(), "min(some_metric)", true), - (Dt::int64_datatype(), "max(some_metric)", true), - (Dt::int64_datatype(), "avg(some_metric)", true), - (Dt::int64_datatype(), "stddev(some_metric)", true), - (Dt::uint64_datatype(), "quantile(0.5, some_metric)", true), - (Dt::int64_datatype(), "group(some_metric)", true), - // `sum` folds a float as a `Float64` and keeps an integer's own type. - (Dt::float32_datatype(), "sum(some_metric)", true), - (Dt::int64_datatype(), "sum(some_metric)", false), - (Dt::uint64_datatype(), "sum(some_metric)", false), - // `sum` publishes what it folds, so an integer answer one level down stays out as well. - ( - Dt::float32_datatype(), - r#"sum(count_values("v", some_metric))"#, - false, - ), - // A range function answers a `Float64` for every numeric input. - (Dt::int64_datatype(), "rate(some_metric[5m])", true), - (Dt::int64_datatype(), "increase(some_metric[5m])", true), - (Dt::int64_datatype(), "sum_over_time(some_metric[5m])", true), - (Dt::uint64_datatype(), "changes(some_metric[5m])", true), - (Dt::float32_datatype(), "rate(some_metric[5m])", true), - // A count is an `Int64` whatever the field holds. - (Dt::int64_datatype(), "count(some_metric)", false), - ( - Dt::float32_datatype(), - r#"count_values("v", some_metric)"#, - false, - ), - // A math function keeps the type it is given, and so does a negation. - (Dt::int64_datatype(), "abs(some_metric)", false), - (Dt::int64_datatype(), "-some_metric", false), - // A comparison without `bool` filters on the field's own column. - (Dt::int64_datatype(), "some_metric > 2", false), + for (field_type, query) in [ + (Dt::int64_datatype(), "some_metric"), + (Dt::float32_datatype(), "some_metric"), + (Dt::uint64_datatype(), "some_metric"), + (Dt::int32_datatype(), r#"some_metric{tag_0=""}"#), + (Dt::int64_datatype(), "sum(some_metric)"), + (Dt::uint64_datatype(), "sum(some_metric)"), + (Dt::int64_datatype(), "count(some_metric)"), + (Dt::int64_datatype(), r#"count_values("v", some_metric)"#), + (Dt::int64_datatype(), "sum(some_metric) * 1"), + (Dt::int64_datatype(), "abs(some_metric)"), + (Dt::int64_datatype(), "-some_metric"), + (Dt::int64_datatype(), "some_metric > 2"), + (Dt::int64_datatype(), "topk(1, some_metric)"), ] { let native = build_native_fused_plan_with_provider( query, @@ -5130,37 +5095,18 @@ async fn native_fused_numeric_field_admission_follows_the_shape() { build_test_table_provider_with_field_type(field_type.clone()).await, ) .await; - if admitted { - let fused = find_fused_series(&native).unwrap_or_else(|| { - panic!( - "{query} over {field_type} must reach the native route: {}", - native.display_indent_schema() - ) - }); - // The value column is the one kind the node publishes, which is what the existing plan - // publishes for this shape too. - assert_eq!( - &ArrowDataType::Float64, - native_value_field(fused, query).data_type(), - "{query} over {field_type} publishes a float" - ); - } else { - let without_flag = build_native_fused_plan_with_provider( - query, - false, - build_test_table_provider_with_field_type(field_type.clone()).await, + let fused = find_fused_series(&native).unwrap_or_else(|| { + panic!( + "{query} over {field_type} must reach the native route: {}", + native.display_indent_schema() ) - .await; - assert!( - find_fused_series(&native).is_none(), - "{query} over {field_type} must not reach the native route" - ); - assert_eq!( - native.display_indent().to_string(), - without_flag.display_indent().to_string(), - "{query} over {field_type} must keep the existing plan" - ); - } + }); + assert_eq!( + &ArrowDataType::Float64, + native_value_field(fused, query).data_type(), + "{query} over {field_type} publishes a float" + ); + assert_eq!(None, take_reported_decline(), "{query} over {field_type}"); } } diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 9f0d18cde39..974f5b4f079 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -13635,19 +13635,19 @@ async fn native_answer(output: Output) -> Answer { } } -/// A numeric field the raw series scan casts to a float is admitted only under the shapes whose -/// existing plan publishes a `Float64` for it too, and the answer is that plan's answer. +/// A numeric field is answered as `Float64` under every shape, with the existing plan's values. /// /// The table holds one integer and one float field, so every statement below reads both: the scan /// casts the integer to a `Float64` and the fused node declares one `Float64` value column per field. -/// That is the column the existing plan publishes for an arithmetic operand, for a range function and -/// for `min`/`max`/`avg`, so those shapes are admitted and must answer the same columns and rows. A -/// bare selector and `sum` keep the existing plan instead: the first copies the field's own type and -/// the second folds an integer as an integer, so a `Float64` column would not be the column reported. +/// For an arithmetic operand, a range function and `min`/`max`/`avg` that is the column the existing +/// plan publishes too. A bare selector, `sum` and `count` publish an integer column there instead, +/// while a Prometheus sample is a `float64`, so the native answer keeps its float column and only the +/// values are compared with the existing plan's. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_answers_a_numeric_field_where_the_shape_publishes_a_float() { +async fn native_promql_answers_numeric_fields_as_float64() { common_telemetry::init_default_ut_logging(); const TABLE: &str = "native_numeric_shape"; + const INTEGER: &str = "native_numeric_shape_int"; let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( "native_promql_numeric_shape", )) @@ -13660,73 +13660,68 @@ async fn native_promql_answers_a_numeric_field_where_the_shape_publishes_a_float INSERT INTO {TABLE} (host, ts, i, f) VALUES \ ('a', 0, 1, 1.5), ('b', 0, 2, 2.5), \ ('a', 1000, 3, 3.5), ('b', 1000, 4, 4.5), \ - ('a', 2000, 5, 5.5), ('b', 2000, 6, 6.5);" + ('a', 2000, 5, 5.5), ('b', 2000, 6, 6.5); \ + CREATE TABLE {INTEGER} (host STRING, ts TIMESTAMP(3) TIME INDEX, v BIGINT, PRIMARY KEY (host)); \ + INSERT INTO {INTEGER} (host, ts, v) VALUES \ + ('a', 0, 1), ('b', 0, 1), ('', 0, 7), \ + ('a', 2000, 3), ('b', 2000, 5), ('', 2000, 7);" ), QueryContext::arc(), ) .await; execute_all( &instance, - &format!("ADMIN FLUSH_TABLE('{TABLE}')"), + &format!("ADMIN FLUSH_TABLE('{TABLE}'); ADMIN FLUSH_TABLE('{INTEGER}');"), QueryContext::arc(), ) .await; for query in [ - // Arithmetic casts both operands, so `i` and `f` are folded as floats. format!("{TABLE} * 2"), format!("{TABLE} - {TABLE}"), - // `min`, `max` and `avg` answer a `Float64` for every numeric input. format!("min({TABLE})"), format!("max({TABLE})"), format!("avg({TABLE})"), - // A range function's value window and answer are both `Float64`. format!("rate({TABLE}[2s])"), format!("sum(rate({TABLE}[2s]))"), + // The existing plan publishes the integer field's own type for these. + TABLE.to_string(), + format!("sum({TABLE})"), + format!("count({TABLE})"), + INTEGER.to_string(), + format!("{INTEGER}{{host=\"\"}}"), + format!("sum({INTEGER})"), + format!("count({INTEGER})"), + // The counted value is written into the label in Go's `'f'` form: `1`, not `1.0`. + format!("count_values(\"v\", {INTEGER})"), ] { - let sql = format!("TQL EVAL (2, 2, '1s') {query}"); + let sql = format!("TQL EVAL (0, 2, '1s') {query}"); observer.clear(); let native = native_answer(native_tql_output(&instance, &sql, true).await).await; - let answering_node = observer.answering_node(); assert_eq!( Some("FusedSeriesExec".to_string()), - answering_node, + observer.answering_node(), "`{query}` must answer from the fused node, not the existing plan" ); - // Both fields of the table are value columns, whatever the shape: the integer is read as the - // float the existing plan publishes for this shape. - assert_eq!( - vec![DataType::Float64, DataType::Float64], - native.value_types, - "`{query}`: one float value column per field of the table" - ); - let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await; - assert_eq!( - native, legacy, - "`{query}`: the value types and the rows must be the existing plan's" - ); - } - - // A bare selector copies the value column's own type, so it keeps the existing plan: the - // `BIGINT` field would come back as a `Float64` under the fused node. - for query in [TABLE.to_string(), format!("sum({TABLE})")] { - let sql = format!("TQL EVAL (2, 2, '1s') {query}"); - observer.clear(); - let native = native_answer(native_tql_output(&instance, &sql, true).await).await; assert!( - observer.fused().is_none(), - "`{query}` must keep the existing plan: a shape that does not publish a float for an \ - integer field would report a different column than the existing plan" - ); - let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await; - assert_eq!(native, legacy, "`{query}`: the existing plan answers it"); - // The reason the shape keeps the existing plan: the integer field is reported as an integer, - // which is the column the fused node would have to publish as a `Float64`. - assert!( - native.value_types.contains(&DataType::Int64), - "`{query}`: the existing plan reports the integer field as an `Int64`: {:?}", + native + .value_types + .iter() + .all(|data_type| data_type == &DataType::Float64), + "`{query}`: one float value column per field: {:?}", native.value_types ); + let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await; + assert_eq!( + native.value_types.len(), + legacy.value_types.len(), + "`{query}`: one value column per field on both routes" + ); + assert_eq!( + numeric_rows(&native), + numeric_rows(&legacy), + "`{query}`: the rows must be the existing plan's" + ); } // A field the raw series preflight refuses has no float to publish, whatever the shape is. These @@ -13777,28 +13772,45 @@ async fn native_run_ignoring_the_answer(instance: &Arc, sql: &str, ena } } -/// An arithmetic operator casts both operands, but the cast is the operator's, so it reaches whatever -/// an operand answers. Where that operand *folds* raw samples into an integer, the existing plan folds -/// exactly and casts the fold, while the raw series scan casts every sample and only then folds: two -/// integers above `2^53` that cancel answer `1` before the cast and `0` after it. The shape therefore -/// keeps the existing plan, while a fold that is a float fold - `sum` over a range function's window - -/// is admitted as before. +/// The rows of an [`Answer`] with each value read as the float it prints, so an integer column and +/// a float column holding the same numbers compare equal. +fn numeric_rows( + answer: &Answer, +) -> Vec<(i64, std::collections::BTreeMap, Vec)> { + answer + .rows + .iter() + .map(|(time, labels, values)| { + ( + *time, + labels.clone(), + values + .iter() + .map(|value| value.parse::().unwrap()) + .collect(), + ) + }) + .collect() +} + +/// An integer sample is a `float64` before anything folds it, as every Prometheus sample is. +/// +/// `9007199254740993` is not a `Float64`: it rounds to `9007199254740992`, which is what makes the +/// order of the cast and the fold visible. The existing plan sums the two `BIGINT`s exactly and +/// answers `1`; the native route casts each sample first, so the two cancel and `sum` answers `0`. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_declines_a_cast_over_an_integer_fold() { +async fn native_promql_casts_integer_samples_before_folding() { common_telemetry::init_default_ut_logging(); const TABLE: &str = "native_late_cast"; let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new("native_promql_late_cast")).await; let instance = standalone.fe_instance().clone(); - // `9007199254740993` is not a `Float64`: it rounds to `9007199254740992`, which is what makes the - // order of the cast and the fold visible. Two series, so `sum` folds them into one value per step. execute_all( &instance, &format!( "CREATE TABLE {TABLE} (host STRING, ts TIMESTAMP(3) TIME INDEX, v BIGINT, PRIMARY KEY (host)); \ INSERT INTO {TABLE} (host, ts, v) VALUES \ - ('a', 0, 9007199254740993), ('a', 60000, 9007199254740993), \ - ('b', 0, -9007199254740992), ('b', 60000, -9007199254740992);" + ('a', 0, 9007199254740993), ('b', 0, -9007199254740992);" ), QueryContext::arc(), ) @@ -13810,46 +13822,25 @@ async fn native_promql_declines_a_cast_over_an_integer_fold() { ) .await; - // The integer sum is 1, and the cast is 1.0 whichever side of it the answer is read from: the - // existing plan sums the two `BIGINT`s exactly, so that is the answer these shapes keep. + // Without this the data might not cross 2^53, and both routes would answer the same sum. + let sql = format!("TQL EVAL (0, 0, '1m') sum({TABLE})"); + let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await; + assert_eq!( + legacy.rows, + vec![(0, Default::default(), vec!["1".to_string()])], + "the existing plan sums the `BIGINT`s exactly" + ); + for (query, expected) in [ - (format!("sum({TABLE}) * 1"), 1.0), - (format!("sum({TABLE}) + 1"), 2.0), + (format!("sum({TABLE})"), 0.0), + (format!("sum({TABLE}) + 1"), 1.0), ] { let sql = format!("TQL EVAL (0, 0, '1m') {query}"); - let legacy = native_rows(native_tql_output(&instance, &sql, false).await, None).await; - assert_eq!( - legacy, - vec![(0, String::new(), expected)], - "`{query}`: the existing plan sums the integers before it casts" - ); observer.clear(); let native = native_rows(native_tql_output(&instance, &sql, true).await, None).await; - assert!( - observer.fused().is_none(), - "`{query}` must keep the existing plan: the raw scan would round each value before it \ - summed them" - ); - assert_eq!( - native, legacy, - "`{query}`: an integer fold is exact, and a fused node cannot repeat that" - ); + assert!(observer.fused().is_some(), "`{query}` must be fused"); + assert_eq!(native, vec![(0, String::new(), expected)], "`{query}`"); } - - // The inner fold is a float fold here, so the outer cast reaches values that were floats already: - // the route takes the statement and answers the existing plan's rows. - let sql = format!("TQL EVAL (60000, 60000, '1m') sum(rate({TABLE}[5m]))"); - let legacy = native_rows(native_tql_output(&instance, &sql, false).await, None).await; - observer.clear(); - let native = native_rows(native_tql_output(&instance, &sql, true).await, None).await; - assert!( - observer.fused().is_some(), - "`sum(rate(...))` folds a float window and must stay admitted" - ); - assert_eq!( - native, legacy, - "`sum(rate(...))`: the fused route reports the existing plan's rows" - ); } /// Enabling Narthex index maintenance must preserve the ordinary Parquet raw scan. @@ -13911,15 +13902,6 @@ async fn native_promql_columnar_config_preserves_parquet_raw_scan() { ); } } - // A bare selector keeps its plan for a type reason, which is what this route decides: it reports - // the column's own `BIGINT`, which no fused node publishes. - let sql = format!("TQL EVAL (120, 120, '1m') {INTEGER}"); - observer.clear(); - let _ = native_tql_output(&instance, &sql, true).await; - assert!( - observer.fused().is_none(), - "a bare selector over an integer field must keep the existing plan" - ); } /// The positive counterpart of the test above: a sparse physical metric table whose series diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 791e90df9a2..ee7d30277a4 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -2412,7 +2412,9 @@ pub async fn test_prometheus_native_promql_route(store_type: StorageType) { "CREATE TABLE native_route (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING, PRIMARY KEY (host))", "CREATE TABLE native_zero (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING, PRIMARY KEY (host))", "CREATE TABLE native_empty (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING, PRIMARY KEY (host))", + "CREATE TABLE native_int (ts TIMESTAMP TIME INDEX, val BIGINT, host STRING, PRIMARY KEY (host))", "INSERT INTO native_route(host, val, ts) VALUES ('h1', 1.0, 0), ('h1', 2.0, 1000)", + "INSERT INTO native_int(host, val, ts) VALUES ('h1', 2, 1000), ('h2', 2, 1000)", "INSERT INTO native_zero(host, val, ts) VALUES ('z', 0.0, 0), ('z', 0.0, 1000)", ] { let res = client @@ -2456,6 +2458,16 @@ pub async fn test_prometheus_native_promql_route(store_type: StorageType) { json!({"resultType":"vector","result":[]}), ), ("native_empty", json!({"resultType":"vector","result":[]})), + // An integer field answers float samples, and `count_values` writes the value as Go's `'f'` + // form does. + ( + "native_int{host=\"h1\"}", + json!({"resultType":"vector","result":[{"metric":{"__name__":"native_int","host":"h1"},"value":[1.0,"2.0"]}]}), + ), + ( + "count_values(\"v\", native_int)", + json!({"resultType":"vector","result":[{"metric":{"v":"2"},"value":[1.0,"2.0"]}]}), + ), ]; for native in [false, true] { for (query, expected) in &instants {