diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index f54d9b55ef4..9a9141edc99 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -42,7 +42,7 @@ use promql_parser::parser::{ }; use super::{ - CompiledInput, SelectorRequirement, SelectorTiming, compile, compile_selectors, + CompiledInput, CompiledTree, SelectorRequirement, SelectorTiming, compile, compile_selectors, compile_statement, validate_inputs, }; @@ -91,6 +91,16 @@ fn raw_schema_with_fields(count: usize) -> Arc { }) } +/// Compiles `query` with every selector bound to [`raw_schema`] and read as floats. +fn compile_float_selectors(query: &str) -> datafusion::error::Result { + compile_selectors( + &eval_stmt(query), + &|_| Ok(raw_schema()), + SeriesOrdering::KeyThenTime, + Some(FieldKind::Float), + ) +} + /// A statement over 100 seconds in 5-second steps, which is 21 grid points. fn eval_stmt(query: &str) -> EvalStmt { eval_stmt_over(query, Duration::from_secs(100)) @@ -422,43 +432,6 @@ fn a_quantile_outside_the_unit_interval_is_bound_as_given() { } } -#[test] -fn a_parenthesised_quantile_binds_as_written() { - let tree = compile( - &eval_stmt("quantile_over_time((0.9), x[5m])"), - raw_schema(), - SeriesOrdering::KeyThenTime, - ) - .expect("a parenthesised literal is the same quantile"); - - let (_, op) = root_window(&tree); - assert_eq!(op.function, RangeFunction::QuantileOverTime(0.9)); -} - -#[test] -fn a_parenthesised_selector_binds_as_written() { - let bare = compile( - &eval_stmt("quantile_over_time(0.9, x[5m])"), - raw_schema(), - SeriesOrdering::KeyThenTime, - ) - .expect("the bare selector binds"); - - for query in [ - "quantile_over_time(0.9, (x[5m]))", - "quantile_over_time((0.9), (x[5m]))", - "(quantile_over_time(0.9, (x[5m])))", - ] { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); - assert_eq!( - tree.to_string(), - bare.to_string(), - "`{query}` did not compile to the tree `quantile_over_time(0.9, x[5m])` does" - ); - } -} - #[test] fn a_parameter_folded_from_an_expression_binds_its_value() { // `1 - 0.1` is `0.9` bit for bit in IEEE754, and `-(0.9)` is the negative of the same number: @@ -621,19 +594,6 @@ fn an_offset_on_a_bare_selector_keeps_its_sign() { } } -#[test] -fn an_anchored_instant_selector_binds_its_anchor() { - let tree = compile( - &eval_stmt("x @ 100"), - raw_schema(), - SeriesOrdering::KeyThenTime, - ) - .unwrap(); - let (_, op) = root_instant(&tree); - assert_eq!(op.at_ms, Some(100_000)); - assert_eq!(op.offset_ms, 0); -} - #[test] fn anchored_instant_selector_binds_scan_bounds() { for (query, at_ms, offset_ms, bounds) in [ @@ -643,16 +603,11 @@ fn anchored_instant_selector_binds_scan_bounds() { 60_000, (1_169_000, 1_174_000, false), ), + ("x @ 100", Some(100_000), 0, (95_000, 100_000, false)), ("x @ start()", Some(0), 0, (-5_000, 0, false)), ("x @ end()", Some(100_000), 0, (95_000, 100_000, false)), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap(); + let compiled = compile_float_selectors(query).unwrap(); let (_, op) = root_instant(&compiled.tree); assert_eq!(op.at_ms, at_ms, "{query}"); assert_eq!(op.offset_ms, offset_ms, "{query}"); @@ -667,15 +622,18 @@ fn anchored_instant_selector_binds_scan_bounds() { #[test] fn an_anchor_on_a_window_resolves_to_absolute_milliseconds() { let cases = [ - ("rate(x[5m] @ 1234)", 1_234_000), - ("rate(x[5m] @ 1.234)", 1_234), + ("rate(x[5m] @ 1234)", 1_234_000, 0), + ("rate(x[5m] @ 1.234)", 1_234, 0), // Prometheus allows a pre-epoch anchor. - ("rate(x[5m] @ -1.5)", -1_500), - ("rate(x[5m] @ start())", 0), - ("rate(x[5m] @ end())", 100_000), + ("rate(x[5m] @ -1.5)", -1_500, 0), + ("rate(x[5m] @ start())", 0, 0), + ("rate(x[5m] @ end())", 100_000, 0), + ("rate(x[5m] @ 1.234 offset 1m)", 1_234, 60_000), + ("rate(x[5m] @ 1234 offset 1m)", 1_234_000, 60_000), + ("rate(x[5m] @ 1.234 offset -1m)", 1_234, -60_000), ]; - for (query, anchor_ms) in cases { + for (query, anchor_ms, offset_ms) in cases { let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); let (_, op) = root_window(&tree); assert_eq!( @@ -683,7 +641,10 @@ fn an_anchor_on_a_window_resolves_to_absolute_milliseconds() { Some(anchor_ms), "`{query}` bound the wrong anchor" ); - assert_eq!(op.window.offset_ms, 0, "`{query}` invented an offset"); + assert_eq!( + op.window.offset_ms, offset_ms, + "`{query}` bound the wrong offset" + ); } } @@ -707,26 +668,6 @@ fn end_resolves_to_the_statement_end_not_the_last_grid_point() { ); } -#[test] -fn an_anchor_and_an_offset_are_bound_apart() { - let cases = [ - ("rate(x[5m] @ 1.234 offset 1m)", 1_234, 60_000), - ("rate(x[5m] @ 1234 offset 1m)", 1_234_000, 60_000), - ("rate(x[5m] @ 1.234 offset -1m)", 1_234, -60_000), - ]; - - for (query, anchor_ms, offset_ms) in cases { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); - let (_, op) = root_window(&tree); - assert_eq!( - op.window.anchor_ms, - Some(anchor_ms), - "`{query}` lost the anchor" - ); - assert_eq!(op.window.offset_ms, offset_ms, "`{query}` lost the offset"); - } -} - #[test] fn the_numeric_edges_of_a_statement_are_bound_as_given() { enum Expected { @@ -990,25 +931,39 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() { #[test] fn parentheses_around_the_accepted_shape_are_transparent() { - let bare = compile( - &eval_stmt("rate(x[5m])"), - raw_schema(), - SeriesOrdering::KeyThenTime, - ) - .unwrap(); - for query in [ - "(rate(x[5m]))", - "rate((x[5m]))", - "rate(((x[5m])))", - "((rate((x[5m]))))", - ] { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); - assert_eq!( - tree.to_string(), - bare.to_string(), - "`{query}` did not compile to the tree `rate(x[5m])` does" - ); + let cases: [(&str, &[&str]); 2] = [ + ( + "rate(x[5m])", + &[ + "(rate(x[5m]))", + "rate((x[5m]))", + "rate(((x[5m])))", + "((rate((x[5m]))))", + ], + ), + ( + "quantile_over_time(0.9, x[5m])", + &[ + "quantile_over_time((0.9), x[5m])", + "quantile_over_time(0.9, (x[5m]))", + "quantile_over_time((0.9), (x[5m]))", + "(quantile_over_time(0.9, (x[5m])))", + ], + ), + ]; + for (bare, queries) in cases { + let bare_tree = compile(&eval_stmt(bare), raw_schema(), SeriesOrdering::KeyThenTime) + .unwrap() + .to_string(); + for query in queries { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + assert_eq!( + tree.to_string(), + bare_tree, + "`{query}` did not compile to the tree `{bare}` does" + ); + } } } #[test] @@ -1380,6 +1335,14 @@ fn a_constant_operand_binds_the_value_it_folds_to() { ("x * 2 ^ 3", 8.0), ("x * -0.5", -0.5), ("x * (1 - 0.1)", 0.9), + // Unfolded, a `Binary` of two constants passes tree validation and fails only at execution. + ("x * (1 < bool 2)", 1.0), + ("x * (1 > bool 2)", 0.0), + ("x * (1 == bool 1)", 1.0), + ("x * (1 != bool 1)", 0.0), + // NaN satisfies only `!=`. + ("x * (0 / 0 == bool 0)", 0.0), + ("x * (0 / 0 != bool 0)", 1.0), ]; for (query, value) in cases { @@ -1402,13 +1365,8 @@ fn a_constant_operand_binds_the_value_it_folds_to() { /// Two vectors bind independently, while the compatibility entry refuses to hide the two inputs. #[test] fn a_two_vector_operation_binds_one_input_per_selector() { - let compiled = compile_selectors( - &eval_stmt("a + b"), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`a + b` was refused: {error}")); + let compiled = compile_float_selectors("a + b") + .unwrap_or_else(|error| panic!("`a + b` was refused: {error}")); assert_eq!(compiled.inputs.len(), 2); assert_eq!(compiled.inputs[0].requirement.metric.as_deref(), Some("a")); assert_eq!(compiled.inputs[1].requirement.metric.as_deref(), Some("b")); @@ -1503,6 +1461,16 @@ fn vector_binary_matching_binds_labels_cardinality_fills_and_bool() { Some(2.0), false, ), + ( + "a / ignoring(instance) group_left(host) b", + false, + vec!["instance"], + "many-to-one", + vec!["host"], + None, + None, + false, + ), ( "a > bool ignoring(zone) b", false, @@ -1514,13 +1482,8 @@ fn vector_binary_matching_binds_labels_cardinality_fills_and_bool() { true, ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + let compiled = compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); let (_, _, matching) = binary_parts(compiled.tree.root()); assert_eq!(matching_labels(&matching.labels), (on, labels), "{query}"); assert_eq!( @@ -1537,23 +1500,6 @@ fn vector_binary_matching_binds_labels_cardinality_fills_and_bool() { } } -#[test] -fn vector_binary_matching_keeps_ignoring_and_group_left_separate() { - let compiled = compile_selectors( - &eval_stmt("a / ignoring(instance) group_left(host) b"), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap(); - let (_, _, matching) = binary_parts(compiled.tree.root()); - assert_eq!(matching_labels(&matching.labels), (false, vec!["instance"])); - assert_eq!( - matching_cardinality(&matching.cardinality), - ("many-to-one", vec!["host"]) - ); -} - #[test] fn set_operators_bind_their_operator_and_labels() { for (query, op, on, labels) in [ @@ -1566,13 +1512,8 @@ fn set_operators_bind_their_operator_and_labels() { vec!["pod"], ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + let compiled = compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); assert_eq!(compiled.inputs.len(), 2, "{query}"); let (left, right, bound) = set_parts(compiled.tree.root()); assert_eq!(bound.op, op, "{query}"); @@ -1658,13 +1599,8 @@ fn info_binds_its_info_metric_after_the_base() { false, ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + let compiled = compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); let [base_input, info_input] = &compiled.inputs[..] else { panic!("{query}: {} inputs", compiled.inputs.len()); }; @@ -1760,13 +1696,8 @@ fn info_selects_its_info_series_at_the_shared_reference_time() { Some(30_000), ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + let compiled = compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); let info = &compiled.inputs.last().unwrap().requirement; assert_eq!(info.metric.as_deref(), Some("target_info"), "{query}"); assert_eq!((info.offset_ms, info.at_ms), (offset_ms, at_ms), "{query}"); @@ -1883,14 +1814,9 @@ fn a_statement_that_reads_no_data_compiles_without_input() { #[test] fn a_varying_scalar_is_broadcast_where_it_was_written() { let compile_tree = |query: &str| { - compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) - .tree + compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) + .tree }; let tree = compile_tree("x > bool time()"); let (left, right, matching) = binary_parts(tree.root()); @@ -1909,13 +1835,8 @@ fn a_varying_scalar_is_broadcast_where_it_was_written() { #[test] fn a_math_function_with_a_varying_parameter_binds_its_parameters_as_scalars() { let compiled = |query: &str| { - compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) + compile_float_selectors(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) }; let parts = |tree: &NativeTree| match &tree.root().expr { NativeExpr::ParameterizedMap { @@ -1964,14 +1885,7 @@ fn a_math_function_with_a_varying_parameter_binds_its_parameters_as_scalars() { /// Prometheus reads a `quantile` φ at every step. #[test] fn a_quantile_reads_its_argument_per_point() { - let compiled = |query: &str| { - compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - }; + let compiled = |query: &str| compile_float_selectors(query); let per_point = |query: &str| match &compiled(query) .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) .tree @@ -2075,41 +1989,31 @@ fn a_call_of_two_scalars_binds_them_as_a_scalar_map() { } #[test] -fn a_scalar_function_over_a_vector_is_refused() { - let stmt = with_call_arguments("max_of(1, 2)", |args| { - *args[0] = a_bare_selector(); - }); - let error = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime) - .expect_err("`max_of(x, 2)` compiled, and it should not have"); - assert!( - matches!(error, DataFusionError::NotImplemented(_)), - "the refusal did not report NotImplemented, so the statement would not fall back: {error}" - ); - let message = error.to_string(); - assert!(message.contains("a call to `max_of`"), "{message}"); - assert!( - message.contains("where the function takes scalars"), - "the refusal did not say what the function takes: {message}" - ); -} - -#[test] -fn a_scalar_function_with_one_argument_is_refused() { - let stmt = with_call_arguments("max_of(1, 2)", |args| { - args.pop(); - }); - let error = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime) - .expect_err("`max_of(1)` compiled, and it should not have"); - assert!( - matches!(error, DataFusionError::NotImplemented(_)), - "the refusal did not report NotImplemented: {error}" - ); - let message = error.to_string(); - assert!(message.contains("a call to `max_of`"), "{message}"); - assert!( - message.contains("where it takes two scalars"), - "the refusal did not name the arguments it takes: {message}" - ); +fn a_scalar_function_over_the_wrong_arguments_is_refused() { + type Edit = fn(&mut Vec>); + let cases: [(Edit, &str); 2] = [ + ( + |args| *args[0] = a_bare_selector(), + "where the function takes scalars", + ), + ( + |args| { + args.pop(); + }, + "where it takes two scalars", + ), + ]; + for (edit, expected) in cases { + let stmt = with_call_arguments("max_of(1, 2)", edit); + let error = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime).expect_err(expected); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "the refusal did not report NotImplemented, so the statement would not fall back: {error}" + ); + let message = error.to_string(); + assert!(message.contains("a call to `max_of`"), "{message}"); + assert!(message.contains(expected), "{message}"); + } } #[test] @@ -2181,34 +2085,6 @@ fn a_modifier_inside_a_folded_call_argument_is_refused() { } } -/// Unfolded, a `Binary` of two constants passes tree validation and fails only at execution. -#[test] -fn a_bool_comparison_of_two_constants_folds_to_its_number() { - for (query, folded) in [ - ("x * (1 < bool 2)", 1.0), - ("x * (1 > bool 2)", 0.0), - ("x * (1 == bool 1)", 1.0), - ("x * (1 != bool 1)", 0.0), - // NaN satisfies only `!=`. - ("x * (0 / 0 == bool 0)", 0.0), - ("x * (0 / 0 != bool 0)", 1.0), - ] { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) - .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); - let (left, right, _) = binary_parts(tree.root()); - let scalar_side = if constant(left).is_some() { - left - } else { - right - }; - assert_eq!( - constant(scalar_side), - Some(folded), - "`{query}` did not fold its comparison to {folded}" - ); - } -} - /// The parser refuses `1 > 2`, so the `bool` flag is cleared on a parsed tree. #[test] fn a_comparison_of_two_constants_without_bool_is_refused() { @@ -2693,29 +2569,6 @@ fn a_compiled_constant_on_the_left_keeps_the_operand_order() { assert_ne!(divided, other, "`100 / x` and `x / 100` agree"); } -#[test] -fn a_compiled_bool_comparison_reports_one_and_zero() { - let (timestamps, _) = samples_at_every_grid_point(); - // Half the values are negative, so the comparison decides both ways. - let values = (1..=21) - .map(|value| Some(f64::from(value) - 10.0)) - .collect(); - let out = execute_compiled("x > bool 0", vec![raw_x(×tamps, values, true)]); - - let expected: Vec<(usize, f64)> = (0..21) - .map(|index| { - let value = index as f64 + 1.0 - 10.0; - (index, f64::from(u8::from(value > 0.0))) - }) - .collect(); - assert_eq!(rows(&out), expected, "`x > bool 0` did not report 0/1"); - assert_eq!( - executed_name(&out), - None, - "`x > bool 0` kept the metric name" - ); -} - /// Constant comparisons fold before the executor runs the vector operation. #[test] fn a_compiled_bool_constant_comparison_runs_with_vector_arithmetic() { @@ -2748,38 +2601,6 @@ fn a_compiled_bool_constant_comparison_runs_with_vector_arithmetic() { } } -#[test] -fn a_compiled_filtering_comparison_keeps_the_values_that_passed() { - let (timestamps, _) = samples_at_every_grid_point(); - let values = (1..=21) - .map(|value| Some(f64::from(value) - 10.0)) - .collect(); - let out = execute_compiled("x > 0", vec![raw_x(×tamps, values, true)]); - - let expected: Vec<(usize, f64)> = (0..21) - .filter_map(|index| { - let value = index as f64 + 1.0 - 10.0; - (value > 0.0).then_some((index, value)) - }) - .collect(); - assert_eq!(rows(&out), expected, "`x > 0` did not filter the vector"); - assert_eq!( - executed_name(&out), - Some("x".to_string()), - "a filtering comparison keeps the labels it read" - ); -} - -#[test] -fn a_compiled_negation_negates_every_value() { - let (timestamps, values) = samples_at_every_grid_point(); - let out = execute_compiled("-x", vec![raw_x(×tamps, values, true)]); - let expected: Vec<(usize, f64)> = (0..21) - .map(|index| (index, -(index as f64 + 1.0))) - .collect(); - assert_eq!(rows(&out), expected, "`-x` did not negate every value"); -} - #[test] fn a_compiled_negation_of_a_window_negates_the_window_result() { let (timestamps, values) = samples_at_every_grid_point(); @@ -4045,7 +3866,8 @@ fn aggregate_results(output: &[EvaluatedChunk]) -> Vec { results } -/// Pushes `chunks` into the tree's only input, ends it, and collects what the root reports. +/// Pushes `chunks` into the tree's only input, ends it, and collects what the root reports. The +/// aggregate at the root must not answer before the input ends. fn run_aggregate_tree(tree: &NativeTree, chunks: Vec) -> Vec { let pool: Arc = Arc::new(GreedyMemoryPool::new(1 << 26)); let state = NativeExecutionState::try_new(tree, pool, None).unwrap(); @@ -4054,6 +3876,10 @@ fn run_aggregate_tree(tree: &NativeTree, chunks: Vec) -> Vec Vec { (0..21).map(|index| index * 5_000).collect() } -#[test] -fn a_compiled_sum_drops_every_label_and_adds_its_group() { - let tree = compile( - &eval_stmt("sum(x)"), - raw_schema(), - SeriesOrdering::KeyThenTime, - ) - .unwrap(); - let schema = raw_schema(); - let timestamps = agg_timestamps_0_to_100(); - let chunks = vec![ - agg_raw_chunk( - &schema, - b"a", - agg_metric("x", &[("job", "api"), ("instance", "a")]), - ×tamps, - &(1..=21).map(f64::from).collect::>(), - ), - agg_raw_chunk( - &schema, - b"b", - agg_metric("x", &[("job", "db"), ("instance", "b")]), - ×tamps, - &(1..=21).map(|value| (2 * value) as f64).collect::>(), - ), - ]; - - let output = run_aggregate_tree(&tree, chunks); - // `3` at the first point, three more at each of the twenty after it: the two members summed. - let values: Vec<(usize, Option)> = agg_points_0_to_100() - .into_iter() - .map(|position| (position, Some(3.0 * (position as f64 + 1.0)))) - .collect(); - assert_eq!(output, vec![(None, Vec::new(), values)]); -} - -#[test] -fn a_compiled_sum_aggregates_series_chunks_after_input_ends() { - let schema = raw_schema(); - let timestamps = agg_timestamps_0_to_100(); - let values: Vec = (1..=21).map(f64::from).collect(); - let cases = [ - ("sum(x)", None, Vec::new()), - ( - "sum by(job)(x)", - None, - vec![("job".to_string(), "api".to_string())], - ), - ( - "sum without(instance)(x)", - None, - vec![("job".to_string(), "api".to_string())], - ), - ]; - - for (query, name, tags) in cases { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); - let metric = agg_metric("x", &[("job", "api"), ("instance", "a")]); - let chunks = vec![ - agg_raw_chunk_with_last( - &schema, - b"a", - metric.clone(), - ×tamps[..10], - &values[..10], - false, - ), - agg_raw_chunk_with_last( - &schema, - b"a", - metric, - ×tamps[10..], - &values[10..], - true, - ), - ]; - let pool: Arc = Arc::new(GreedyMemoryPool::new(1 << 26)); - let state = NativeExecutionState::try_new(&tree, pool, None).unwrap(); - let mut execution = NativeExecutor::new(state); - for chunk in chunks { - execution.push_raw(InputId::new(0), chunk).unwrap(); - assert!( - execution.next_chunk().unwrap().is_none(), - "`{query}` produced output before the whole input ended" - ); - } - let output = execution.finish().unwrap(); - let results = aggregate_results(&output); - let expected_points = values - .iter() - .enumerate() - .map(|(position, value)| (position, Some(*value))) - .collect(); - assert_eq!( - results, - vec![(name.map(str::to_string), tags, expected_points)], - "`{query}`" - ); - } -} - -#[test] -fn a_compiled_aggregate_over_empty_input_produces_no_groups() { - for query in ["sum(x)", "sum by(job)(x)", "sum without(instance)(x)"] { - let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); - assert_eq!( - run_aggregate_tree(&tree, Vec::new()), - Vec::new(), - "`{query}` invented a group for empty input" - ); - } -} - /// Members cover different points, so each group sums a subset that changes per point. No sample /// sits exactly one lookback behind a grid point, so the boundary convention does not matter. #[test] @@ -4196,15 +3909,18 @@ fn a_compiled_sum_by_groups_its_members_and_sums_each_group() { .unwrap(); let schema = raw_schema(); let all = agg_timestamps_0_to_100(); + let metric_a = agg_metric("x", &[("job", "api"), ("instance", "a")]); let chunks = vec![ - // The whole grid, holding one. - agg_raw_chunk( + // The whole grid, holding one, in two chunks. + agg_raw_chunk_with_last( &schema, b"a", - agg_metric("x", &[("job", "api"), ("instance", "a")]), - &all, - &[1.0; 21], + metric_a.clone(), + &all[..10], + &[1.0; 10], + false, ), + agg_raw_chunk_with_last(&schema, b"a", metric_a, &all[10..], &[1.0; 11], true), // One sample halfway between grid points 0 and 1, so only grid point 1 selects it. agg_raw_chunk( &schema, @@ -4338,13 +4054,30 @@ fn a_compiled_sum_over_a_rate_groups_the_window_it_reads() { let schema = raw_schema(); let timestamps: Vec = (0..=80).map(|index| index * 5_000).collect(); let values: Vec = (0..=80).map(|index| f64::from(index) + 1.0).collect(); + assert_eq!( + run_aggregate_tree(&tree, Vec::new()), + Vec::new(), + "empty input invented a group" + ); + // Series `a` arrives in two chunks, so the window carries its state across the split before + // handing the series to the aggregate. + let metric_a = agg_metric("x", &[("job", "api"), ("instance", "a")]); let chunks = vec![ - agg_raw_chunk( + agg_raw_chunk_with_last( &schema, b"a", - agg_metric("x", &[("job", "api"), ("instance", "a")]), - ×tamps, - &values, + metric_a.clone(), + ×tamps[..41], + &values[..41], + false, + ), + agg_raw_chunk_with_last( + &schema, + b"a", + metric_a, + ×tamps[41..], + &values[41..], + true, ), agg_raw_chunk( &schema, @@ -4384,74 +4117,6 @@ fn a_compiled_sum_over_a_rate_groups_the_window_it_reads() { ); } -#[test] -fn a_compiled_sum_over_a_rate_aggregates_series_chunks_after_input_ends() { - let statement = EvalStmt { - expr: promql_parser::parser::parse("sum by(job)(rate(x[5m]))").unwrap(), - start: UNIX_EPOCH + Duration::from_secs(300), - end: UNIX_EPOCH + Duration::from_secs(400), - interval: Duration::from_secs(5), - lookback_delta: Duration::from_secs(5), - }; - let tree = compile(&statement, raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); - let schema = raw_schema(); - let timestamps: Vec = (0..=80).map(|index| index * 5_000).collect(); - let values: Vec = (0..=80).map(|index| f64::from(index) + 1.0).collect(); - let metric = agg_metric("x", &[("job", "api"), ("instance", "a")]); - let chunks = [ - agg_raw_chunk_with_last( - &schema, - b"a", - metric.clone(), - ×tamps[..41], - &values[..41], - false, - ), - agg_raw_chunk_with_last( - &schema, - b"a", - metric, - ×tamps[41..], - &values[41..], - true, - ), - ]; - let pool: Arc = Arc::new(GreedyMemoryPool::new(1 << 26)); - let state = NativeExecutionState::try_new(&tree, pool, None).unwrap(); - let mut execution = NativeExecutor::new(state); - for chunk in chunks { - execution.push_raw(InputId::new(0), chunk).unwrap(); - assert!( - execution.next_chunk().unwrap().is_none(), - "the rate aggregate produced output before the whole input ended" - ); - } - let output = execution.finish().unwrap(); - assert_eq!( - aggregate_results(&output), - vec![( - None, - vec![("job".to_string(), "api".to_string())], - (0..21) - .map(|position| (position, Some(0.19999999999999998))) - .collect(), - )] - ); -} - -#[test] -fn a_compiled_sum_over_a_rate_with_empty_input_produces_no_groups() { - let statement = EvalStmt { - expr: promql_parser::parser::parse("sum by(job)(rate(x[5m]))").unwrap(), - start: UNIX_EPOCH + Duration::from_secs(300), - end: UNIX_EPOCH + Duration::from_secs(400), - interval: Duration::from_secs(5), - lookback_delta: Duration::from_secs(5), - }; - let tree = compile(&statement, raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); - assert_eq!(run_aggregate_tree(&tree, Vec::new()), Vec::new()); -} - #[test] fn label_functions_bind_their_change_into_a_map() { let cases = [ @@ -4542,13 +4207,8 @@ fn timestamp_anchored_selector_retains_offset_and_ordinary_selection_keeps_it() (-15_000, -10_000), ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|error| panic!("{query}: {error}")); + let compiled = + compile_float_selectors(query).unwrap_or_else(|error| panic!("{query}: {error}")); let requirement = &compiled.inputs[0].requirement; assert_eq!(requirement.offset_ms, expected_offset, "{query}"); assert_eq!(requirement.at_ms, expected_anchor, "{query}"); @@ -4701,13 +4361,7 @@ fn subquery_selector_bounds_use_inner_grid_and_selector_offset() { (840_000, 1_170_000, false), ), ] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap_or_else(|e| panic!("{query}: {e}")); + let compiled = compile_float_selectors(query).unwrap_or_else(|e| panic!("{query}: {e}")); let req = &compiled.inputs[0].requirement; assert_eq!( (req.grid_start_ms, req.grid_end_ms), @@ -4739,22 +4393,10 @@ fn selector_binding_callback_error_is_returned_once() { #[test] fn validate_inputs_rejects_misbound_occurrences_and_accepts_scalar_wrappers() { for query in ["x * 2", "2 * x"] { - let compiled = compile_selectors( - &eval_stmt(query), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap(); + let compiled = compile_float_selectors(query).unwrap(); validate_inputs(compiled.tree.root(), &compiled.inputs).unwrap(); } - let compiled = compile_selectors( - &eval_stmt("x * 2"), - &|_| Ok(raw_schema()), - SeriesOrdering::KeyThenTime, - Some(FieldKind::Float), - ) - .unwrap(); + let compiled = compile_float_selectors("x * 2").unwrap(); let original = compiled.inputs[0].clone(); for records in [Vec::new(), vec![original.clone(), original.clone()]] { diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index f9c944a3f98..da68eb2445e 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -2761,6 +2761,11 @@ async fn native_empty_discovery_declares_the_field_its_matcher_names() { // The matcher decides the name: the input declares the field the statement asks for, not // the default one this route gives a selection that names no field. (r#"{__field__="measured", job="api"}"#, "measured"), + // The default field is kept or dropped by the rule. + (r#"{__field__!="field_0", job="api"}"#, "value"), + (r#"{__field__!~"field.*", job="api"}"#, "value"), + (r#"{__field__=~"value", job="api"}"#, "value"), + (r#"{__field__=~".*", job="api"}"#, "value"), ] { let (plan, batches) = execute_no_match_discovery(query).await; let fused = find_fused_series(&plan) @@ -2824,57 +2829,6 @@ async fn native_empty_discovery_declines_a_field_operator_it_cannot_apply() { } } -#[tokio::test] -async fn native_empty_discovery_applies_a_field_operator_to_the_default_field() { - // The value column is named after the expression, so the layouts are compared by type. - let (plain, _) = execute_no_match_discovery(r#"{job="api"}"#).await; - let layout = |plan: &LogicalPlan| { - plan.schema() - .fields() - .iter() - .map(|field| field.data_type().clone()) - .collect::>() - }; - for query in [ - r#"{__field__!="field_0", job="api"}"#, - r#"{__field__!~"field.*", job="api"}"#, - r#"{__field__=~"value", job="api"}"#, - r#"{__field__=~".*", job="api"}"#, - ] { - let (plan, batches) = execute_no_match_discovery(query).await; - assert!( - find_fused_series(&plan).is_some(), - "`{query}` left the native route: {plan:?}" - ); - assert_eq!( - 0, - batch_rows(&batches), - "`{query}` answered rows over a selection that matches no metric: {plan:?}" - ); - let fused = find_fused_series(&plan).expect("the plan is the native one"); - let [LogicalPlan::EmptyRelation(relation)] = fused.children() else { - panic!("`{query}`: the empty input is the node's only child: {plan:?}"); - }; - let declaration = SeriesFrameDeclaration::parse(relation.schema.as_arrow()) - .unwrap_or_else(|error| panic!("`{query}` declares no raw series frame: {error}")); - assert_eq!( - vec!["value".to_string()], - declaration - .series() - .fields - .iter() - .map(|field| field.name.to_string()) - .collect::>(), - "`{query}`: the empty frame declares the one field the rule kept" - ); - assert_eq!( - layout(&plain), - layout(&plan), - "`{query}` publishes the layout a selection of one field publishes: {plan:?}" - ); - } -} - /// A zero-match discovery selector is a real input even when another selector reads a metric. #[tokio::test] async fn native_zero_match_discovery_with_real_selector_binds_both_inputs() { @@ -3174,81 +3128,45 @@ async fn native_named_selector_over_a_missing_table_answers_what_prometheus_answ "{plan:?}" ); - // `absent` reports the absence of what it read as one series holding 1. The selector names no - // equality label, so the row names nothing - not even the metric the selector wrote. - let (plan, batches) = execute_missing("absent(nonexistent_metric)", 0).await; - assert_eq!(1, batch_rows(&batches), "{plan:?}"); - assert_eq!( - vec![1.0], - numeric_values(&batches, &value_column("absent(nonexistent_metric)")), - "{plan:?}" - ); - for batch in &batches { - let name = batch - .column_by_name(METRIC_NAME) - .expect("the rows root declares the name column") - .as_any() - .downcast_ref::() - .expect("the name column is Utf8"); - assert_eq!(1, name.len(), "{batch:?}"); - assert!(name.is_null(0), "`absent` names no series: {batch:?}"); - } - - // A matcher that must be set is a label of the answer, as in Prometheus. - let (plan, batches) = execute_missing(r#"absent(nonexistent_metric{job="x"})"#, 0).await; - assert_eq!(1, batch_rows(&batches), "{plan:?}"); - assert_eq!( - vec![1.0], - numeric_values( - &batches, - &value_column(r#"absent(nonexistent_metric{job="x"})"#) + // `absent` and `absent_over_time` report the absence of what they read as one series holding 1 + // per step, labelled by the selector's equality matchers. A selector without one names nothing, + // not even the metric it wrote. `(query, steps, job label)`. + for (query, steps, job) in [ + ("absent(nonexistent_metric)", 0, None), + (r#"absent(nonexistent_metric{job="x"})"#, 0, Some("x")), + ( + r#"absent_over_time(nonexistent{job="x"}[5m])"#, + 0, + Some("x"), ), - "{plan:?}" - ); - for batch in &batches { - let job = batch - .column_by_name("job") - .expect("absent reports the selector's equality labels") - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(Some("x"), job.iter().next().flatten(), "{batch:?}"); + (r#"absent(nonexistent_metric{job="x"})"#, 2, Some("x")), + ] { + let (plan, batches) = execute_missing(query, steps).await; + let points = steps as usize + 1; + assert_eq!(points, batch_rows(&batches), "`{query}`: {plan:?}"); + assert_eq!( + vec![1.0; points], + numeric_values(&batches, &value_column(query)), + "`{query}`: {plan:?}" + ); + for batch in &batches { + let column = match job { + Some(_) => "job", + None => METRIC_NAME, + }; + let labels = batch + .column_by_name(column) + .unwrap_or_else(|| panic!("`{query}` declares no `{column}` column")) + .as_any() + .downcast_ref::() + .unwrap(); + assert!( + labels.iter().all(|label| label == job), + "`{query}`: {batch:?}" + ); + } } - // `absent_over_time` answers the same way over a missing table. - let (plan, batches) = execute_missing(r#"absent_over_time(nonexistent{job="x"}[5m])"#, 0).await; - assert_eq!(1, batch_rows(&batches), "{plan:?}"); - assert_eq!( - vec![1.0], - numeric_values( - &batches, - &value_column(r#"absent_over_time(nonexistent{job="x"}[5m])"#) - ), - "{plan:?}" - ); - for batch in &batches { - let job = batch - .column_by_name("job") - .expect("absent_over_time reports the selector's equality labels") - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(Some("x"), job.iter().next().flatten(), "{batch:?}"); - } - - // A range statement evaluates the same empty input on a grid of its own: three points, each - // answering the absence of what the selector named. - let (plan, batches) = execute_missing(r#"absent(nonexistent_metric{job="x"})"#, 2).await; - assert_eq!(3, batch_rows(&batches), "{plan:?}"); - assert_eq!( - vec![1.0, 1.0, 1.0], - numeric_values( - &batches, - &value_column(r#"absent(nonexistent_metric{job="x"})"#) - ), - "{plan:?}" - ); - // An `or` keeps the side that holds a series, in either position. for query in ["nonexistent or vector(7)", "vector(7) or nonexistent"] { let (plan, batches) = execute_missing(query, 0).await; @@ -4245,37 +4163,14 @@ async fn native_fused_rate_plans_to_a_fused_series_node() { bound.ordering, "the tree claimed an ordering a raw-series scan need not guarantee" ); -} - -/// A single-metric `rate` streams: the window drops the metric name, but every series the scan -/// hands over is named the same one, so the drop tells none of them apart. Nothing has to collect -/// what the window hands out, and the plan keeps the one node over the scan. -#[tokio::test] -async fn native_fused_single_metric_rate_streams_without_a_canonical_merge() { - let query = "rate(some_metric[5m])"; - let plan = build_native_fused_plan(query, true).await; - let fused = find_fused_series(&plan).expect("the native route answers the query"); - assert_eq!( - Some("some_metric"), - fused.binding().metric_name.as_deref(), - "the binding names the one metric the scan reads" - ); - assert!( - !fused.is_canonical_producer(), - "`{query}` needs no canonical boundary: {plan}" - ); - assert!( - matches!(fused.tree().root().expr, NativeExpr::Window { .. }), - "`{query}`: the root stays the window: {:?}", - fused.tree().root().expr - ); - let [child] = fused.children() else { - panic!("`{query}` reads one input: {plan}"); + // A single-metric `rate` streams: the window drops the metric name, but every series the scan + // hands over is named the same one, so the drop tells none of them apart and nothing has to + // collect what the window hands out. + assert_eq!(Some("some_metric"), fused.binding().metric_name.as_deref()); + assert!(!fused.is_canonical_producer(), "{display}"); + let [LogicalPlan::TableScan(_)] = fused.children() else { + panic!("the window does not read the scan itself: {display}"); }; - assert!( - matches!(child, LogicalPlan::TableScan(_)), - "`{query}`: the window reads the scan itself: {plan}" - ); } /// A `rate` over a selector that discovered several metrics keeps its collection: two of those @@ -5786,41 +5681,71 @@ async fn native_disjoint_tag_provider() -> DfTableSourceProvider { ) } +/// A histogram and a float selector pair as two evaluated frames, and the declared value column +/// follows the output kind: `histogram * float` and `histogram / float` answer histograms, while +/// unsupported histogram arithmetic still runs the native matcher and declares an empty float. #[tokio::test] async fn native_fused_composes_independent_histogram_binary_frames() { - for query in [ - "hist * on(tag_0) floats", - "floats * on(tag_0) hist", - "hist / on(tag_0) floats", - "clamp(floats, 1, 2) * on(tag_0) hist", + // `(query, fills_left, fills_right, histogram)`. + for (query, fills_left, fills_right, histogram) in [ + ("hist * on(tag_0) floats", false, false, true), + ("floats * on(tag_0) hist", false, false, true), + ("hist / on(tag_0) floats", false, false, true), + ("clamp(floats, 1, 2) * on(tag_0) hist", false, false, true), + ("clamp(floats, 1, 2) + on(tag_0) hist", false, false, false), + ("hist + on(tag_0) clamp(floats, 1, 2)", false, false, false), + // A filled right side is a float meeting a histogram here, and `histogram * float` answers a + // histogram: the same column carries the matched rows and the filled ones. + ("hist * on(tag_0) fill_right(0) floats", false, true, true), ] { let plan = build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) .await; let display = plan.display_indent().to_string(); let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("{query}: {display}")); - let NativeExpr::Binary { left, right, .. } = &fused.tree().root().expr else { + let NativeExpr::Binary { + left, + right, + matching, + } = &fused.tree().root().expr + else { panic!("expected Binary for {query}: {display}"); }; assert!( matches!(left.expr, NativeExpr::Input(_)) && matches!(right.expr, NativeExpr::Input(_)), - "{display}" + "{query}: {display}" ); - assert_eq!(2, fused.children().len(), "{display}"); + assert_eq!( + (fills_left, fills_right), + (matching.fill.lhs.is_some(), matching.fill.rhs.is_some()), + "{query}: {display}" + ); + assert_eq!(2, fused.children().len(), "{query}: {display}"); for child in fused.children() { let frame = find_fused_series(child) .unwrap_or_else(|| panic!("missing operand frame: {display}")); assert_eq!( promql::extension_plan::FusedOutputFormat::SeriesFrame, frame.format(), - "{display}" + "{query}: {display}" ); } - assert!(!display.contains("Join:"), "{display}"); + assert!(!display.contains("Join:"), "{query}: {display}"); + let expected = if histogram { + native_histogram_value_type().as_arrow_type() + } else { + ArrowDataType::Float64 + }; + let expression = parser::parse(query).unwrap().to_string(); + let field = plan + .schema() + .field_with_unqualified_name(&expression) + .unwrap_or_else(|_| panic!("`{query}` names its value after the statement: {display}")); + assert_eq!(&expected, field.data_type(), "{query}: {display}"); assert_eq!( expected_native_column_names(query, &["tag_0", "__name__"]), sorted_column_names(&plan), - "{display}" + "{query}: {display}" ); } } @@ -5899,97 +5824,9 @@ async fn a_pair_of_histogram_metrics_runs_natively() { } } -/// Unsupported histogram arithmetic still runs the native matcher and declares an empty float. -#[tokio::test] -async fn native_composed_invalid_histogram_arithmetic_declares_float() { - for query in [ - "clamp(floats, 1, 2) + on(tag_0) hist", - "hist + on(tag_0) clamp(floats, 1, 2)", - ] { - let plan = - build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) - .await; - let display = plan.display_indent().to_string(); - let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("{query}: {display}")); - let NativeExpr::Binary { left, right, .. } = &fused.tree().root().expr else { - panic!("expected Binary for {query}: {display}"); - }; - assert!( - matches!(left.expr, NativeExpr::Input(_)) && matches!(right.expr, NativeExpr::Input(_)), - "{display}" - ); - assert_eq!(2, fused.children().len(), "{display}"); - assert!(!display.contains("Join:"), "{display}"); - let expression = parser::parse(query).unwrap().to_string(); - let fields = plan.schema().fields(); - let field = fields - .iter() - .find(|field| field.name() == &expression) - .unwrap_or_else(|| panic!("`{query}` names its value after the statement: {display}")); - assert_eq!(field.data_type(), &ArrowDataType::Float64, "{display}"); - assert_eq!( - expected_native_column_names(query, &["tag_0", "__name__"]), - sorted_column_names(&plan), - "{display}" - ); - } -} - /// Fill modifiers are part of the composed binary's matching, decided by the output kind they imply. #[tokio::test] async fn native_composed_binary_admits_fill() { - for (query, fills_left, fills_right) in [ - // A filled right side is a float meeting a histogram here, and `histogram * float` answers a - // histogram: the same column carries the matched rows and the filled ones. - ("hist * on(tag_0) fill_right(0) floats", false, true), - ] { - let plan = - build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) - .await; - let display = plan.display_indent().to_string(); - let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("{query}: {display}")); - let NativeExpr::Binary { - left, - right, - matching, - } = &fused.tree().root().expr - else { - panic!("expected composed Binary for {query}: {display}"); - }; - assert!( - matches!(left.expr, NativeExpr::Input(_)) && matches!(right.expr, NativeExpr::Input(_)), - "{display}" - ); - assert_eq!( - (fills_left, fills_right), - (matching.fill.lhs.is_some(), matching.fill.rhs.is_some()), - "{query}: {display}" - ); - assert_eq!(2, fused.children().len(), "{display}"); - for child in fused.children() { - let frame = find_fused_series(child) - .unwrap_or_else(|| panic!("missing operand frame: {display}")); - assert_eq!( - promql::extension_plan::FusedOutputFormat::SeriesFrame, - frame.format(), - "{query}: {display}" - ); - } - assert!(!display.contains("Join:"), "{display}"); - let expression = parser::parse(query).unwrap().to_string(); - let field = plan - .schema() - .fields() - .iter() - .find(|field| field.name() == &expression) - .unwrap_or_else(|| panic!("`{query}` names its value after the statement: {display}")); - assert_eq!( - field.data_type(), - &native_histogram_value_type().as_arrow_type(), - "{query}: {display}" - ); - } - // A filled left side meets the right side alone, and `float * float` is a float: with a // histogram on the right, one column would have to carry a histogram row and a float row. The // kind walk refuses that shape, so the route refuses the statement - the two refusals are the @@ -7943,50 +7780,60 @@ async fn native_fused_whole_vector_operators_over_an_aggregate_stay_native() { } } -/// A data-free vector stays in the gathered parent while the data-bearing prefix is cut. +/// A data-free vector or a scalar operand stays in the gathered parent while the data-bearing prefix +/// is cut into its own segment. #[tokio::test] -async fn native_fused_data_free_vector_does_not_block_segmentation() { - let query = "sum(topk(1, some_metric)) + vector(1)"; - let native = build_native_fused_plan(query, true).await; - let legacy = build_native_fused_plan(query, false).await; - - let LogicalPlan::Extension(Extension { node }) = &native else { - panic!("expected a native parent rather than a legacy root: {native}"); - }; - let parent = node - .as_any() - .downcast_ref::() - .unwrap_or_else(|| panic!("expected a fused root rather than a legacy root: {native}")); - let NativeExpr::Binary { left, right, .. } = &parent.tree().root().expr else { - panic!("expected the whole binary expression in the native parent: {native}"); - }; - assert!( - matches!(&right.expr, NativeExpr::VectorOf { .. }), - "the data-free vector must stay in the parent: {native}" - ); - let NativeExpr::Aggregate { input, .. } = &left.expr else { - panic!("expected sum in the parent: {native}"); - }; - let NativeExpr::Vector { input, .. } = &input.expr else { - panic!("expected topk in the parent: {native}"); - }; - assert!( - matches!(&input.expr, NativeExpr::Input(input) if input.source_index == 0), - "the data-bearing prefix must be replaced by a segment input: {native}" - ); - assert_eq!(parent.children().len(), 1, "{native}"); - let LogicalPlan::Extension(Extension { node }) = &parent.children()[0] else { - panic!("expected a fused prefix segment: {native}"); - }; - let prefix = node - .as_any() - .downcast_ref::() - .unwrap_or_else(|| panic!("expected a fused prefix segment: {native}")); - assert!( - matches!(&prefix.tree().root().expr, NativeExpr::Instant { .. }), - "the prefix must evaluate the selector in its own segment: {native}" - ); - assert!(find_fused_series(&legacy).is_none(), "{legacy}"); +async fn native_fused_data_free_operand_does_not_block_segmentation() { + // `(query, the data-free operand is a vector rather than a scalar)`. + let cases = [ + ("sum(topk(1, some_metric)) + vector(1)", true), + ("sum(topk(1, some_metric)) + 1", false), + ("avg(topk(1, some_metric)) * 2", false), + ]; + for (query, vector_of) in cases { + let native = build_native_fused_plan(query, true).await; + let LogicalPlan::Extension(Extension { node }) = &native else { + panic!("{query}: expected a native parent rather than a legacy root: {native}"); + }; + let parent = node + .as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("{query}: expected a fused root: {native}")); + let NativeExpr::Binary { left, right, .. } = &parent.tree().root().expr else { + panic!("{query}: expected the whole binary expression in the parent: {native}"); + }; + assert!( + if vector_of { + matches!(right.expr, NativeExpr::VectorOf { .. }) + } else { + matches!(right.expr, NativeExpr::Scalar(_)) + }, + "{query}: the data-free operand must stay in the parent: {native}" + ); + let NativeExpr::Aggregate { input, .. } = &left.expr else { + panic!("{query}: expected the aggregate in the parent: {native}"); + }; + let NativeExpr::Vector { input, .. } = &input.expr else { + panic!("{query}: expected topk in the parent: {native}"); + }; + assert!( + matches!(&input.expr, NativeExpr::Input(input) if input.source_index == 0), + "{query}: the data-bearing prefix must be replaced by a segment input: {native}" + ); + let [LogicalPlan::Extension(Extension { node })] = parent.children() else { + panic!("{query}: expected one prefix segment: {native}"); + }; + let prefix = node + .as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("{query}: expected a fused prefix segment: {native}")); + assert!( + matches!(&prefix.tree().root().expr, NativeExpr::Instant { .. }), + "{query}: the prefix must evaluate the selector in its own segment: {native}" + ); + let legacy = build_native_fused_plan(query, false).await; + assert!(find_fused_series(&legacy).is_none(), "{legacy}"); + } } /// Source-free statements still plan as one native node without needing a segment. @@ -8008,41 +7855,6 @@ async fn native_fused_data_free_aggregate_stays_single_node() { assert!(fused.children().is_empty(), "{plan}"); } -/// Scalar broadcasts still leave the data-bearing prefix in its own segment. -#[tokio::test] -async fn native_fused_scalar_broadcast_keeps_segmentation() { - let query = "sum(topk(1, some_metric)) + 1"; - let plan = build_native_fused_plan(query, true).await; - let LogicalPlan::Extension(Extension { node }) = &plan else { - panic!("expected a native parent: {plan}"); - }; - let parent = node - .as_any() - .downcast_ref::() - .unwrap_or_else(|| panic!("expected a fused parent: {plan}")); - let NativeExpr::Binary { left, right, .. } = &parent.tree().root().expr else { - panic!("expected the binary in the native parent: {plan}"); - }; - assert!(matches!(&right.expr, NativeExpr::Scalar(_)), "{plan}"); - let NativeExpr::Aggregate { input, .. } = &left.expr else { - panic!("expected sum in the parent: {plan}"); - }; - let NativeExpr::Vector { input, .. } = &input.expr else { - panic!("expected topk in the parent: {plan}"); - }; - assert!( - matches!(&input.expr, NativeExpr::Input(input) if input.source_index == 0), - "the data prefix must remain cut: {plan}" - ); - assert_eq!(parent.children().len(), 1, "{plan}"); - let prefix = find_fused_series(&parent.children()[0]) - .unwrap_or_else(|| panic!("expected a fused prefix segment: {plan}")); - assert!( - matches!(&prefix.tree().root().expr, NativeExpr::Instant { .. }), - "{plan}" - ); -} - /// The split boundary publishes expression names without an aliasing plan. #[tokio::test] async fn native_split_boundary_uses_native_tree_column_names() { @@ -13339,29 +13151,40 @@ async fn a_segmented_histogram_answer_crosses_its_collected_boundary() { ); } -/// A histogram fold is admitted below a pointwise operator. +/// `sum` and `avg` over native histograms fold and merge their own state, so the statement is +/// admitted and its answer column is the canonical histogram struct. /// -/// 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 the split declines are segmented -/// instead, which `a_histogram_fold_the_split_declines_is_segmented` pins. +/// The single-selector split answers them: the producer folds each partition's histograms into a +/// `Partial` state and the final node merges that state above the series router. 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. 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() { +async fn a_histogram_sum_or_avg_folds_natively() { for query in [ "sum(some_metric)", + "avg(some_metric)", + "sum(rate(some_metric[5m]))", + "avg by (tag_0) (some_metric)", "sum(some_metric) * 2", "sum(some_metric) / 2", "avg(some_metric) + 1", "-sum(some_metric)", ] { - // A metric-engine table, whose tag columns are all nullable: the fixture the statements - // below ran against before the drop's proof changed, and the one this test pins. + // The metric-engine table every drop over it collects for: its `le` tag is nullable, so + // the canonical pass inserts a `Merge` above the window and the split has to carry one. + // This is the fixture the regression this test guards appeared on: a split that declined + // across that merge sent `sum(rate(h[5m]))` back to the existing plan. 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(); 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}" + ); assert_eq!( &native_histogram_value_type().as_arrow_type(), native_value_field(final_node, query).data_type(), @@ -13606,7 +13429,7 @@ async fn timestamp_filters_native_histogram_stale_marker_before_projection() { assert!(plan_text.contains(TIMESTAMP_VALUE_PREFIX), "{plan_text}"); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); } #[tokio::test] @@ -13669,7 +13492,7 @@ async fn timestamp_filters_stale_marker_from_mixed_sample_companion() { .unwrap(); let (_, batches) = execute(plan, &build_query_engine_state()).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); } #[tokio::test] @@ -13802,10 +13625,7 @@ async fn mixed_histogram_helpers_report_annotations() { .unwrap(); let (_, batches) = execute(plan, &state).await; - assert_eq!( - batches.iter().map(RecordBatch::num_rows).sum::(), - expected_rows - ); + assert_eq!(batch_rows(&batches), expected_rows); let mut warnings = vec![]; let mut infos = vec![]; collector.append_to(&mut warnings, &mut infos); @@ -13910,7 +13730,7 @@ async fn nested_histogram_helpers_ignore_unparsable_bucket_labels() { let (_, batches) = execute(plan, &state).await; assert_eq!( - batches.iter().map(RecordBatch::num_rows).sum::(), + batch_rows(&batches), 0, "native_le={native_le:?}, query={query}" ); @@ -14023,35 +13843,6 @@ async fn native_histogram_value_sort_is_empty_but_label_sort_preserves_samples() } } -#[tokio::test] -async fn unsupported_native_histogram_functions_use_drop_udf() { - for query in [ - "deriv(some_metric[5m])", - "min_over_time(some_metric[5m])", - "quantile_over_time(0.9, some_metric[5m])", - "predict_linear(some_metric[5m], 60)", - "round(some_metric)", - "abs(some_metric)", - ] { - let plan = native_histogram_plan(query).await; - - assert!( - plan.contains("prom_native_histogram_drop_float"), - "{query}\n{plan}" - ); - } -} - -#[tokio::test] -async fn native_histogram_absent_over_time_uses_native_udf() { - let plan = native_histogram_plan("absent_over_time(some_metric[5m])").await; - - assert!( - plan.contains("prom_native_histogram_absent_over_time"), - "{plan}" - ); -} - #[tokio::test] async fn native_histogram_all_function_arms_route_correctly() { // Every native-histogram match arm in `create_function_expr` must route to the @@ -14090,6 +13881,10 @@ async fn native_histogram_all_function_arms_route_correctly() { "present_over_time(some_metric[5m])", "prom_native_histogram_present_over_time", ), + ( + "absent_over_time(some_metric[5m])", + "prom_native_histogram_absent_over_time", + ), // Unsupported functions dropped with the float-null UDF. ("deriv(some_metric[5m])", "prom_native_histogram_drop_float"), ( @@ -14121,6 +13916,7 @@ async fn native_histogram_all_function_arms_route_correctly() { "prom_native_histogram_drop_float", ), ("round(some_metric)", "prom_native_histogram_drop_float"), + ("abs(some_metric)", "prom_native_histogram_drop_float"), ("rad(some_metric)", "prom_native_histogram_drop_float"), ("deg(some_metric)", "prom_native_histogram_drop_float"), ("sgn(some_metric)", "prom_native_histogram_drop_float"), @@ -14337,7 +14133,7 @@ async fn mixed_native_histogram_rate_executes_real_ranges() { .build() .unwrap(); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); let mut warnings = Vec::new(); collector.append_to(&mut warnings, &mut Vec::new()); assert!( @@ -14511,8 +14307,8 @@ async fn build_subquery_offset_probe_provider() -> DfTableSourceProvider { .collect::>(); for (table_id, name, rows) in [ - (7_001_u32, "subquery_offset_probe", &probe_rows), - (7_002_u32, "subquery_offset_offgrid", &offgrid_rows), + (7_001_u32, "on_grid", &probe_rows), + (7_002_u32, "off_grid", &offgrid_rows), ] { let schema = Arc::new(Schema::new(vec![ ColumnSchema::new( @@ -14664,139 +14460,111 @@ async fn run_subquery_offset_probe( rows } -#[tokio::test] -async fn subquery_own_offset_shifts_the_inner_window_but_keeps_evaluation_timestamps() { - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] offset 30s)", - 45, - 45, - 1 - ) - .await, - vec![(45_000, 3.0)], - ); - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_probe[20s:10s])", 15, 15, 1).await, - vec![(15_000, 3.0)], - ); - - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] offset 30s)", - 30, - 60, - 30 - ) - .await, - vec![(30_000, 1.0), (60_000, 7.0)], - ); - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_probe[20s:10s])", 0, 30, 30).await, - vec![(0, 1.0), (30_000, 7.0)], - ); - - // Negative offsets look ahead while retaining outer timestamps. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] offset -30s)", - 0, - 30, - 30 - ) - .await, - vec![(0, 7.0), (30_000, 13.0)], - ); - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_probe[20s:10s])", 30, 60, 30) - .await, - vec![(30_000, 7.0), (60_000, 13.0)], - ); -} - -/// Expectations match Prometheus v3.14.0. +/// Subquery windows that `subquery.sql` and `subquery_at_modifier.sql` do not pin. #[tokio::test] async fn subquery_inner_points_are_anchored_on_absolute_step_multiples() { - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[20s:10s])", 45, 45, 1) - .await, - vec![(45_000, 7.0)], - ); - - // An off-grid offset distinguishes absolute anchoring from re-phasing. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset 5s)", - 30, - 30, - 1 - ) - .await, - vec![(30_000, 3.0)], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset 5s)", + let ramp = |values: [f64; 4]| -> Vec<(i64, f64)> { + (0..4) + .map(|step| (35_000 + step * 10_000, values[step as usize])) + .collect() + }; + // `(query, start, end, step, rows)`, bounds in seconds. + let cases = [ + // An off-grid evaluation instant over on-grid samples, with and without an offset. + ( + "sum_over_time(on_grid[20s:10s] offset 30s)", 45, 45, - 1 - ) - .await, - vec![(45_000, 7.0)], - ); - - // The window starts before the first sample. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset 15s)", - 30, - 30, - 1 - ) - .await, - vec![(30_000, 1.0)], - ); - - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset -5s)", + 1, + vec![(45_000, 3.0)], + ), + ( + "sum_over_time(on_grid[20s:10s])", 15, 15, - 1 - ) - .await, - vec![(15_000, 3.0)], - ); - - // The negative grid start exercises Euclidean alignment. - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[40s:10s])", 15, 15, 1) - .await, - vec![(15_000, 1.0)], - ); - - // Multi-step evaluation starts off the subquery grid. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s])", + 1, + vec![(15_000, 3.0)], + ), + // Negative offsets look ahead while retaining outer timestamps. + ( + "sum_over_time(on_grid[20s:10s] offset -30s)", + 0, + 30, + 30, + vec![(0, 7.0), (30_000, 13.0)], + ), + ( + "sum_over_time(off_grid[20s:10s])", + 45, + 45, + 1, + vec![(45_000, 7.0)], + ), + // An off-grid offset distinguishes absolute anchoring from re-phasing. + ( + "sum_over_time(off_grid[20s:10s] offset 5s)", + 45, + 45, + 1, + vec![(45_000, 7.0)], + ), + ( + "sum_over_time(off_grid[20s:10s] offset 5s)", 35, 65, - 30 - ) - .await, - vec![(35_000, 5.0), (65_000, 11.0)], - ); - - // Child points reach no sample at the first evaluation. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset 30s)", + 10, + ramp([5.0, 7.0, 9.0, 11.0]), + ), + // The negative grid start exercises Euclidean alignment. + ( + "sum_over_time(off_grid[40s:10s])", + 15, + 15, + 1, + vec![(15_000, 1.0)], + ), + // A nonempty child grid can yield no parent rows; every step then falls back. + ("sum_over_time(off_grid[5s:10s])", 35, 65, 10, vec![]), + ( + "sum_over_time(off_grid[5s:10s]) or vector(1)", + 35, + 65, + 10, + ramp([1.0; 4]), + ), + // An inner fallback does not fill an empty outer window. + ( + "sum_over_time((sum_over_time(off_grid[5s:10s]) or vector(1))[5s:10s])", + 35, + 44, + 10, + vec![], + ), + // `@ 0` folds `(-20s, 0s]`, where only the point 0s has a sample. + ( + "sum_over_time(on_grid[20s:10s] @ 0)", 30, 60, - 30 - ) - .await, - vec![(60_000, 5.0)], + 30, + vec![(30_000, 1.0), (60_000, 1.0)], + ), + ]; + for (query, start, end, step, expected) in cases { + assert_eq!( + run_subquery_offset_probe(query, start, end, step).await, + expected, + "{query}" + ); + } + + // `predict_linear` is not promoted as a whole, so it consumes the window replayed by the + // anchored subquery itself; that window holds the same points as the range selector form. + let anchored = + run_subquery_offset_probe("predict_linear(on_grid[20s:10s] @ 60, 0)", 30, 60, 30).await; + assert_eq!(anchored.len(), 2, "{anchored:?}"); + assert_eq!( + anchored, + run_subquery_offset_probe("predict_linear(on_grid[20s] @ 60, 0)", 30, 60, 30).await, ); } @@ -14914,124 +14682,9 @@ fn subquery_child_window_is_the_child_grid_window() { } #[tokio::test] -async fn subquery_child_window_without_a_step_reports_no_row() { - // The first child point is after the parent’s only evaluation. - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[5s:10s])", 35, 44, 10) - .await, - vec![], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[5s:10s]) or vector(1)", - 35, - 44, - 10 - ) - .await, - vec![(35_000, 1.0)], - ); - // Multi-step: every step of the grid reports no child point and falls back. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[5s:10s]) or vector(1)", - 35, - 65, - 10 - ) - .await, - vec![(35_000, 1.0), (45_000, 1.0), (55_000, 1.0), (65_000, 1.0)], - ); - // A nonempty child grid can yield no parent rows; a longer range does. - assert_eq!( - run_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[5s:10s])", 35, 65, 10) - .await, - vec![], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s])", - 35, - 65, - 10 - ) - .await, - vec![(35_000, 5.0), (45_000, 7.0), (55_000, 9.0), (65_000, 11.0)], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset 5s)", - 35, - 65, - 10 - ) - .await, - vec![(35_000, 5.0), (45_000, 7.0), (55_000, 9.0), (65_000, 11.0)], - ); - // A negative offset makes the short window reach a child point. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[5s:10s] offset -5s)", - 35, - 44, - 10 - ) - .await, - vec![(35_000, 4.0)], - ); - - // An empty outer window suppresses inner results, but not an outer fallback. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time((sum_over_time(subquery_offset_offgrid[5s:10s]))[5s:10s])", - 35, - 44, - 10 - ) - .await, - vec![], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time((sum_over_time(subquery_offset_offgrid[5s:10s]))[5s:10s]) or vector(1)", - 35, - 44, - 10 - ) - .await, - vec![(35_000, 1.0)], - ); - assert_eq!( - run_subquery_offset_probe( - "sum_over_time((sum_over_time(subquery_offset_offgrid[5s:10s]) or vector(1))[5s:10s])", - 35, - 44, - 10 - ) - .await, - vec![], - ); -} - -#[tokio::test] -async fn subquery_rejects_invalid_range_and_zero_step() { - let err = - plan_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[5s:10s])", 44, 35, 10) - .await - .unwrap_err(); - assert!( - matches!( - &err, - crate::promql::error::Error::InvalidTimeRange { - start: 44_000, - end: 35_000, - .. - } - ), - "{err}" - ); +async fn subquery_rejects_an_invalid_range_around_a_nested_subquery() { let err = plan_subquery_offset_probe( - "sum_over_time((sum_over_time(subquery_offset_offgrid[5s:10s]))[5s:10s])", + "sum_over_time((sum_over_time(off_grid[5s:10s]))[5s:10s])", 44, 35, 10, @@ -15039,15 +14692,6 @@ async fn subquery_rejects_invalid_range_and_zero_step() { .await .unwrap_err(); assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}"); - - // `[5s:0]` parses to zero; planning rejects it. - let err = plan_subquery_offset_probe("sum_over_time(subquery_offset_offgrid[5s:0])", 60, 60, 1) - .await - .unwrap_err(); - assert!( - matches!(&err, crate::promql::error::Error::ZeroSubqueryStep { .. }), - "{err}" - ); } /// Rejects nonempty child windows whose derived millisecond bounds are unrepresentable. @@ -15055,7 +14699,7 @@ async fn subquery_rejects_invalid_range_and_zero_step() { async fn subquery_rejects_a_child_window_out_of_the_representable_range() { // Offset is i64::MAX milliseconds; only the derived start overflows. let err = plan_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[21366776s:10s] offset 292471208y21366775s807ms)", + "sum_over_time(off_grid[21366776s:10s] offset 292471208y21366775s807ms)", 0, 60, 10, @@ -15073,7 +14717,7 @@ async fn subquery_rejects_a_child_window_out_of_the_representable_range() { assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}"); // Offset is -i64::MAX milliseconds; only the derived end overflows. let err = plan_subquery_offset_probe( - "sum_over_time(subquery_offset_offgrid[20s:10s] offset -292471208y21366775s807ms)", + "sum_over_time(off_grid[20s:10s] offset -292471208y21366775s807ms)", 0, 60, 10, @@ -15091,107 +14735,13 @@ async fn subquery_rejects_a_child_window_out_of_the_representable_range() { assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}"); } -/// `@` on a subquery pins its evaluation instant, like `@` on a range selector: Prometheus folds -/// the anchor into the subquery offset (`setOffsetForAtModifier`) and treats the subquery as -/// step-invariant, so every step reports the window `(anchor - offset - range, anchor - offset]`. -/// See . -/// -/// The probe samples are at 0s..60s every 10s with values 1..7, on the 10s subquery grid. -#[tokio::test] -async fn subquery_at_modifier_pins_the_evaluation_instant() { - // The issue reproducer: `@ 60` folds `(40s, 60s]` -- the points 50s and 60s, 6 + 7 -- at every - // step, the same as the range selector form `m[20s] @ 60`. - for query in [ - "sum_over_time(subquery_offset_probe[20s] @ 60)", - "sum_over_time(subquery_offset_probe[20s:10s] @ 60)", - "sum_over_time(subquery_offset_probe[20s:10s] @ end())", - ] { - assert_eq!( - run_subquery_offset_probe(query, 30, 60, 30).await, - vec![(30_000, 13.0), (60_000, 13.0)], - "{query}" - ); - } - // `@ start()` folds `(10s, 30s]` -- 3 + 4 -- at every step. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] @ start())", - 30, - 60, - 30 - ) - .await, - vec![(30_000, 7.0), (60_000, 7.0)], - ); - // `offset` is applied relative to the anchor: `@ 60 offset 30s` folds `(10s, 30s]`, in either - // order of the modifiers. - for query in [ - "sum_over_time(subquery_offset_probe[20s:10s] @ 60 offset 30s)", - "sum_over_time(subquery_offset_probe[20s:10s] offset 30s @ 60)", - ] { - assert_eq!( - run_subquery_offset_probe(query, 30, 60, 30).await, - vec![(30_000, 7.0), (60_000, 7.0)], - "{query}" - ); - } - // An instant query evaluated away from the anchor still folds the anchored window. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] @ 60)", - 0, - 0, - 1 - ) - .await, - vec![(0, 13.0)], - ); - // An anchor whose window starts before the first sample: `@ 0` folds `(-20s, 0s]`, where only - // the point 0s has a sample. - assert_eq!( - run_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] @ 0)", - 30, - 60, - 30 - ) - .await, - vec![(30_000, 1.0), (60_000, 1.0)], - ); - // `predict_linear` is not promoted as a whole, so it consumes the window replayed by the - // subquery itself; that window holds the same points as the range selector form. - let anchored = run_subquery_offset_probe( - "predict_linear(subquery_offset_probe[20s:10s] @ 60, 0)", - 30, - 60, - 30, - ) - .await; - assert_eq!(anchored.len(), 2, "{anchored:?}"); - assert_eq!( - anchored, - run_subquery_offset_probe( - "predict_linear(subquery_offset_probe[20s] @ 60, 0)", - 30, - 60, - 30 - ) - .await, - ); -} - /// An anchored subquery evaluates its child over the anchored window only, not over the whole /// outer evaluation range, and an anchor that cannot be represented in milliseconds is rejected. #[tokio::test] async fn subquery_at_modifier_scans_only_the_anchored_window() { - let plan = plan_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] @ 60)", - 0, - 100_000, - 30, - ) - .await - .unwrap(); + let plan = plan_subquery_offset_probe("sum_over_time(on_grid[20s:10s] @ 60)", 0, 100_000, 30) + .await + .unwrap(); let plan_str = plan.display_indent_schema().to_string(); // The child grid is the points 50s and 60s of `(40s, 60s]`. assert!( @@ -15205,20 +14755,15 @@ async fn subquery_at_modifier_scans_only_the_anchored_window() { "{plan_str}" ); assert!( - plan_str.contains("subquery_offset_probe.timestamp <= TimestampMillisecond(60000, None)"), + plan_str.contains("on_grid.timestamp <= TimestampMillisecond(60000, None)"), "the child must not be evaluated over the outer range:\n{plan_str}" ); #[cfg(not(windows))] { - let err = plan_subquery_offset_probe( - "sum_over_time(subquery_offset_probe[20s:10s] @ 1e16)", - 0, - 60, - 30, - ) - .await - .unwrap_err(); + let err = plan_subquery_offset_probe("sum_over_time(on_grid[20s:10s] @ 1e16)", 0, 60, 30) + .await + .unwrap_err(); assert!( err.to_string() .contains("Timestamp out of range for the `@` modifier"), @@ -15751,29 +15296,6 @@ async fn only_equals_is_supported_for_special_matcher() { } } -#[tokio::test] -async fn scatter_time_filter_many_evaluation_points() { - for function in ["increase", "sum_over_time"] { - for window in ["1h", "2h", "3h"] { - let query = format!("sum({function}(some_metric[{window}]))"); - let eval_stmt = EvalStmt { - expr: parser::parse(&query).unwrap(), - start: UNIX_EPOCH, - end: UNIX_EPOCH + Duration::from_secs(30 * 24 * 3600 + 1800), - interval: Duration::from_secs(2 * 3600), - lookback_delta: Duration::from_secs(300), - }; - let provider = build_test_table_provider( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - ) - .await; - build_optimized_promql_plan(provider, &eval_stmt).await; - } - } -} - #[tokio::test] async fn native_scan_bounds_preserve_zero_lookback_and_overflow() { let table_provider = build_test_table_provider( @@ -16489,10 +16011,7 @@ async fn test_direct_or_match_modifiers() { &modifier, ) .await; - assert_eq!( - batches.iter().map(RecordBatch::num_rows).sum::(), - expected - ); + assert_eq!(batch_rows(&batches), expected); } } @@ -17160,7 +16679,7 @@ async fn malformed_classic_bucket_does_not_drop_native_histogram() { .clone(); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); + assert_eq!(batch_rows(&batches), 1); assert_eq!(values(&batches, &value_field), vec![0.0]); let mut warnings = vec![]; let mut infos = vec![]; @@ -17206,7 +16725,7 @@ async fn test_mixed_binary_operator_aligns_both_alternative_inputs() { .clone(); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!(batch_rows(&batches), 2); assert!(values(&batches, &float_field).is_empty()); let mut sums = histograms(&batches, &histogram_field) .into_iter() @@ -17236,11 +16755,7 @@ async fn test_mixed_binary_operator_reports_only_dropped_samples() { .unwrap(); let (_, batches) = execute(plan, &state).await; - assert_eq!( - batches.iter().map(RecordBatch::num_rows).sum::(), - expected_rows, - "{query}" - ); + assert_eq!(batch_rows(&batches), expected_rows, "{query}"); let mut warnings = vec![]; let mut infos = vec![]; annotations.append_to(&mut warnings, &mut infos); @@ -17264,11 +16779,7 @@ async fn test_histogram_only_min_drops_empty_aggregate_group() { .await .unwrap(); let (_, batches) = execute(plan, &state).await; - assert_eq!( - batches.iter().map(RecordBatch::num_rows).sum::(), - 0, - "{query}" - ); + assert_eq!(batch_rows(&batches), 0, "{query}"); } } @@ -17294,7 +16805,7 @@ async fn test_mixed_min_drops_histogram_only_group() { .name() .clone(); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); + assert_eq!(batch_rows(&batches), 1); assert_eq!(values(&batches, &float_field), vec![2.0]); } @@ -17326,7 +16837,7 @@ async fn test_mixed_or_can_feed_another_or() { .clone(); let (_, batches) = execute(plan, &state).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 3); + assert_eq!(batch_rows(&batches), 3); let mut float_values = values(&batches, &float_field); float_values.sort_by(f64::total_cmp); assert_eq!(float_values, vec![2.0, 7.0]); @@ -17416,7 +16927,7 @@ async fn test_non_bool_comparison_filters_mixed_sample_lanes() { let (_, batches) = execute(plan, &build_query_engine_state()).await; assert_eq!(values(&batches, &float_field), vec![1.25]); - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); + assert_eq!(batch_rows(&batches), 1); } #[tokio::test] @@ -17610,7 +17121,7 @@ async fn test_native_histogram_sum_and_avg_execute_real_batches() { collector.append_to(&mut warnings, &mut infos); assert!(infos.is_empty()); if incompatible { - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); assert!(warnings.iter().any(|warning| { warning == &format!( @@ -17771,7 +17282,7 @@ async fn test_mixed_or_sum_aggregates_each_sample_type() { .unwrap(); let (_, batches) = execute(plan, &build_query_engine_state()).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); let mut warnings = vec![]; let mut infos = vec![]; collector.append_to(&mut warnings, &mut infos); @@ -17811,7 +17322,7 @@ async fn test_mixed_or_sum_drops_incompatible_mixed_group() { .unwrap(); let (_, batches) = execute(plan, &build_query_engine_state()).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + assert_eq!(batch_rows(&batches), 0); let mut warnings = vec![]; let mut infos = vec![]; collector.append_to(&mut warnings, &mut infos); @@ -17938,7 +17449,7 @@ async fn test_mixed_or_value_aliases_do_not_replace_labels() { &planner.ctx.field_columns )); let (_, batches) = execute(plan, &build_query_engine_state()).await; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!(batch_rows(&batches), 2); let labels = batches .iter() .flat_map(|batch| { @@ -18037,7 +17548,7 @@ async fn test_mixed_or_routes_float_histogram_and_label_functions() { .build() .unwrap(); let (_, batches) = execute(plan, &state).await; - let sample_count = batches.iter().map(RecordBatch::num_rows).sum::(); + let sample_count = batch_rows(&batches); assert_eq!(sample_count, 2); } @@ -18631,51 +18142,6 @@ async fn native_composed_binary_admits_a_split_aggregate_frame_operand() { } } -/// `sum` and `avg` over native histograms fold and merge their own state, so the statement is -/// admitted and its answer column is the canonical histogram struct. -/// -/// The single-selector split answers them: the producer folds each partition's histograms into a -/// `Partial` state and the final node merges that state above the series router, which is the -/// pairing the merge rules were written for. A histogram answer came out of this route before only -/// for statements that never folded the payload (`count`, a range function), and those keep their -/// float columns. -#[tokio::test] -async fn a_histogram_sum_or_avg_folds_natively() { - for query in [ - "sum(some_metric)", - "avg(some_metric)", - "sum(rate(some_metric[5m]))", - "avg by (tag_0) (some_metric)", - ] { - // The metric-engine table every drop over it collects for: its `le` tag is nullable, so - // the canonical pass inserts a `Merge` above the window and the split has to carry one. - // This is the fixture the regression this test guards appeared on: a split that declined - // across that merge sent `sum(rate(h[5m]))` back to the existing plan. - 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(); - 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}" - ); - // The value column is the one carrying the histogram type. Its name follows the - // expression now (`sum(some_metric)`), so the type is what identifies it. - let histogram_type = native_histogram_value_type().as_arrow_type(); - let fields = final_node.schema().fields(); - let field = fields - .iter() - .find(|field| field.data_type() == &histogram_type) - .unwrap_or_else(|| panic!("{query} published no field column: {display}")); - assert_eq!( - &histogram_type, - field.data_type(), - "{query} answers the histogram it folded: {display}" - ); - } -} - /// A source-free evaluated vector is a frame operand. /// /// `vector(2)` reads no region and answers one series on the statement's grid, so the match pairs it @@ -19110,22 +18576,6 @@ async fn histogram_state_crosses_a_canonical_merge() { ); } -/// The histogram refusals do not touch a float tree: a shape that segments today still segments. -#[tokio::test] -async fn a_float_tree_still_segments_next_to_the_histogram_gates() { - for query in [ - "sum(topk(1, some_metric)) + 1", - "avg(topk(1, some_metric)) * 2", - ] { - let plan = build_native_fused_plan(query, true).await; - assert!( - find_fused_series(&plan).is_some(), - "{query} left the native route: {}", - plan.display_indent_schema() - ); - } -} - /// A statement named after the column its own layout publishes takes a free grid name, or is /// refused when the name it would need is one a tag already holds. ///