test(perf): cover short series and enforce the native PromQL route (#10523)

* test(perf): add a short-series case and widen the native-eligible query matrix

Signed-off-by: discord9 <discord9@163.com>

* test(perf): register the short-series case in the heavy set

`many_short_series` (100,000 series x 8 samples, 8 SSTs) is the same size
class as the high-cardinality cases that already live in `HEAVY_CASES`: the
per-series setup dominates, and the self-hosted runner has been lost on
fixtures of this size before. Leaving it out of both lists meant nothing ran
it; putting it in the routine set would charge every PR regression for it.

Register it in `HEAVY_CASES` (so `/query-regression heavy` and the
`heavy` workflow-dispatch token select it) and describe the case next to the
other heavy ones in `tests/perf/README.md`.

Signed-off-by: discord9 <discord9@163.com>

* test(perf): fix the short-series case's comments and heavy selection

The case measured shapes whose comments described other shapes: the plain grid
does not cover the offset/pinned/host-filtered queries, `[10m:1m]` holds ten
aligned inner points per left-open outer window (not eleven, so two outer points
are twenty inner evaluations), and the #7913 subquery uses a five-minute inner
step rather than a one-minute one. The README also said the short case rewrites
`__name__`; it rewrites `dst`.

Registering the case in `HEAVY_CASES` also left `test_heavy_selects_the_heavy_case_set`
red, because its expectation still listed three paths; add the fourth and bring
the README's heavy description in line with the four-case set.

Signed-off-by: discord9 <discord9@163.com>

* test(perf): fail a perf case that silently measures the legacy PromQL route

The native PromQL route is off by default and declines a query it cannot take
by returning `None`, which the planner turns into the legacy plan without a
word. A perf case that means to time the native route therefore timed legacy
whenever the hint was absent, and nothing in the report said so.

A query now declares `require_native = true` on a `TQL ANALYZE ... FORMAT JSON`
statement. The runner parses the statement with the SQL parser to keep a
commented-out keyword or a look-alike `SELECT` from standing in for it, states
`query.experimental_native_promql=true` in the request hints on both targets,
and runs the same statement once per target before warmup. That response's
`plan` cells are JSON plan trees; the assertion walks their `children` and
reads only node `name` values, because a node's `param` carries the rest of its
plan line, where a label value or a filter can spell anything. A name of
`FusedSeries` or `FusedSeriesExec` (as a whole word) keeps the query; anything
else records a `validation_errors` entry naming the case, query, and target,
reports no benchmark measurement for it, and fails the run. Declaring the flag
on any other statement is a configuration error reported before either target
is contacted, because only that form answers the plan of the query being timed.

The structured form is required because text plan lines can start with a label
value: only the tree is evidence. Cases without the flag send the requests they
sent before, which a test pins by comparing the built headers.

Signed-off-by: discord9 <discord9@163.com>
(cherry picked from commit 792d8cfbf05ca352d3a915cf40036a0219651970)

* test(perf): reject a prom_http query that only looks like a TQL analyze

`require_native` is checked against the statement text, so a `kind = "prom_http"`
entry carrying a `TQL ANALYZE ... FORMAT JSON` string passed the pre-flight
check and was then posted to the Prometheus range endpoint, which answers no
plan tree: the run failed as a request error instead of the configuration error
the docs promise. Reject the kind explicitly and cover that exact combination.

Signed-off-by: discord9 <discord9@163.com>
(cherry picked from commit 868b474027b58602174a8aedca316d9d5c54a08e)

* test(perf): assert the native route in the new native cases

The 19 short-series queries and the six queries added for the remote-write
case's eligible table now declare `require_native` and are measured as
`TQL ANALYZE VERBOSE FORMAT JSON`, so the runner proves from the JSON plan
tree that each one ran on the fused-series route before its latency counts.

The three selectors on the `TIMESTAMP(9)`/`append_mode` table keep plain
`TQL ANALYZE VERBOSE` and no flag: that table can never route natively, so
requiring the route there would fail the run by design.

Signed-off-by: discord9 <discord9@163.com>

* test(perf): fold two rate points per outer step in the subquery case

At a one-minute inner step the first outer evaluation of
`max_over_time(rate(m[5m])[10m:1m])` saw a single raw sample in its rate window
and the second folded one valid rate point, so the subquery's fold was barely
exercised. At thirty seconds both outer points fold two valid rate points, and
the comment states the new arithmetic: twenty aligned inner points per outer
one, forty inner evaluations in total.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-27 10:07:53 +00:00
committed by GitHub
parent 95e69f80c3
commit fea71143b2
11 changed files with 1346 additions and 32 deletions
+4
View File
@@ -53,6 +53,10 @@ HEAVY_CASES = [
# run). Keep them in the heavy set so they only run on demand.
"tests/perf/query_cases/promql_constant_tag_concat_ms_10k/case.toml",
"tests/perf/query_cases/promql_constant_tag_concat_ms_100k/case.toml",
# 100,000 short series x 8 samples across 8 SSTs: the per-series setup
# dominates, and the fixture is as large as the high-cardinality cases
# above, so it stays on demand.
"tests/perf/query_cases/many_short_series/case.toml",
]
CASE_GROUPS = {
Generated
+1
View File
@@ -2242,6 +2242,7 @@ dependencies = [
"similar-asserts",
"smallvec",
"snafu 0.8.6",
"sql",
"sqlparser",
"standalone",
"store-api",
+1
View File
@@ -104,6 +104,7 @@ serde_json.workspace = true
servers.workspace = true
smallvec.workspace = true
snafu.workspace = true
sql.workspace = true
sqlparser.workspace = true
standalone.workspace = true
store-api.workspace = true
@@ -13,17 +13,32 @@
// limitations under the License.
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use std::{fs, io};
use query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY;
use reqwest::Client;
use serde_json::{Map, Value, json};
use sql::dialect::GreptimeDbDialect;
use sql::parser::{ParseOptions, ParserContext};
use sql::statements::statement::Statement;
use sql::statements::tql::Tql;
use sqlparser::ast::AnalyzeFormat;
use crate::query_regression_runner::model::{Measurement, Query, QueryResult, Scenario, Table};
use crate::query_regression_runner::plan::{load_plan, normalize_scenario};
use crate::query_regression_runner::sql::{http_post_prom_range_query, http_post_sql, sql_ident};
use crate::query_regression_runner::sql::{
http_post_prom_range_query, http_post_sql, http_post_sql_with_hints, plan_trees_from_response,
required_hints, sql_ident,
};
use crate::query_regression_runner::{MeasureArgs, Result};
/// The plan node names that mark the native fused-series route: the logical
/// extension node and its physical form, the shape `src/query/src/planner.rs`
/// asserts on.
const NATIVE_PROMQL_OPERATORS: [&str; 2] = ["FusedSeries", "FusedSeriesExec"];
pub(super) async fn run_measure(args: MeasureArgs) -> Result<()> {
if !args.http_timeout.is_finite() || args.http_timeout < 0.0 {
return Err("--http-timeout must be a non-negative finite number".into());
@@ -45,12 +60,25 @@ pub(super) async fn run_measure(args: MeasureArgs) -> Result<()> {
.ok_or("fixture plan has no scenario")?;
let scenario: Scenario = serde_json::from_value(scenario_value.clone())?;
let (tables, configured_queries) = normalize_scenario(scenario)?;
// A `require_native` query that cannot show its own plan is a case defect, not
// a target defect: reject it before either target is contacted.
validate_native_queries(&case_path, &configured_queries)?;
let client = Client::builder()
.timeout(Duration::from_secs_f64(args.http_timeout))
.build()?;
let base = run_target(args.base_http_port, &tables, &configured_queries, &client).await;
let base = run_target(
"base",
&case_path,
args.base_http_port,
&tables,
&configured_queries,
&client,
)
.await;
let candidate = run_target(
"candidate",
&case_path,
args.candidate_http_port,
&tables,
&configured_queries,
@@ -110,23 +138,29 @@ fn target_report(name: &str, http_port: u16, result: QueryResult) -> Value {
/// the Prometheus HTTP range API (which exercises the Prometheus JSON response
/// builder), everything else goes through `/v1/sql` (including `TQL ANALYZE`).
async fn post_query(client: &Client, port: u16, query: &Query, db: &str) -> Value {
post_query_with_hints(client, port, query, db, required_hints(query).as_deref()).await
}
/// Posts one configured query, stating `hints` on the wire when the caller has
/// any. Every request the runner makes for a query goes through here, so a
/// `require_native` query states its hint on both targets.
async fn post_query_with_hints(
client: &Client,
port: u16,
query: &Query,
db: &str,
hints: Option<&str>,
) -> Value {
if query.kind.as_deref() == Some("prom_http") {
http_post_prom_range_query(
client,
port,
&query.query,
query.start.as_deref(),
query.end.as_deref(),
query.step.as_deref(),
db,
)
.await
http_post_prom_range_query(client, port, query, db, hints).await
} else {
http_post_sql(client, port, &query.query, db).await
http_post_sql_with_hints(client, port, &query.query, db, hints).await
}
}
async fn run_target(
target: &str,
case_path: &Path,
port: u16,
tables: &[Table],
configured_queries: &[Query],
@@ -144,6 +178,7 @@ async fn run_target(
warmup: 0,
iterations: 1,
thresholds: Map::new(),
require_native: false,
});
}
@@ -182,6 +217,15 @@ async fn run_target(
let mut measurements = Vec::with_capacity(queries.len());
for query in &queries {
if query.require_native {
// Asserted once per target per query, before warmup: a case routed to
// the legacy planner fails in seconds and reports no latency.
let outcome = probe_native_route(target, client, port, query, db).await;
if !record_native_route_check(case_path, target, query, outcome, &mut validation_errors)
{
continue;
}
}
for _ in 0..query.warmup {
let warmup = post_query(client, port, query, db).await;
if !warmup["ok"].as_bool().unwrap_or(false) {
@@ -239,6 +283,210 @@ async fn run_target(
}
}
/// What one failed native-route assertion observed on one target.
struct NativeRouteFailure {
/// The plan tree that response carried, or the whole body when it carried none.
observed: String,
/// What went wrong, before the case, query, and target identification is added.
reason: String,
}
/// Whether a statement is a `TQL ANALYZE ... FORMAT JSON` form, whose own response
/// carries the plan tree of the statement.
///
/// The statement is parsed rather than pattern-matched as text: only the parser
/// knows whether those keywords belong to the statement or to a comment, and only
/// `FORMAT JSON` makes the response a plan tree instead of plan text lines.
fn is_tql_plan_statement(statement: &str) -> bool {
let Ok(mut statements) = ParserContext::create_with_dialect(
statement,
&GreptimeDbDialect {},
ParseOptions::default(),
) else {
return false;
};
statements.len() == 1
&& matches!(
statements.pop(),
Some(Statement::Tql(Tql::Analyze(analyze)))
if analyze.format == Some(AnalyzeFormat::JSON)
)
}
/// Whether a JSON plan tree names the native fused-series operator.
///
/// Only a node's own `name` counts. `param` holds the rest of that plan line,
/// where a label value or a filter can spell anything, so it is never read.
fn plan_tree_names_native(tree: &Value) -> bool {
match tree {
Value::Object(node) => {
node.get("name")
.and_then(Value::as_str)
.is_some_and(is_native_operator_name)
|| node
.get("children")
.and_then(Value::as_array)
.is_some_and(|children| children.iter().any(plan_tree_names_native))
}
Value::Array(nodes) => nodes.iter().any(plan_tree_names_native),
_ => false,
}
}
/// Whether a plan node name is the native fused-series operator.
///
/// A name may carry the rest of its plan line (`FusedSeriesExec metrics=[]`), so
/// the operator has to match as a whole word.
fn is_native_operator_name(name: &str) -> bool {
NATIVE_PROMQL_OPERATORS.iter().any(|operator| {
name.strip_prefix(operator).is_some_and(|rest| {
rest.chars()
.next()
.is_none_or(|character| !character.is_alphanumeric() && character != '_')
})
})
}
/// The name of a query in messages: its declared name, or its statement.
fn query_label(query: &Query) -> &str {
query.name.as_deref().unwrap_or(&query.query)
}
/// Rejects `require_native` queries that cannot prove their plan, before either
/// target is contacted.
///
/// Only `TQL ANALYZE ... FORMAT JSON` answers the plan tree of the statement
/// itself, and a statement that is not the timed query cannot prove anything about
/// it.
fn validate_native_queries(case_path: &Path, queries: &[Query]) -> Result<()> {
if let Some(query) = queries.iter().find(|query| {
query.require_native
&& (query.kind.as_deref() == Some("prom_http") || !is_tql_plan_statement(&query.query))
}) {
return Err(format!(
"case {}: query `{}` declares require_native but is not a `TQL ANALYZE ... FORMAT \
JSON` request to `/v1/sql`; only that statement answers the plan tree of the query \
being timed, so nothing else can prove the native route",
case_path.display(),
query_label(query),
)
.into());
}
Ok(())
}
/// Proves one `require_native` query runs on the native fused-series route on one
/// target.
///
/// The assertion runs the same statement one extra time before any timing sample,
/// with the same hint, and reads the plan tree out of that untimed response.
async fn probe_native_route(
target: &str,
client: &Client,
port: u16,
query: &Query,
db: &str,
) -> std::result::Result<(), NativeRouteFailure> {
let hints = required_hints(query);
let sample = post_query_with_hints(client, port, query, db, hints.as_deref()).await;
if !sample["ok"].as_bool().unwrap_or(false) {
return Err(NativeRouteFailure {
observed: sample
.get("response")
.map(response_text)
.unwrap_or_default(),
reason: request_failure_reason(target, &sample),
});
}
native_route_verdict(&sample["response"]).map_err(|reason| NativeRouteFailure {
observed: sample
.get("response")
.map(response_text)
.unwrap_or_default(),
reason,
})
}
/// Whether one analyze response proves the native route, or why it does not.
fn native_route_verdict(body: &Value) -> std::result::Result<(), String> {
const NOT_A_TREE: &str = "its response was not a JSON plan tree, so it names no plan node; \
the statement must be `TQL ANALYZE ... FORMAT JSON`";
let Some(trees) = plan_trees_from_response(body) else {
return Err(NOT_A_TREE.to_string());
};
if trees.iter().any(plan_tree_names_native) {
Ok(())
} else {
Err(format!(
"its plan tree names no {} node, so it took the legacy path",
native_operator_list()
))
}
}
/// Records one query's native-route outcome on one target.
///
/// Returns whether the target may time the query: a failed assertion records a
/// `validation_errors` entry and skips the query, so the target reports no
/// benchmark measurement for a query that ran on the legacy route.
fn record_native_route_check(
case_path: &Path,
target: &str,
query: &Query,
outcome: std::result::Result<(), NativeRouteFailure>,
validation_errors: &mut Vec<Value>,
) -> bool {
let Err(failure) = outcome else {
return true;
};
let message = format!(
"case {}: query `{}` on the {target} target must be planned on the native PromQL route, \
but {}; expected a plan node named {}",
case_path.display(),
query_label(query),
failure.reason,
native_operator_list(),
);
validation_errors.push(json!({
"sql": query.query,
"error": message,
"response": plan_excerpt(&failure.observed),
}));
false
}
/// The accepted plan node names, for a failure message.
fn native_operator_list() -> String {
NATIVE_PROMQL_OPERATORS.join(" or ")
}
/// Explains a failed hint-bearing request, including the base-binary hazard: an
/// unknown `query.*` option is a hard error, so a target whose binary predates the
/// option fails here instead of silently planning the legacy route.
fn request_failure_reason(target: &str, sample: &Value) -> String {
let status = match sample.get("status").and_then(Value::as_u64) {
Some(status) => format!("HTTP {status}"),
None => sample
.get("error")
.and_then(Value::as_str)
.unwrap_or("no response")
.to_string(),
};
format!(
"the request failed ({status}); the {target} binary may predate \
`{NATIVE_PROMQL_EXTENSION_KEY}`, and require_native needs a base that supports it"
)
}
/// The beginning of a plan or response body, short enough for a report entry.
fn plan_excerpt(text: &str) -> String {
const MAX_CHARS: usize = 1200;
match text.char_indices().nth(MAX_CHARS) {
Some((index, _)) => format!("{}…", &text[..index]),
None => text.to_string(),
}
}
fn validate_show_create(result: &Value, table: &Table) -> Vec<&'static str> {
let text = result
.get("response")
@@ -445,6 +693,7 @@ mod tests {
("max_candidate_latency_regression_pct".to_string(), json!(0)),
("other".to_string(), json!(1)),
]),
require_native: false,
};
let measurement = |median| Measurement {
name: Some("q".to_string()),
@@ -474,4 +723,313 @@ mod tests {
);
assert_eq!(results[1]["reason"], "unsupported threshold");
}
fn native_query(kind: Option<&str>, query: &str) -> Query {
let range_parameter =
|value: &'static str| (kind == Some("prom_http")).then(|| value.to_string());
Query {
name: Some("native_range".to_string()),
kind: kind.map(ToString::to_string),
query: query.to_string(),
start: range_parameter("1704067200"),
end: range_parameter("1704070800"),
step: range_parameter("15s"),
warmup: 0,
iterations: 1,
thresholds: Map::new(),
require_native: true,
}
}
/// An `ANALYZE ... FORMAT JSON` response body in the shape `format=json`
/// answers: one object per row keyed by column name.
fn analyze_body(cells: &[&str]) -> Value {
json!({
"data": cells
.iter()
.enumerate()
.map(|(node, cell)| json!({"stage": 0, "node": node, "plan": cell}))
.collect::<Vec<_>>(),
"execution_time_ms": 3,
})
}
/// One plan tree node, as `ANALYZE ... FORMAT JSON` prints it.
fn plan_node(name: &str, param: &str, children: Vec<Value>) -> Value {
json!({
"name": name,
"param": param,
"output_rows": 4,
"elapsed_compute": 7,
"metrics": {},
"children": children,
})
}
/// The evidence pipeline [`probe_native_route`] applies to one response body.
fn plans_native(body: &Value) -> bool {
plan_trees_from_response(body).is_some_and(|trees| trees.iter().any(plan_tree_names_native))
}
#[test]
fn native_plan_classification_reads_the_tree_node_names() {
// The physical operator as its own node, and the logical extension node as
// a node an operator runs inside itself. The analyze result always ends
// with a plain-text `Total rows` cell, which is not evidence either way.
let fused = plan_node(
"FusedSeriesExec",
"metric=some_metric",
vec![plan_node("SeriesScan", "region=0", vec![])],
)
.to_string();
let repartition = plan_node("SeriesRepartitionExec", "", vec![]).to_string();
assert!(plans_native(&analyze_body(&[
&fused,
&repartition,
"Total rows: 580"
])));
let logical = plan_node(
"CooperativeExec",
"",
vec![plan_node("FusedSeries", "metric=some_metric", vec![])],
)
.to_string();
assert!(plans_native(&analyze_body(&[&logical, "Total rows: 4"])));
assert!(
native_route_verdict(&analyze_body(&[&fused, &repartition, "Total rows: 580"])).is_ok()
);
// A name may carry the rest of its plan line.
let named_with_metrics =
plan_node("FusedSeriesExec metrics=[]", "metric=m", vec![]).to_string();
assert!(plans_native(&analyze_body(&[
&named_with_metrics,
"Total rows: 4"
])));
// A legacy tree names no fused node at any depth.
let legacy = plan_node(
"PromInstantManipulateExec",
"range=[0..10000]",
vec![plan_node(
"PromSeriesDivideExec",
"tags=[\"host\"]",
vec![plan_node("MergeScanExec", "peers=[]", vec![])],
)],
)
.to_string();
let body = analyze_body(&[&legacy, "Total rows: 580"]);
assert!(!plans_native(&body));
let reason = native_route_verdict(&body).unwrap_err();
assert!(
reason.contains("names no FusedSeries or FusedSeriesExec node"),
"{reason}"
);
}
#[test]
fn native_plan_classification_never_reads_the_param_of_a_node() {
// The marker in a node's `param` is the rest of a plan line: a filter or a
// label value can spell it, so it is not evidence of the operator.
let filtered =
plan_node("TableScan", "m, filter=FusedSeries IS NOT NULL", vec![]).to_string();
assert!(!plans_native(&analyze_body(&[&filtered, "Total rows: 4"])));
let filtered_exec = plan_node(
"Filter",
"FusedSeriesExec = 1",
vec![plan_node("SeriesScan", "metric=FusedSeries_x", vec![])],
)
.to_string();
assert!(!plans_native(&analyze_body(&[
&filtered_exec,
"Total rows: 4"
])));
// A name that only starts with the operator text is a different node.
let similar = plan_node("FusedSeriesExtraExec", "metric=some_metric", vec![]).to_string();
assert!(!plans_native(&analyze_body(&[&similar, "Total rows: 4"])));
}
#[test]
fn native_plan_classification_fails_closed_without_a_plan_tree() {
// A text plan cell is not a tree, so it proves no node; the same holds for
// a body without a readable `plan` column.
let text_only = json!({"data": [{"plan": "Total rows: 1"}]});
assert!(plan_trees_from_response(&text_only).is_none());
assert!(!plans_native(&text_only));
let reason = native_route_verdict(&text_only).unwrap_err();
assert!(reason.contains("was not a JSON plan tree"), "{reason}");
assert!(reason.contains("TQL ANALYZE ... FORMAT JSON"), "{reason}");
assert!(!plans_native(
&json!({"data": [{"plan": "CooperativeExec\n FusedSeriesExec"}]})
));
assert!(!plans_native(&json!({"data": [{"note": "FusedSeries"}]})));
assert!(!plans_native(&json!({"data": []})));
assert!(!plans_native(
&json!({"output": [{"rows": [["FusedSeries"]]}]})
));
}
#[test]
fn require_native_query_must_be_a_tql_analyze_format_json_statement() {
let case_path = Path::new("tests/perf/query_cases/prom_native/case.toml");
for (kind, statement) in [
(Some("prom_http"), "rate(some_metric[5m])"),
(Some("sql"), "TQL EVAL (0, 10, '5s') some_metric"),
(Some("sql"), "SELECT count(*) FROM t"),
// The concrete false pass: a commented-out keyword in front of a
// statement that echoes the marker.
(
Some("sql"),
"/* TQL ANALYZE FORMAT JSON */ SELECT 'FusedSeries' AS plan",
),
// The statement parses, but this kind sends it to the Prometheus
// range endpoint, which answers no plan tree.
(
Some("prom_http"),
"TQL ANALYZE FORMAT JSON (0, 10, '5s') some_metric",
),
] {
let error = validate_native_queries(case_path, &[native_query(kind, statement)])
.expect_err("require_native outside the JSON analyze form must be rejected")
.to_string();
assert!(error.contains("prom_native/case.toml"), "{error}");
assert!(error.contains("native_range"), "{error}");
assert!(error.contains("TQL ANALYZE ... FORMAT JSON"), "{error}");
}
for statement in [
"TQL ANALYZE VERBOSE FORMAT JSON (0, 10, '5s') some_metric",
"TQL ANALYZE FORMAT JSON (0, 10, '5s') some_metric",
"tql analyze format json (0, 10, '5s') some_metric",
] {
assert!(
validate_native_queries(case_path, &[native_query(Some("sql"), statement)]).is_ok(),
"{statement}"
);
}
}
#[test]
fn tql_plan_statement_requires_the_json_format() {
for statement in [
"TQL ANALYZE VERBOSE FORMAT JSON (0, 10, '5s') some_metric",
"TQL ANALYZE FORMAT JSON (0, 10, '5s') some_metric",
] {
assert!(is_tql_plan_statement(statement), "{statement:?}");
}
for statement in [
// The text form answers plan lines, which a label value can imitate.
"TQL ANALYZE VERBOSE (0, 10, '5s') some_metric",
"TQL ANALYZE (0, 10, '5s') some_metric",
"TQL ANALYZE FORMAT TEXT (0, 10, '5s') some_metric",
"TQL EXPLAIN VERBOSE FORMAT JSON (0, 10, '5s') some_metric",
"TQL EVAL (0, 10, '5s') some_metric",
"SELECT 'TQL ANALYZE FORMAT JSON'",
"ANALYZE TABLE t",
"TQL",
] {
assert!(!is_tql_plan_statement(statement), "{statement:?}");
}
}
#[test]
fn failed_native_route_check_records_a_validation_error_and_skips_the_query() {
let case_path = Path::new("tests/perf/query_cases/prom_native/case.toml");
let query = native_query(
Some("sql"),
"TQL ANALYZE FORMAT JSON (0, 10, '5s') rate(some_metric[5m])",
);
let mut validation_errors = Vec::new();
let failure = NativeRouteFailure {
observed: "CooperativeExec\n MergeScanExec: peers=[]".to_string(),
reason: "its plan tree names no FusedSeries or FusedSeriesExec node, so it took \
the legacy path"
.to_string(),
};
let measure = record_native_route_check(
case_path,
"candidate",
&query,
Err(failure),
&mut validation_errors,
);
// The query is skipped, so no `Measurement` is pushed for it.
assert!(!measure);
assert_eq!(validation_errors.len(), 1);
let entry = &validation_errors[0];
assert_eq!(
entry["sql"],
"TQL ANALYZE FORMAT JSON (0, 10, '5s') rate(some_metric[5m])"
);
assert_eq!(
entry["response"],
"CooperativeExec\n MergeScanExec: peers=[]"
);
let message = entry["error"].as_str().unwrap();
assert!(message.contains("prom_native/case.toml"), "{message}");
assert!(message.contains("native_range"), "{message}");
assert!(message.contains("candidate"), "{message}");
assert!(
message.contains("FusedSeries or FusedSeriesExec"),
"{message}"
);
// The observed plan stays in `response`, like the other entries in this file.
assert!(
entry["response"]
.as_str()
.unwrap()
.contains("MergeScanExec"),
"{entry}"
);
// A passing check keeps the query and records nothing.
let mut validation_errors = Vec::new();
assert!(record_native_route_check(
case_path,
"base",
&query,
Ok(()),
&mut validation_errors
));
assert!(validation_errors.is_empty());
}
#[test]
fn failed_hint_request_names_the_base_binary_hazard() {
let rejected = json!({
"ok": false,
"status": 400,
"latency_ms": 1.0,
"error": "HTTP 400",
"response": {"error": "Unknown or unsupported query option: query.experimental_native_promql"},
});
let reason = request_failure_reason("base", &rejected);
assert!(reason.contains("HTTP 400"), "{reason}");
assert!(reason.contains("may predate"), "{reason}");
assert!(
reason.contains("query.experimental_native_promql"),
"{reason}"
);
assert!(
reason.contains("require_native needs a base that supports it"),
"{reason}"
);
let unreachable = json!({"ok": false, "status": null, "error": "connection refused"});
assert!(request_failure_reason("candidate", &unreachable).contains("connection refused"));
}
#[test]
fn plan_excerpt_caps_the_character_count() {
let plan = "n".repeat(1_300);
let excerpt = plan_excerpt(&plan);
assert_eq!(excerpt.chars().count(), 1_201);
assert!(excerpt.ends_with('…'));
assert_eq!(plan_excerpt("short"), "short");
}
}
@@ -226,12 +226,28 @@ pub(super) struct Query {
pub(super) iterations: usize,
#[serde(default)]
pub(super) thresholds: Map<String, Value>,
/// Whether this query must be planned on the native PromQL route.
///
/// The runner states `query.experimental_native_promql=true` in the request
/// hints of every request it makes for the query, on every target, and proves
/// the plan tree of the statement names a `FusedSeries`/`FusedSeriesExec` node
/// before it records a timing sample. Only a `TQL ANALYZE ... FORMAT JSON`
/// statement answers that plan tree, so any other statement is a configuration
/// error.
#[serde(default, skip_serializing_if = "is_false")]
pub(super) require_native: bool,
}
const fn one() -> usize {
1
}
/// Skips the default value of [`Query::require_native`] in reports, so a case
/// that does not declare it serializes as it did before the field existed.
fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Debug, Serialize)]
pub(super) struct QueryResult {
pub(super) validation: Vec<Value>,
+207 -16
View File
@@ -14,10 +14,33 @@
use std::time::Instant;
use reqwest::Client;
use query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY;
use reqwest::{Client, RequestBuilder};
use serde_json::{Value, json};
use crate::query_regression_runner::Result;
use crate::query_regression_runner::model::Query;
/// Header that carries per-request query hints.
///
/// The name is a literal because it lives in the `session` crate
/// (`session::hints::HINTS_KEY`), which this runner does not depend on.
const HINTS_HEADER: &str = "x-greptime-hints";
/// The hints value that asks the frontend to plan a PromQL statement on the
/// native fused-series route, built from the option key the planner reads.
pub(super) fn native_promql_hint() -> String {
format!("{NATIVE_PROMQL_EXTENSION_KEY}=true")
}
/// The value of the hints header one query needs, or [`None`] when the query
/// declares no requirement.
///
/// A query without [`Query::require_native`] keeps sending exactly the request it
/// sent before this header existed.
pub(super) fn required_hints(query: &Query) -> Option<String> {
query.require_native.then(native_promql_hint)
}
pub(super) fn sql_string(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
@@ -93,6 +116,28 @@ pub(super) fn value_text(value: &Value) -> String {
}
}
/// The plan trees of a `TQL ANALYZE ... FORMAT JSON` response body.
///
/// `format=json` answers `data` as one object per row keyed by column name, and
/// `FORMAT JSON` puts a plan tree into a row's `plan` cell: a node names itself in
/// `name`, carries the rest of its plan line in `param`, and hangs its sub-nodes
/// from `children`. The analyze result also carries a plain-text `Total rows: N`
/// cell, so only the cells that are JSON objects or arrays are kept; a text cell
/// never contributes evidence.
///
/// [`None`] means the body held no plan tree at all, which proves no node.
pub(super) fn plan_trees_from_response(body: &Value) -> Option<Vec<Value>> {
let trees = body
.get("data")?
.as_array()?
.iter()
.filter_map(|row| row.get("plan")?.as_str())
.filter_map(|cell| serde_json::from_str::<Value>(cell).ok())
.filter(|tree| tree.is_object() || tree.is_array())
.collect::<Vec<_>>();
(!trees.is_empty()).then_some(trees)
}
pub(super) fn extract_count_value(result: &Value) -> Option<u64> {
let row = result
.get("response")?
@@ -117,10 +162,23 @@ pub(super) fn value_f64(value: Option<&Value>) -> Option<f64> {
}
pub(super) async fn http_post_sql(client: &Client, port: u16, sql: &str, db: &str) -> Value {
http_post_sql_with_hints(client, port, sql, db, None).await
}
/// Posts one SQL statement, carrying `hints` in the request hints header when the
/// caller states any.
pub(super) async fn http_post_sql_with_hints(
client: &Client,
port: u16,
sql: &str,
db: &str,
hints: Option<&str>,
) -> Value {
let mut sample = post_form(
client,
format!("http://127.0.0.1:{port}/v1/sql"),
&[("sql", sql), ("db", db), ("format", "json")],
hints,
)
.await;
sample
@@ -130,34 +188,36 @@ pub(super) async fn http_post_sql(client: &Client, port: u16, sql: &str, db: &st
sample
}
/// Posts a Prometheus HTTP API range query (`/v1/prometheus/api/v1/query_range`)
/// and measures the full request-to-body latency. This exercises the Prometheus
/// JSON response building path (`PrometheusJsonResponse::record_batches_to_data`)
/// that `/v1/sql` (including `TQL ANALYZE`) does not go through.
/// Posts the Prometheus HTTP API range query (`/v1/prometheus/api/v1/query_range`)
/// one configured query declares, and measures the full request-to-body latency.
/// This exercises the Prometheus JSON response building path
/// (`PrometheusJsonResponse::record_batches_to_data`) that `/v1/sql` (including
/// `TQL ANALYZE`) does not go through.
///
/// `hints` carries the request hints header when the caller states any.
pub(super) async fn http_post_prom_range_query(
client: &Client,
port: u16,
query: &str,
start: Option<&str>,
end: Option<&str>,
step: Option<&str>,
query: &Query,
db: &str,
hints: Option<&str>,
) -> Value {
let mut sample = post_form(
client,
prom_range_query_url(port, db),
&[
("query", query),
("start", start.unwrap_or_default()),
("end", end.unwrap_or_default()),
("step", step.unwrap_or_default()),
("query", &query.query),
("start", query.start.as_deref().unwrap_or_default()),
("end", query.end.as_deref().unwrap_or_default()),
("step", query.step.as_deref().unwrap_or_default()),
],
hints,
)
.await;
sample
.as_object_mut()
.expect("HTTP samples are objects")
.insert("query".to_string(), Value::String(query.to_string()));
.insert("query".to_string(), Value::String(query.query.clone()));
sample
}
@@ -170,9 +230,14 @@ fn prom_range_query_url(port: u16, db: &str) -> String {
url.into()
}
async fn post_form(client: &Client, url: String, form: &[(&str, &str)]) -> Value {
async fn post_form(
client: &Client,
url: String,
form: &[(&str, &str)],
hints: Option<&str>,
) -> Value {
let started = Instant::now();
let request = client.post(url).form(form);
let request = build_form_request(client, url, form, hints);
match request.send().await {
Ok(response) => {
let status = response.status().as_u16();
@@ -211,6 +276,21 @@ async fn post_form(client: &Client, url: String, form: &[(&str, &str)]) -> Value
}
}
/// Builds one form-encoded POST, attaching the hints header only when the query
/// states one, so an unflagged query's request stays what it was.
fn build_form_request(
client: &Client,
url: String,
form: &[(&str, &str)],
hints: Option<&str>,
) -> RequestBuilder {
let request = client.post(url).form(form);
match hints {
Some(hints) => request.header(HINTS_HEADER, hints),
None => request,
}
}
fn response_has_error(body: &Value) -> bool {
let Some(body) = body.as_object() else {
return false;
@@ -257,6 +337,117 @@ pub(super) fn sql_ident(name: &str) -> String {
mod tests {
use super::*;
fn query(require_native: bool) -> Query {
Query {
name: Some("native_range".to_string()),
kind: Some("sql".to_string()),
query: "TQL ANALYZE (0, 10, '5s') some_metric".to_string(),
start: None,
end: None,
step: None,
warmup: 0,
iterations: 1,
thresholds: serde_json::Map::new(),
require_native,
}
}
fn request_headers(query: &Query) -> reqwest::header::HeaderMap {
let client = Client::new();
build_form_request(
&client,
"http://127.0.0.1:4000/v1/sql".to_string(),
&[("sql", "SELECT 1"), ("format", "json")],
required_hints(query).as_deref(),
)
.build()
.expect("request must build without a network")
.headers()
.clone()
}
#[test]
fn native_route_query_states_the_hint_and_an_unflagged_query_does_not() {
let native = request_headers(&query(true));
assert_eq!(
native
.get(HINTS_HEADER)
.and_then(|value| value.to_str().ok()),
Some("query.experimental_native_promql=true")
);
let plain = request_headers(&query(false));
assert!(plain.get(HINTS_HEADER).is_none());
// The unflagged request keeps the headers it sent before the hint existed.
let baseline = Client::new()
.post("http://127.0.0.1:4000/v1/sql")
.form(&[("sql", "SELECT 1"), ("format", "json")])
.build()
.expect("request must build without a network")
.headers()
.clone();
assert_eq!(plain, baseline);
}
#[test]
fn plan_trees_read_only_the_plan_column_of_the_json_data_shape() {
// `format=json` answers `data` as one object per row keyed by column name,
// and `FORMAT JSON` puts one plan tree into the `plan` cell.
let analyze = json!({
"data": [
{
"stage": 0,
"node": 0,
"plan": json!({
"name": "CooperativeExec",
"param": "",
"children": [{"name": "FusedSeriesExec", "param": "metric=m", "children": []}],
})
.to_string(),
},
{
"stage": 1,
"node": 0,
"plan": json!({"name": "SeriesScan", "param": "region=0", "children": []})
.to_string(),
},
],
"execution_time_ms": 3,
});
let trees = plan_trees_from_response(&analyze).unwrap();
assert_eq!(trees.len(), 2);
assert_eq!(trees[0]["name"], "CooperativeExec");
assert_eq!(trees[0]["children"][0]["name"], "FusedSeriesExec");
assert_eq!(trees[1]["name"], "SeriesScan");
// The analyze result always ends with a plain-text `Total rows` cell, which
// is ignored rather than treated as a malformed tree.
let with_total = json!({
"data": [
{"plan": json!({"name": "FusedSeriesExec", "param": "metric=m", "children": []})
.to_string()},
{"plan": "Total rows: 580"},
],
});
assert_eq!(plan_trees_from_response(&with_total).unwrap().len(), 1);
// A `plan` column of text cells, an empty cell, and a result without a
// `plan` column all hold no tree, even when a cell spells the marker.
assert!(
plan_trees_from_response(&json!({"data": [{"plan": "CooperativeExec"}]})).is_none()
);
assert!(plan_trees_from_response(&json!({"data": [{"plan": "Total rows: 1"}]})).is_none());
assert!(
plan_trees_from_response(&json!({"data": [{"plan": "\"FusedSeries\""}]})).is_none()
);
assert!(plan_trees_from_response(&json!({"data": [{"stage": 0, "plan": ""}]})).is_none());
assert!(plan_trees_from_response(&json!({"data": [{"note": "FusedSeries"}]})).is_none());
assert!(plan_trees_from_response(&json!({"data": []})).is_none());
assert!(
plan_trees_from_response(&json!({"output": [{"rows": [["FusedSeries"]]}]})).is_none()
);
}
#[test]
fn prom_range_query_url_places_database_in_query_parameters() {
let url = reqwest::Url::parse(&prom_range_query_url(4000, "catalog-schema name"))
+66 -3
View File
@@ -228,11 +228,20 @@ case for issue #7913. It writes 8192 series × 20160 samples through remote-writ
in 1440-sample daily time chunks, flushing after each chunk before running 1d/7d/14d
TQL selectors. It is not included in the default `all` case set because ingestion
cost dominates routine CI validation. Commenting `/query-regression heavy` runs
only this case; `/query-regression` runs the nine routine default cases, including
the heavy set, which starts with this case; `/query-regression` runs the nine routine default cases, including
`sst_float_bss`, `promql_instant_last_row_9034`, and
`mito_prefilter_all_match`. Manual
workflow dispatch accepts the `heavy` token to select this case.
`tests/perf/query_cases/many_short_series/case.toml` is the wide-and-shallow
companion to `promql_constant_tag_concat_ms_100k`: 100,000 series x 8 samples in
8 non-overlapping SSTs (800,000 rows, `TIMESTAMP(3)`, not `append_mode`), with 19
queries covering the split aggregate, `topk`, `on(...)`/`ignoring` matching,
`avg`/`max`/`quantile_over_time`, `label_replace` rewriting a label (`dst`), filter and
`bool` comparison, `and`, a subquery, `offset`, `@` and an instant evaluation.
Every query must stay on the native fused-series route. Like the other
high-cardinality cases it is in the `heavy` set, not the routine one.
The routine default set also includes
`tests/perf/query_cases/mito_prefilter_all_match/case.toml`. It covers the
Mito prefilter all-match path, a mixed integer/float filter, and integer and
@@ -348,6 +357,59 @@ seed = 12345
The outer driver currently supports `direct_readable_sst`,
`prom_remote_write_then_query`, and `otlp_trace_load`.
## Native PromQL route enforcement
The native fused-series PromQL route is off by default
(`query.experimental_native_promql`) and a query it does not accept falls back to
the legacy planner without saying so. A case that means to time the native route
therefore declares it:
```toml
[[scenario.queries]]
name = "native_rate"
kind = "sql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067200, 1704070800, '15s') rate(some_metric[5m])"
require_native = true
warmup = 3
iterations = 15
```
`require_native` defaults to `false`, is legal only on a `TQL ANALYZE [VERBOSE]
FORMAT JSON (...)` statement, and changes two things for that query:
- `query_regression_runner` adds
`x-greptime-hints: query.experimental_native_promql=true` to every request it
makes for the query, on both the base and the candidate target. A query without
the flag sends exactly the request it sent before the flag existed.
- Once per target, before warmup, the runner runs the same statement one extra
time and inspects that untimed response. `FORMAT JSON` is required because the
text `ANALYZE` output is plan lines, and a label value or a filter can begin a
line with anything; the JSON form answers a plan tree instead. The assertion
walks that tree's `children` and reads each node's `name` only, accepting a node
whose name is `FusedSeries` or `FusedSeriesExec` (the name may carry the rest of
its plan line). A node's `param` is never read, because that is where a label
value or a filter spells the marker, and the trailing `Total rows: N` cell is
text that carries no node. The timed samples themselves are not re-inspected.
A plan tree without such a node, or a response that is not a JSON plan tree, fails
that target: the run records a `validation_errors` entry naming the case, query,
and target plus the observed response, and reports no benchmark measurement for
that query, so its latency is never compared. The earlier validation sample of the
first query keeps its own latency; `measure` exits non-zero.
A `require_native` query whose statement is not a `TQL ANALYZE [VERBOSE] FORMAT
JSON (...)` form — `kind = "prom_http"`, a plain `TQL EVAL`, `TQL ANALYZE` without
`FORMAT JSON`, plain SQL — is a configuration error: the run stops before it
contacts either target, with a message naming the case and the query. Only that
statement answers the plan tree of the statement being timed, so nothing else
could prove the route. The statement is parsed, so a keyword that only appears in
a comment does not qualify.
An unknown `query.*` option is a hard HTTP error, so a target whose binary
predates `query.experimental_native_promql` fails the assertion instead of being
timed on the legacy route. A `require_native` case needs a base that supports the
option, and the same holds for the candidate.
## Metrics
Primary gates should compare query work rather than plan text:
@@ -561,8 +623,9 @@ The workflow runs when an allowlisted repository admin comments
`/query-regression` on a non-draft PR. It does not rerun on pushes,
ready-for-review, or reopen events. `/query-regression` runs the nine routine
default cases, including `sst_float_bss`, `promql_instant_last_row_9034`, and
`mito_prefilter_all_match`; `/query-regression heavy` runs only the
high-cardinality remote-write #7913 case. PR runs build base/candidate once and
`mito_prefilter_all_match`; `/query-regression heavy` runs the heavy set: the
high-cardinality remote-write #7913 case, the two constant-tag concat cases, and
`many_short_series`. PR runs build base/candidate once and
use `--allow-large-fixture`. Manual `workflow_dispatch` runs can pass `all`,
`heavy`, one case path, or a comma/whitespace-separated list of case paths, and
can override refs.
+11
View File
@@ -72,6 +72,17 @@ response body is read and parsed as JSON. It therefore includes request send,
server-side Prometheus JSON response building, and response-body read and JSON
parsing; it is not server-side-only latency.
### Native PromQL route
`require_native = true` (default `false`) states that a query must be planned on
the native fused-series PromQL route, and is legal only on a
`TQL ANALYZE [VERBOSE] FORMAT JSON (...)` statement. The runner sends
`x-greptime-hints: query.experimental_native_promql=true` on every request it
makes for that query and proves the statement's plan tree before it times the
query. See the "Native PromQL route enforcement" section of
[`README.md`](README.md) for the requirement, the assertion, and the failure
semantics.
`series_layout = "round_robin"` advances the timestamp once per generated row and
cycles series labels across rows. `series_layout = "timestamp_major"` writes all
series for one timestamp before advancing to the next timestamp; use it for
@@ -0,0 +1,364 @@
# Many short series: 100,000 series x 8 samples in 8 non-overlapping SSTs.
#
# This is the "wide and shallow" companion to promql_constant_tag_concat_ms_100k
# (100,000 series, 8 samples per series per file, 32 SSTs). Here every series
# holds only eight samples in total, one per file, so a five-minute window spans
# every file and the query cost is dominated by per-series setup rather than by
# points per series.
#
# It is also the only direct-SST case whose table is *not* `append_mode`: the
# native fused-series route admits a region only when its time index is
# `TIMESTAMP(3)` and the table is copy-on-write (see the raw-series preflight in
# `src/query/src/promql/planner/native.rs`, the
# `timestamp_millisecond_datatype` / `APPEND_MODE_KEY` checks). A `TIMESTAMP(9)`
# or `append_mode` fixture would send every query below down the legacy plan.
#
# Layout arithmetic (timestamp-major generation: every series occurs once per
# scrape timestamp, and every file holds one timestamp for all series):
# sst_count 8 x rows_per_sst 100,000 = 800,000 rows
# series_count 100,000 -> 8 samples per series
# step 15s -> 00:00:00Z, 00:00:15Z, ... 00:01:45Z (a 105-second span)
# Measured on the generated fixture: 800,000 rows, 100,000 distinct
# (host, instance) pairs, 16 distinct hosts, 8 distinct timestamps, and exactly
# 8 samples per series.
#
# Label cardinality: the generator derives each tag value as
# `series % cardinality`, so the number of distinct (host, instance) series is
# the least common multiple of the two cardinalities, capped by series_count.
# The requested 16 hosts x 6,250 instances is not expressible: lcm(16, 6250) is
# 50,000, which would silently halve the series count. `instance` therefore
# declares 6,251 values, which is coprime with 16 (it is odd), so
# 16 x 6,251 = 100,016 >= 100,000 and all 100,000 series keep a distinct label
# pair: 16 hosts with 6,250 or 6,251 instances each, the closest expressible
# shape to the request.
#
# Query matrix: one entry per plan shape the native fused-series route is meant
# to answer, plus the controls that keep a shape's timing honest. Every query is
# measured as `TQL ANALYZE VERBOSE FORMAT JSON` because the framework reads
# `execution_time_ms` out of the ANALYZE output (a bare `TQL EVAL` returns rows
# only; see `query_regression_runner::measure`), and every entry sets
# `require_native = true` so the runner also states the
# `query.experimental_native_promql` hint and asserts the native route from the
# statement's JSON plan tree before it times the query. The assertion reads node
# names only (`FusedSeries`/`FusedSeriesExec`) and fails the run on any other
# plan; the text form cannot prove the route, because a plan line may begin with
# a label value. Warmup 3 / iterations 9 throughout.
#
# Two deviations from a literal reading of "binary + matching", both required to
# keep the query *valid* rather than to reach the native route (the route
# declines or admits these on its own):
# * `rate(m[5m]) / ignoring(instance) rate(m[5m])` matches on `host` alone, so
# each side contributes 6,250-6,251 series per group and the match is
# many-to-many. Prometheus rejects that, and so does GreptimeDB's vector
# match (`src/promql/src/vector_match.rs`: "many-to-one matching must be
# explicit (group_left/group_right)"). The identity-match form of the same
# 100,000-way shape is `... / on(host, instance) ...` (7a).
# * `sum by (host) (rate(m[5m])) / ignoring(instance) sum by (host) (...)`
# (7b) is the aggregated form: 16 series per side, matched one-to-one.
[case]
name = "many_short_series"
description = "100,000 short series (8 samples each) in 8 SSTs: wide-and-shallow PromQL shape coverage for the native fused-series route"
[scenario]
kind = "direct_readable_sst"
seed = 20480
[[scenario.tables]]
database = "public"
name = "many_short_series"
engine = "mito"
# Copy-on-write on purpose: `append_mode` stays unset, and mito's default is
# false. The native route declines an append-only region outright.
sst_format = "flat"
primary_key = ["host", "instance"]
time_index = "ts"
[[scenario.tables.columns]]
name = "host"
type = "STRING"
semantic = "tag"
distribution = { kind = "cardinality", values = 16, prefix = "host" }
[[scenario.tables.columns]]
name = "instance"
type = "STRING"
semantic = "tag"
distribution = { kind = "cardinality", values = 6_251, prefix = "instance" }
[[scenario.tables.columns]]
name = "value"
type = "DOUBLE"
semantic = "field"
distribution = { kind = "deterministic_wave", min = 0.0, max = 1000.0 }
# Milliseconds, not nanoseconds: the native route binds a raw-series source only
# for a `TIMESTAMP(3)` time index.
[[scenario.tables.columns]]
name = "ts"
type = "TIMESTAMP(3)"
semantic = "timestamp"
[scenario.layout]
regions = 1
sst_count = 8
rows_per_sst = 100_000
row_group_size = 8_192
series_count = 100_000
start_unix_nanos = 1_704_067_200_000_000_000 # 2024-01-01T00:00:00Z
step_nanos = 15_000_000_000
time_range_layout = "non_overlapping_per_sst"
series_layout = "timestamp_major"
# Evaluation grid: 00:00:45Z-00:01:45Z at a 15-second step, five evaluations.
# The plain shapes scan [1704066945, 1704067305] -- all eight files and all
# 100,000 series -- and their five evaluations read a growing prefix of that one
# scan. The shapes below that pin, offset or filter by host read fewer
# files/series by construction; each says so where it appears.
# 1. Bare selector: the control group.
[[scenario.queries]]
name = "selector_all_control"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') many_short_series"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 2. Rate over a window that holds every sample of every series.
[[scenario.queries]]
name = "rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 3. Whole-vector sum: the split shape (the per-series prefix plus a Partial
# aggregate in the first producer, SeriesRepartitionExec, then the Final
# aggregate in a second producer).
[[scenario.queries]]
name = "sum_rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') sum(rate(many_short_series[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 4. Grouped sum: 16 groups, state-routed like the whole-vector sum.
[[scenario.queries]]
name = "sum_by_host_rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') sum by (host) (rate(many_short_series[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 5. Grouped count: `count` carries no per-series state, so it is the split
# shape with the least per-series work.
[[scenario.queries]]
name = "count_by_host_rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') count by (host) (rate(many_short_series[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 6. topk over the whole vector: a global reduction over 100,000 series.
[[scenario.queries]]
name = "topk_5_rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') topk(5, rate(many_short_series[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 7a. Binary between two full vectors with an explicit identity match: every
# series matches itself, so this is the 100,000-way matching and repartition
# shape.
[[scenario.queries]]
name = "rate_ratio_on_host_instance"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m]) / on(host, instance) rate(many_short_series[5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 7b. The aggregated form of the same binary: 16 one-to-one matches, each side a
# split aggregate. `ignoring(instance)` is a no-op here because neither side
# carries `instance` any more; it spells out the requested matching explicitly.
[[scenario.queries]]
name = "sum_by_host_ratio_ignoring_instance"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') sum by (host) (rate(many_short_series[5m])) / ignoring(instance) sum by (host) (rate(many_short_series[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 8. Three range-function reductions: mean, extremum, and a quantile that needs
# the whole window rather than a running fold.
[[scenario.queries]]
name = "avg_over_time_1m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') avg_over_time(many_short_series[1m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
[[scenario.queries]]
name = "max_over_time_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') max_over_time(many_short_series[5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
[[scenario.queries]]
name = "quantile_over_time_09_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') quantile_over_time(0.9, many_short_series[5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 9. Label rewrite over the evaluated vector: 100,000 output label sets.
[[scenario.queries]]
name = "label_replace_dst_from_host"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') label_replace(rate(many_short_series[5m]), 'dst', '$1', 'host', '(.*)')"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 10. Comparison, as a filter and as `bool`: the filter drops samples, while the
# `bool` form keeps every series and writes 0 or 1.
[[scenario.queries]]
name = "rate_gt_05_filter"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m]) > 0.5"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
[[scenario.queries]]
name = "rate_gt_bool_05"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m]) > bool 0.5"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 11. Set operation: `and` keeps the left side's samples where the right side
# has a match, so it is the join-shaped vector operation without arithmetic.
[[scenario.queries]]
name = "rate_and_rate"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m]) and rate(many_short_series[5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 12. Subquery: a ten-minute window at a thirty-second step holds twenty aligned
# inner points per outer one (the window is left-open). A one-minute step would
# leave the first outer evaluation with a single raw sample in its `rate` window
# and the second folding one valid rate point, so the fold would barely be
# exercised; at thirty seconds both outer points fold two valid rate points.
# The outer grid is kept to two points -- forty inner evaluations -- instead of
# the five used elsewhere.
[[scenario.queries]]
name = "max_over_time_rate_10m_1m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '1m') max_over_time(rate(many_short_series[5m])[10m:30s])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 13. Window modifiers. `offset 1m` shifts the window back, so the early
# evaluations hold fewer samples than the late ones. `@ 1704067200` pins every
# evaluation to the first sample's instant: that five-minute window holds
# exactly one sample per series, so `rate` returns no series at all. The query
# still plans and scans the shifted window, which is what this control measures.
[[scenario.queries]]
name = "rate_5m_offset_1m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m] offset 1m)"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
[[scenario.queries]]
name = "rate_5m_at_1704067200_empty_control"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067245, 1704067305, '15s') rate(many_short_series[5m] @ 1704067200)"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
# 14. Instant query. `TQL` has no bare instant form (every statement takes the
# `(start, end, step[, lookback])` parameters, see
# `src/sql/src/parsers/tql_parser.rs`), so a single evaluation is the framework's
# equivalent: start == end, one step. `host1` holds 6,250 series.
[[scenario.queries]]
name = "instant_selector_host1"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704067305, 1704067305, '15s') many_short_series{host=\"host1\"}"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 20
@@ -2,6 +2,12 @@
# through the normal metric write path. This case is intentionally not part of the
# default query-regression set; run it explicitly when validating PromQL pipeline
# placement on realistic metric-engine data.
#
# It is also the only ingested case the native fused-series route can serve: the
# metric engine writes a millisecond time index and the table is copy-on-write.
# The queries below the three bare selectors cover the shapes that route splits
# or composes over ingested data (grouped aggregate, global topk, ignored-label
# binary match, subquery, offset selector, metric-name rewrite).
[case]
name = "prom_remote_write_7913"
@@ -59,3 +65,101 @@ iterations = 2
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
# ---------------------------------------------------------------------------
# Plan-shape coverage on top of the three bare selectors.
#
# This table is the one ingested case the native fused-series route can serve:
# the metric engine writes a millisecond time index and the table is not
# `append_mode`. The queries below therefore cover the shapes that route splits
# or composes over real ingested data: a grouped aggregate, a global topk, a
# binary match, a subquery, an offset selector, and a metric-name rewrite (which
# makes eight series share one name and so goes through the canonical
# merge/collect path).
#
# Every one is measured with `TQL ANALYZE VERBOSE FORMAT JSON` and declares
# `require_native = true`: the framework reads `execution_time_ms` from the
# ANALYZE output, the JSON form answers a plan tree rather than plan lines, and
# the runner asserts that tree names a `FusedSeries`/`FusedSeriesExec` node
# before it records a timing sample. The three bare selectors above stay plain
# `TQL ANALYZE VERBOSE` requests with no route requirement, so the runner sends
# them exactly what it sent before: flagging a query the route declines fails
# the run by design, so only a query meant to prove the route carries the flag.
#
# The six cover the two hours starting one hour after ingestion starts, so
# `offset 1h` still reads stored samples. The subquery query pairs a five-minute
# inner step with a coarser 15-minute outer step, which keeps the inner
# evaluation count bounded without changing the shape being measured.
#
# `... / ignoring(host) ...` is a valid one-to-one match here: `instance` is
# unique per series in this fixture, so ignoring `host` still leaves a distinct
# key per series.
# ---------------------------------------------------------------------------
[[scenario.queries]]
name = "sum_by_host_rate_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '5m') sum by (host) (rate(prom_remote_write_7913{host=~'host.*'}[5m]))"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
[[scenario.queries]]
name = "topk_10_selector"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '5m') topk(10, prom_remote_write_7913{host=~'host.*'})"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
[[scenario.queries]]
name = "selector_ratio_ignoring_host"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '5m') prom_remote_write_7913{host=~'host.*'} / ignoring(host) prom_remote_write_7913{host=~'host.*'}"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
[[scenario.queries]]
name = "max_over_time_rate_1h_5m"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '15m') max_over_time(rate(prom_remote_write_7913{host=~'host.*'}[5m])[1h:5m])"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
[[scenario.queries]]
name = "selector_offset_1h"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '5m') prom_remote_write_7913{host=~'host.*'} offset 1h"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
# Renaming the metric leaves 1024 distinct names over 8192 series, so eight
# series share each name: the canonical merge/collect path.
[[scenario.queries]]
name = "label_replace_metric_name"
kind = "tql"
query = "TQL ANALYZE VERBOSE FORMAT JSON (1704070800, 1704078000, '5m') label_replace(rate(prom_remote_write_7913{host=~'host.*'}[5m]), '__name__', 'rewritten_$1', 'host', '(.*)')"
require_native = true
warmup = 3
iterations = 9
[scenario.queries.thresholds]
max_candidate_latency_regression_pct = 100
@@ -58,6 +58,7 @@ class QueryRegressionCaseSelectionTest(unittest.TestCase):
"tests/perf/query_cases/prom_remote_write_7913/case.toml",
"tests/perf/query_cases/promql_constant_tag_concat_ms_10k/case.toml",
"tests/perf/query_cases/promql_constant_tag_concat_ms_100k/case.toml",
"tests/perf/query_cases/many_short_series/case.toml",
],
)