diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 037bcb49788..0e480338199 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -1650,12 +1650,6 @@ impl PromPlanner { grid, ))); } - // A segment reads assembled frames, and no single-input histogram fold runs over those. - // A tree over several inputs is segmented below its fold, which runs once above every - // operand's frames. - if !multi_input && binds_histogram_state_anywhere(root) { - return Ok(declined("histogram_state_above_a_segment_boundary")); - } } let output_tags = match &tree.root().output { NativeType::Scalar(_) => Vec::new(), @@ -2288,18 +2282,6 @@ fn binds_histogram_state(op: &BoundAggregate) -> bool { aggregate_state_binding(op.kind, op.field_kind).is_some_and(|(kind, _)| kind.is_histogram()) } -/// Whether any aggregate in `node` binds a state that carries a native histogram. -/// -/// Only the aggregate split carries histogram state across a partition boundary. -fn binds_histogram_state_anywhere(node: &NativeNode) -> bool { - node.any(&|node| { - matches!( - &node.expr, - NativeExpr::Aggregate { op, .. } if binds_histogram_state(op) - ) - }) -} - /// Whether the state a split tree exports is a native histogram's. /// /// Read from the partial tree's root, the cut aggregate. diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index ebb6a92a335..59ad0d3ac24 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -12337,7 +12337,7 @@ async fn native_histogram_plan(query: &str) -> String { plan.display_indent_schema().to_string() } -/// A histogram fold over a set operation runs natively; one over a collected rewrite does not. +/// A histogram fold over a set operation or a collapsing rewrite runs natively. /// /// A set operation hands its fold histograms of a kind its two sides agree on, so the fold binds /// histogram state and runs once above the set's frames. @@ -12367,15 +12367,8 @@ async fn histogram_folds_over_sets_and_collected_rewrites() { "{query} answers the histograms it folded: {display}" ); } - // `sum(label_replace(...))` is one of the shapes above. The rewrite collapses every series onto - // one `tag_0`, so the canonical pass collects it with a `Merge` on the fold's own input side - - // and a split keeps that merge inside its per-partition prefix, where the pieces of one label - // set are collected a partition at a time: two colliding series that landed in different - // partitions are each folded apart, their states are added above the router, and the statement - // answers a value where Prometheus reports `vector cannot contain metrics with the same - // labelset`. The split therefore refuses a merge, and a tree over one input that folds - // histogram state is not segmented either, so the statement keeps the existing plan and the - // collision is the existing route's to report. + // A fold over a collapsing rewrite reads what the canonical merge collected from every + // partition: the merge is a segment boundary, and the fold runs once above it natively. let table_provider = build_test_native_histogram_table_provider_with_stable_keys("some_metric").await; let plan = build_native_fused_plan_with_provider( @@ -12386,13 +12379,12 @@ async fn histogram_folds_over_sets_and_collected_rewrites() { .await; let display = plan.display_indent_schema().to_string(); assert!( - display.contains("Aggregate: groupBy=") - && display.contains("prom_native_histogram_agg_sum("), + !display.contains("prom_native_histogram_agg_sum("), "the collected histogram fold kept the existing plan: {display}" ); assert!( - find_fused_series(&plan).is_none(), - "the collected histogram fold ran a native fold per segment: {display}" + find_fused_series(&plan).is_some(), + "the collected histogram fold left the route: {display}" ); // A float-producing window still answers on the route: its count, not the input histogram, @@ -12738,9 +12730,8 @@ async fn a_segmented_histogram_answer_crosses_its_collected_boundary() { /// The gate cannot look at the root alone: `sum(h) * 2` has a binary root and the fold sits below /// it, so the value entering each aggregate is what decides. A scalar multiple of a histogram - a /// negation included - is a histogram, which this route's binary kernel answers, so those -/// statements run and publish the histogram column. The shapes whose state cannot cross keep the -/// existing plan instead, which `a_histogram_aggregate_the_split_declines_keeps_the_existing_plan` -/// pins. +/// statements run and publish the histogram column. The shapes the split declines are segmented +/// instead, which `a_histogram_fold_the_split_declines_is_segmented` pins. #[tokio::test] async fn a_histogram_fold_is_admitted_below_a_pointwise_operator() { for query in [ @@ -12833,27 +12824,19 @@ async fn presence_and_order_aggregates_fold_histograms_natively() { "{query} answers a count or a `1`, not a histogram: {display}" ); } - for query in [ - // A skipping or counting aggregate at the root does not excuse the payload-folding one - // below it: the split cannot carry an aggregate above an aggregate, and a segmented tree - // would fold each segment's histograms into an answer no segment owns. - "count(sum(some_metric))", - "min(sum(some_metric))", - ] { + // A skipping or counting aggregate above the payload-folding one is two cuts, which the split + // declines; the statement is segmented and the outer aggregate reads the folded histograms. + for query in ["count(sum(some_metric))", "min(sum(some_metric))"] { let table_provider = build_test_native_histogram_table_provider("some_metric").await; let plan = build_native_fused_plan_with_provider(query, true, table_provider).await; - assert!( - find_fused_series(&plan).is_none(), - "{query} ran a native fold over histograms: {}", - plan.display_indent_schema() - ); - // The two-aggregate cut declines the split, and a tree that folds histogram state has no - // segment execution here, so this is the refusal that answers it - recorded, not silent. + let display = plan.display_indent_schema().to_string(); + let fused = + find_fused_series(&plan).unwrap_or_else(|| panic!("{query} left the route: {display}")); + assert_eq!(None, take_reported_decline(), "{query}: {display}"); assert_eq!( - Some("histogram_state_above_a_segment_boundary"), - take_reported_decline(), - "{query}: {}", - plan.display_indent_schema() + &ArrowDataType::Float64, + native_value_field(fused, query).data_type(), + "{query} answers a count or nothing, not a histogram: {display}" ); } } @@ -12890,7 +12873,10 @@ async fn a_histogram_sum_over_stable_keys_keeps_its_split() { async fn a_float_function_over_a_split_histogram_fold_publishes_floats() { for query in [ "histogram_count(sum(some_metric))", + "histogram_sum(sum(some_metric))", + "histogram_avg(sum(some_metric))", "histogram_quantile(0.9, sum(rate(some_metric[2m])))", + "histogram_fraction(0, 1, sum(some_metric))", ] { let table_provider = build_test_native_histogram_table_provider_with_stable_keys("some_metric").await; @@ -12949,8 +12935,8 @@ async fn histogram_statements_run_natively_until_an_aggregate_folds_them() { } // An aggregate over a histogram now folds it natively - `sum(some_metric)` and // `sum(rate(some_metric[5m]))` - which is what `a_histogram_sum_or_avg_folds_natively` - // covers; the histogram shapes the split still declines are pinned by - // `a_histogram_aggregate_the_split_declines_keeps_the_existing_plan`. + // covers; the histogram shapes the split declines are pinned by + // `a_histogram_fold_the_split_declines_is_segmented`. } /// An instant selection over a native histogram keeps the histogram, so its output column stays the @@ -18264,32 +18250,39 @@ async fn native_composed_binary_restores_the_context_after_a_refused_operand() { ); } -/// A histogram aggregate the split cannot carry keeps the existing plan instead of being segmented. +/// A histogram fold the split cannot carry is segmented. /// -/// Segmentation answers a group by folding each segment's samples and appending the pieces, so a -/// histogram point whose contributions are spread over partitions would be folded once per segment: -/// a sum would merge histograms that never met, and an average would average averages. An aggregate -/// above another aggregate is such a shape and falls back rather than being cut; a ranking above the -/// fold is not, because it reads the cut's answer as a whole. +/// Neither an aggregate above another aggregate nor a whole-vector consumer is a shape the split can +/// move across the boundary, so the per-series prefix is cut into its own segment and everything +/// above it, the histogram fold included, runs once over every segment's frames. #[tokio::test] -async fn a_histogram_aggregate_the_split_declines_keeps_the_existing_plan() { +async fn a_histogram_fold_the_split_declines_is_segmented() { for query in [ "sum(sum(some_metric))", "count(sum(some_metric))", "min(sum(some_metric))", "avg(sum(some_metric))", + "sort(sum(some_metric))", + "scalar(sum(some_metric))", + "absent(sum(some_metric))", + "sum(sort(some_metric))", ] { let table_provider = build_test_native_histogram_table_provider("some_metric").await; let plan = build_native_fused_plan_with_provider(query, true, table_provider).await; let display = plan.display_indent_schema().to_string(); + assert_eq!(None, take_reported_decline(), "{query}: {display}"); + let fused = + find_fused_series(&plan).unwrap_or_else(|| panic!("{query} left the route: {display}")); assert!( - find_fused_series(&plan).is_none(), - "{query} ran a histogram fold per segment: {display}" + fused + .tree() + .root() + .any(&|node| matches!(node.expr, NativeExpr::Aggregate { .. })), + "{query} does not fold above its segment: {display}" ); - // The fallback is the legacy plan, not a native segment above a missing partial. assert!( - !display.contains("FusedSeriesExec"), - "{query} was segmented instead of kept: {display}" + find_final_split(&plan).is_none(), + "{query} was split instead of segmented: {display}" ); } } @@ -18358,41 +18351,32 @@ async fn a_ranking_above_a_histogram_fold_splits_without_ranking_a_histogram() { ); } -/// The gates that admit a histogram fold do not admit the shapes whose histogram state has no -/// execution: a canonical merge carrying histograms. +/// A histogram fold above a canonical merge runs natively. +/// +/// The split refuses a merge on the fold's input side, because the merge has to collect each label +/// set from every partition. The merge is therefore a segment boundary of its own, and the fold +/// runs once above what it collected, so two colliding series are reported rather than folded apart. #[tokio::test] -async fn histogram_state_stays_out_of_the_shapes_it_cannot_cross() { - // A `Merge` on the aggregate's own input side is such a shape. The merge answers one series per - // label set from pieces that are spread over the scan's partitions, and a split keeps it in the - // per-partition prefix, where two colliding pieces from different partitions are folded apart - // instead of reported. A histogram fold has no execution above a boundary either - the chain - // this route builds there folds floats - so the statement keeps the existing plan. - let table_provider = build_test_native_histogram_table_provider("some_metric").await; - let plan = build_native_fused_plan_with_provider( +async fn histogram_state_crosses_a_canonical_merge() { + for query in [ "sum(label_replace(some_metric, \"tag_0\", \"x\", \"tag_0\", \".*\"))", - true, - table_provider, - ) - .await; - let display = plan.display_indent_schema().to_string(); - assert!( - find_fused_series(&plan).is_none(), - "the collected histogram fold ran a native fold: {display}" - ); - // Two aggregates are two cuts, which this split still cannot carry: the inner one would have to - // be replanned as its own pair above the outer one's answer. - let table_provider = build_test_native_histogram_table_provider("some_metric").await; - let plan = build_native_fused_plan_with_provider( "sum(sum(label_replace(some_metric, \"tag_0\", \"x\", \"tag_0\", \".*\")))", - true, - table_provider, - ) - .await; - assert!( - find_fused_series(&plan).is_none(), - "the two-aggregate shape ran a native fold: {}", - plan.display_indent_schema() - ); + ] { + let table_provider = build_test_native_histogram_table_provider("some_metric").await; + let plan = build_native_fused_plan_with_provider(query, true, table_provider).await; + let display = plan.display_indent_schema().to_string(); + assert_eq!(None, take_reported_decline(), "{query}: {display}"); + let fused = + find_fused_series(&plan).unwrap_or_else(|| panic!("{query} left the route: {display}")); + assert!( + matches!(fused.tree().root().expr, NativeExpr::Aggregate { .. }), + "{query} does not fold natively: {display}" + ); + assert!( + find_final_split(&plan).is_none(), + "{query} split across the merge: {display}" + ); + } // Two histogram tables are a multi-input tree, but each fold is its own subtree: the binary // above them combines two already-folded histograms, so no aggregate state crosses the pairing // and the statement runs. diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index b003001083a..b48e245093a 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -205,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_fold_above_split_native_route, test_remote_write_v2_histogram_delta_temporality_native_route, test_remote_write_v2_histogram_native_annotations, test_remote_write_v2_histogram_native_arithmetic, @@ -7780,6 +7781,287 @@ pub async fn test_remote_write_v2_histogram_avg_native_partitions(store_type: St ); } +/// A native-histogram fold whose answer is finished above the fold runs natively. +/// +/// Every statement here folds histograms and then does something else with the result: a second +/// aggregate, a histogram function, a ranking, `sort`, `scalar` or `absent`. The four series are +/// flushed one by one and read over four partitions, so the fold below has contributions from +/// several partitions. The expectations are Prometheus's: `sort`, `topk`, `min` and +/// `max_over_time` ignore histogram samples, and `scalar` of a vector without a float is `NaN`. +pub async fn test_remote_write_v2_histogram_fold_above_split_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_fold_above_split", + ) + .with_default_store_type(store_type) + .with_query_options(QueryOptions { + experimental_native_promql: true, + parallelism: 4, + ..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; + + // The series scan deals out batches round robin, and a batch read from one file can carry + // several series. The default compaction merges the flushed files once the fourth lands, which + // left every series in partition 0, so the physical table keeps one file per flush. + tests_integration::test_util::execute_sql( + instance.fe_instance(), + "CREATE TABLE greptime_physical_table (greptime_timestamp TIMESTAMP(3) NOT NULL, \ + greptime_value DOUBLE NULL, TIME INDEX (greptime_timestamp)) ENGINE = metric \ + WITH ('physical_metric_table' = 'true', 'compaction.twcs.trigger_file_num' = '100')", + ) + .await; + let metric = "nh_seg"; + for (job, host, count, sum) in [ + ("a", "x", 2, 1.0), + ("a", "y", 4, 2.0), + ("b", "x", 6, 3.0), + ("b", "y", 8, 4.0), + ] { + write_native_histogram_sample( + &client, + &[ + (prom_store::METRIC_NAME_LABEL, metric), + ("job", job), + ("instance", host), + ], + 1, + vec![], + 2_000, + count, + sum, + ) + .await; + tests_integration::test_util::execute_sql( + instance.fe_instance(), + &format!("ADMIN FLUSH_TABLE('{metric}')"), + ) + .await; + } + + let histograms = |fields: &[(f64, f64)]| Some(fields.to_vec()); + for (query, expected_histograms, expected_floats) in [ + ( + "sum(sum by (job) (nh_seg))", + histograms(&[(20.0, 10.0)]), + None, + ), + ( + "avg(sum by (job) (nh_seg))", + histograms(&[(10.0, 5.0)]), + None, + ), + ("count(sum by (job) (nh_seg))", None, Some(vec![2.0])), + ( + r#"sum by (team) (label_replace(nh_seg, "team", "t-$1", "job", "(.*)"))"#, + histograms(&[(6.0, 3.0), (14.0, 7.0)]), + None, + ), + ("histogram_count(sum(nh_seg))", None, Some(vec![20.0])), + ("histogram_sum(sum(nh_seg))", None, Some(vec![10.0])), + ("histogram_quantile(0.5, sum(nh_seg))", None, None), + ("histogram_fraction(0, 2, sum(nh_seg))", None, None), + ( + "max_over_time(sum(nh_seg)[1s:1s])", + None, + Some(Vec::::new()), + ), + ("sort(sum by (job) (nh_seg))", None, Some(Vec::::new())), + ( + "topk(1, sum by (job) (nh_seg))", + None, + Some(Vec::::new()), + ), + ("min(sum by (job) (nh_seg))", None, Some(Vec::::new())), + ("absent(sum(nh_seg))", None, Some(Vec::::new())), + ("scalar(sum(nh_seg))", None, None), + ] { + observer.clear(); + let native = sorted_prom_query( + &client, + "query", + query, + "time=2", + "query.experimental_native_promql=true,query_parallelism=4", + ) + .await; + let described = describe_nodes(&observer.take_all(query)); + assert!( + described.iter().any(|node| node + .lines() + .any(|line| line.trim_start().starts_with("Aggregate:"))), + "`{query}` did not fold natively: {described:?}" + ); + let legacy = sorted_prom_query( + &client, + "query", + query, + "time=2", + "query.experimental_native_promql=false", + ) + .await; + assert_eq!( + native, legacy, + "`{query}`: native and existing answers differ" + ); + if let Some(expected) = expected_histograms { + assert_eq!( + expected, + vector_histogram_fields(&native), + "`{query}`: {native}" + ); + } + if let Some(expected) = expected_floats { + let values = native["result"] + .as_array() + .unwrap_or_else(|| panic!("`{query}`: no vector in {native}")) + .iter() + .map(|result| { + result["value"][1] + .as_str() + .and_then(|value| value.parse::().ok()) + .unwrap_or_else(|| panic!("`{query}`: no float in {result}")) + }) + .collect::>(); + assert_eq!(expected, values, "`{query}`: {native}"); + } + } + // The frames the fold reads come from the segment below it, one producer per scan partition. + // Counting the samples each partition emitted is what shows the fold merged frames from more + // than one of them rather than a single partition's. + let query = "sum(sum by (job) (nh_seg))"; + observer.clear(); + sorted_prom_query( + &client, + "query", + query, + "time=2", + "query.experimental_native_promql=true,query_parallelism=4", + ) + .await; + let fused = observer.take_all(query); + let producer = fused + .iter() + .find(|node| describe_node(node).contains("(output: series_frame)")) + .unwrap_or_else(|| { + panic!( + "`{query}` ran no frame producer: {:?}", + describe_nodes(&fused) + ) + }); + let mut partitions: BTreeMap = BTreeMap::new(); + for metric in node_metric_set(producer).iter() { + let (Some(partition), MetricValue::Count { count, .. }) = + (metric.partition(), metric.value()) + else { + continue; + }; + if metric.value().name() == "native.root.output_values" { + *partitions.entry(partition).or_insert(0) += count.value(); + } + } + let non_empty = partitions.values().filter(|count| **count > 0).count(); + assert!( + non_empty >= 2, + "`{query}`: frames came from fewer than two partitions: {partitions:?}" + ); + let scalar = sorted_prom_query( + &client, + "query", + "scalar(sum(nh_seg))", + "time=2", + "query.experimental_native_promql=true", + ) + .await; + assert_eq!( + "NaN", scalar["result"][1], + "a histogram is not a float: {scalar}" + ); + // Rewriting `instance` away gives two series of each job one label set. Prometheus refuses + // that before anything folds them, and both routes report the collision. + let collapsed = r#"sum(label_replace(nh_seg, "instance", "z", "instance", ".*"))"#; + for (hints, native) in [ + ( + "query.experimental_native_promql=true,query_parallelism=4", + true, + ), + ("query.experimental_native_promql=false", false), + ] { + observer.clear(); + let response = client + .get(&format!( + "/v1/prometheus/api/v1/query?query={}&time=2", + encode(collapsed) + )) + .header("x-greptime-hints", hints) + .send() + .await; + let status = response.status(); + let body = response.text().await; + assert!( + status != StatusCode::OK + && body.contains("vector cannot contain metrics with the same labelset"), + "`{collapsed}` with {hints}: {status} {body}" + ); + if native { + assert_outer_sum_folded_natively(&observer.take_all(collapsed), collapsed); + } + } + // The same folds over a range: every step folds all four series once. + for query in ["sum(sum by (job) (nh_seg))", "histogram_count(sum(nh_seg))"] { + observer.clear(); + let native = sorted_prom_query( + &client, + "query_range", + query, + "start=0&end=4&step=1", + "query.experimental_native_promql=true,query_parallelism=4", + ) + .await; + assert_outer_sum_folded_natively(&observer.take_all(query), query); + let legacy = sorted_prom_query( + &client, + "query_range", + query, + "start=0&end=4&step=1", + "query.experimental_native_promql=false", + ) + .await; + assert_eq!( + native, legacy, + "`{query}` over a range: native and existing answers differ" + ); + assert_eq!( + Some(3), + native["result"][0]["histograms"] + .as_array() + .or(native["result"][0]["values"].as_array()) + .map(Vec::len), + "`{query}` answers steps 2, 3 and 4: {native}" + ); + } +} + +/// Asserts that the statement's outermost `sum` ran in a fused node, not only a fold below it. +fn assert_outer_sum_folded_natively(fused: &[Arc], query: &str) { + let described = describe_nodes(fused); + assert!( + described.iter().any(|node| node + .lines() + .any(|line| line.trim_start().starts_with("Aggregate: sum by [] "))), + "`{query}` did not run its outer fold natively: {described:?}" + ); +} + /// A point whose samples disagree on their bucket layout is removed, and the response says why. /// /// One series carries exponential buckets and the other custom ones, which no addition can merge.