fix(promql): publish legacy columns for native TQL in CTEs and flows (#10666)

* fix(promql): keep the native name column out of TQL CTEs and flows

The native rows layout always appends a per-row `__name__` column. The
Prometheus HTTP response reads it, but two SQL-visible consumers took it
as part of the statement's columns:

- A hybrid CTE published it after the existing planner's columns, so
  `WITH t (ts, val) AS (TQL EVAL ... metric)` failed with a column count
  mismatch on the native route.
- A TQL flow matched it against the sink table and failed with "found 4
  flow output columns and 3 sink table columns".

A CTE now publishes exactly the existing planner's columns over the
native plan. A TQL flow plans its query with the native route off, like
CREATE VIEW does, because its output columns are the sink table's schema
and the native route also names value columns differently.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(flow): plan TQL flows on the native route with the existing columns

The previous commit kept a TQL flow's sink schema stable by forcing the
existing PromQL planner. Plan it like a TQL CTE instead: run natively and
publish the existing planner's columns over the native plan.

`LogicalPlanner::plan_relation` plans a statement whose columns are read
by SQL. The CTE path and `sql_to_df_plan` both use it.

The standalone test harness now starts the flow consistency check task,
which `ADMIN FLUSH_FLOW` syncs with, so the flow test can run the flow
and compare the sink table and rows with the existing route's.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(promql): pair per-series columns by role when a TQL CTE or flow runs natively

publish_legacy_schema paired the columns it could not match by name by
type alone, so a series with two string labels left both label columns
ambiguous and the statement fell back to the existing plan. Per-series
outputs such as rate(), topk(), offset binaries and label_replace() over
a table with more than one tag never ran natively in a CTE or a flow.

Pair the time index by its marker, labels by name, and the remaining
value columns in order, with the same casts as before.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test: start the flow check task only in the flow test

The standalone harness started the flow consistent-check task for every
instance. The task runs on the global runtime and holds the flow engine,
and nothing stopped it, so it outlived the instance and each rebuild
started another one. The harness now exposes the flow engine, and the
flow test that needs ADMIN FLUSH_FLOW starts the task and stops it.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* test(promql): check a two-field TQL CTE keeps each value column

The native route pairs value columns with the existing ones by position.
Two fields with different values make a swapped pair visible.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* style: format the two-field CTE test

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(flow): key a TQL sink table on every label of the answer

The sink table of a TQL flow took its primary key from the innermost
aggregate when the plan had one. In `m / scalar(sum(m))` that aggregate
groups by time alone, so the labels of `m` were created as DOUBLE fields,
written as NULL, and every series collapsed into one row per timestamp.
The native route has no such aggregate and keyed on the labels, so the
two routes created different sinks for the same flow.

Every string column of a PromQL answer is a label of its output series,
so the sink now keys on all of them on both routes.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix(flow): keep writing a TQL sink that has the native __name__ column

Before TQL flows were planned with `plan_relation`, a native TQL flow
auto-created its sink from the native plan's own columns: the value named
by that route, the labels, and `__name__` as a primary key column. The
relation plan publishes neither, so such a flow failed sink validation
and stopped writing.

When the sink has a `__name__` column, plan the statement with `plan`,
which is what these flows ran before. They keep writing the same columns
and the same `__name__` values: the metric name for a selector, NULL
where PromQL drops the name.

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
dennis zhuang
2026-11-27 12:13:15 +00:00
committed by GitHub
parent c2a66803ff
commit 15ca57ca20
6 changed files with 728 additions and 344 deletions
+4 -8
View File
@@ -49,14 +49,10 @@ pub(super) fn create_table_with_expr(
build_by_sql_schema(plan)?
}
}
QueryType::Tql => {
// first try build from aggr, then from tql schema because tql query might not have aggr node
if let Some(table_def) = build_pk_from_aggr(plan)? {
table_def
} else {
build_by_tql_schema(plan)?
}
}
// Every string column of a PromQL answer is a label of its output series. An aggregate
// inside the plan does not tell which: in `m / scalar(sum(m))` it groups by time alone
// while the answer keeps every label of `m`.
QueryType::Tql => build_by_tql_schema(plan)?,
};
let first_time_stamp = table_def.ts_col;
let primary_keys = table_def.pks;
+53 -15
View File
@@ -1021,6 +1021,56 @@ pub async fn sql_to_df_plan(
sql: &str,
optimize: bool,
) -> Result<LogicalPlan, Error> {
let query_stmt = parse_flow_query(&query_ctx, sql)?;
// The plan's columns are matched against the sink table, so a TQL query must publish the same
// columns whichever PromQL route plans it.
let plan = engine
.planner()
.plan_relation(&query_stmt, query_ctx.clone())
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
let plan = if optimize {
apply_df_optimizer(plan, &query_ctx).await?
} else {
plan
};
Ok(plan)
}
/// The column the native PromQL route publishes each row's metric name under.
const METRIC_NAME_COLUMN: &str = "__name__";
/// Plans `sql` unoptimized, to be written into a sink table with `sink_schema`.
///
/// Before TQL flows were planned with `plan_relation`, a flow on the native PromQL route
/// auto-created its sink from the native plan's own columns: the value named by that route, the
/// labels, and `__name__` as a primary key column. A sink with `__name__` is still written from the
/// statement's own plan, so such a flow keeps writing the same columns and the same series keys.
/// `plan_relation` and `plan` only differ for a PromQL statement on the native route.
async fn sql_to_df_plan_for_sink(
query_ctx: QueryContextRef,
engine: QueryEngineRef,
sql: &str,
sink_schema: &datatypes::schema::Schema,
) -> Result<LogicalPlan, Error> {
if sink_schema
.column_schema_by_name(METRIC_NAME_COLUMN)
.is_none()
{
return sql_to_df_plan(query_ctx, engine, sql, false).await;
}
let query_stmt = parse_flow_query(&query_ctx, sql)?;
engine
.planner()
.plan(&query_stmt, query_ctx)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)
}
fn parse_flow_query(query_ctx: &QueryContextRef, sql: &str) -> Result<QueryStatement, Error> {
let scheduled_time = query::options::parse_scheduled_time_datetime(&query_ctx.extensions())
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
@@ -1054,7 +1104,7 @@ pub async fn sql_to_df_plan(
alias: eval.alias.clone(),
};
QueryLanguageParser::parse_promql(&promql, &query_ctx)
QueryLanguageParser::parse_promql(&promql, query_ctx)
.map_err(BoxedError::new)
.context(ExternalSnafu)?
}
@@ -1065,19 +1115,7 @@ pub async fn sql_to_df_plan(
},
_ => QueryStatement::Sql(stmt.clone()),
};
let plan = engine
.planner()
.plan(&query_stmt, query_ctx.clone())
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
let plan = if optimize {
apply_df_optimizer(plan, &query_ctx).await?
} else {
plan
};
Ok(plan)
Ok(query_stmt)
}
/// Generate a plan that matches the schema of the sink table
@@ -1112,7 +1150,7 @@ pub(crate) async fn gen_plan_with_matching_schema_and_values(
allow_partial: bool,
values: &BTreeMap<String, ScalarValue>,
) -> Result<LogicalPlan, Error> {
let plan = sql_to_df_plan(query_ctx.clone(), engine.clone(), sql, false).await?;
let plan = sql_to_df_plan_for_sink(query_ctx, engine, sql, &sink_table_schema).await?;
let mut add_auto_column = ColumnMatcherRewriter::new_with_values(
sink_table_schema,
+214 -190
View File
@@ -70,6 +70,15 @@ use crate::{DfContextProviderAdapter, QueryEngineContext};
pub trait LogicalPlanner: Send + Sync {
async fn plan(&self, stmt: &QueryStatement, query_ctx: QueryContextRef) -> Result<LogicalPlan>;
/// Plans a statement whose output columns are read by SQL rather than returned to a client, such
/// as a flow's sink rows. A PromQL statement may still run on the native route, but publishes the
/// existing planner's columns on either route, as a TQL CTE does.
async fn plan_relation(
&self,
stmt: &QueryStatement,
query_ctx: QueryContextRef,
) -> Result<LogicalPlan>;
async fn plan_logs_query(
&self,
query: LogQuery,
@@ -281,25 +290,29 @@ fn unwrap_dictionary(data_type: &DataType) -> &DataType {
/// it. This wraps the native plan in the projection that publishes the existing planner's answer for
/// the same statement instead.
///
/// One column follows the answer rather than the existing planner: a native rows answer declares the
/// per-row metric name, which the existing planner never publishes, and that column is part of what
/// the statement answers. It is appended after the existing planner's columns, so those keep their
/// names, order, types and metadata, while a column list the CTE declares needs one more name - and a
/// statement whose answer declares no name column (a scalar-typed answer) publishes none here. A CTE
/// answered by the existing planner publishes exactly the columns it always has.
/// The per-row metric-name column a native rows answer declares is not published: the existing
/// planner never publishes one, so a column list the CTE declares (`tql (ts, val)`) and every
/// column the outer query reads stay the same on both routes. The name column serves the Prometheus
/// HTTP response, which reads the plan's own output rather than a CTE.
///
/// The projection is made of expressions - an alias per column, and a cast where the two routes carry
/// the same values in different Arrow types - because that is what survives analysis: the analyzer
/// rebuilds a projection's schema from its expressions, so anything the projection declared but its
/// expressions did not carry would be gone by the time the CTE's columns are read.
///
/// The mapping is the identity on every column both plans publish alike - the time index and the
/// label columns, which carry the same metadata on both routes now - and is a cast for a column
/// whose identity is unambiguous: one native column of the same type once both are unencoded, no
/// per-column metadata to lose and the same nullability. `None` says the two plans admit no such
/// mapping - a differently named time index, an ambiguous set of columns left over, or a column a
/// cast cannot reproduce faithfully - and the caller then keeps the existing plan rather than publish
/// a column it cannot fill faithfully.
/// Columns are paired by the role they play in a rows answer rather than by type alone, because a
/// series usually carries several labels of the same type:
/// - the time index is the one column each plan marks as such, and is renamed if the routes name it
/// differently;
/// - a label is the native column of the same name, cast where only the dictionary encoding
/// differs. Every native label has to be published, or the existing plan answers rows without a
/// label the native answer keeps;
/// - the value columns are what is left on each side, paired in order, of the same type.
///
/// `None` says the plans admit no such pairing - the value columns differ in number or in type, a
/// label of one plan is missing from the other, or the result does not publish exactly the existing
/// columns - and the caller then keeps the existing plan rather than publish a column it cannot fill
/// faithfully.
fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option<LogicalPlan> {
let native_schema = native.schema().clone();
let legacy_schema = legacy.schema();
@@ -314,77 +327,79 @@ fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option<Lo
return Some(native);
}
let is_time_index = |field: &arrow_schema::Field| {
field
.metadata()
.contains_key(datatypes::schema::TIME_INDEX_KEY)
};
let native_fields = native_schema
.iter()
.map(|(qualifier, field)| (qualifier.cloned(), field))
.collect::<Vec<_>>();
let mut taken = vec![false; native_fields.len()];
let mut source: Vec<Option<usize>> = vec![None; legacy_schema.fields().len()];
// First the columns both plans publish alike: the same name and the same column, metadata
// included. These are read as they are, so nothing about them is re-declared here.
let mut native_time = None;
let mut native_tags = Vec::new();
let mut native_values = Vec::new();
// The native rows layout publishes every label as `Utf8` and every value as a float or a
// histogram (`segment::fused_output_schema`), so the type alone tells the two apart.
for (index, (_, field)) in native_fields.iter().enumerate() {
if is_time_index(field) {
if native_time.replace(index).is_some() {
return None;
}
} else if datatypes::schema::is_metric_name_field(field) {
// The per-row name serves the Prometheus response; the existing planner publishes none.
} else if field.data_type() == &DataType::Utf8 {
native_tags.push(index);
} else {
native_values.push(index);
}
}
let native_time = native_time?;
let mut source = vec![None; legacy_schema.fields().len()];
let mut legacy_values = Vec::new();
let mut paired_tags = 0;
let mut legacy_time = false;
for (legacy_index, (_, legacy_field)) in legacy_schema.iter().enumerate() {
let found =
native_fields
.iter()
.enumerate()
.find_map(|(native_index, (_, native_field))| {
(!taken[native_index]
&& native_field.name() == legacy_field.name()
&& native_field.data_type() == legacy_field.data_type()
&& native_field.is_nullable() == legacy_field.is_nullable()
&& native_field.metadata() == legacy_field.metadata())
.then_some(native_index)
});
if let Some(native_index) = found {
taken[native_index] = true;
source[legacy_index] = Some(native_index);
}
}
// Then the columns whose only difference is that the routes carry them in different Arrow
// types. A cast reproduces the existing planner's type, so it is only paired when exactly one
// native column can be that column: the same type once both are unencoded, the same
// nullability, and no metadata a cast would drop.
for (legacy_index, source) in source.iter_mut().enumerate() {
if source.is_some() {
continue;
}
let legacy_field = legacy_schema.field(legacy_index);
if !legacy_field.metadata().is_empty() {
continue;
}
let candidates = native_fields
if is_time_index(legacy_field) {
if legacy_time {
return None;
}
legacy_time = true;
source[legacy_index] = Some(native_time);
} else if let Some(&native_index) = native_tags
.iter()
.enumerate()
.filter(|(native_index, (_, native_field))| {
!taken[*native_index]
&& unwrap_dictionary(native_field.data_type())
== unwrap_dictionary(legacy_field.data_type())
&& native_field.is_nullable() == legacy_field.is_nullable()
// A cast reproduces the field it rebuilds, and the native rows layout marks its
// metric-name column with metadata a cast would drop. Such a column is never a
// candidate for a legacy column: the name is the native answer's own and this
// boundary publishes the existing planner's columns.
&& native_field.metadata().is_empty()
})
.map(|(native_index, _)| native_index)
.collect::<Vec<_>>();
if let [native_index] = candidates.as_slice() {
taken[*native_index] = true;
*source = Some(*native_index);
.find(|&&index| native_fields[index].1.name() == legacy_field.name())
{
paired_tags += 1;
source[legacy_index] = Some(native_index);
} else {
legacy_values.push(legacy_index);
}
}
let source = source.into_iter().collect::<Option<Vec<usize>>>()?;
if !legacy_time
|| paired_tags != native_tags.len()
|| legacy_values.len() != native_values.len()
{
return None;
}
for (legacy_index, native_index) in legacy_values.into_iter().zip(native_values) {
source[legacy_index] = Some(native_index);
}
let mut exprs = Vec::with_capacity(source.len());
for ((_, legacy_field), native_index) in legacy_schema.iter().zip(source) {
let (native_qualifier, native_field) = &native_fields[native_index];
let (native_qualifier, native_field) = &native_fields[native_index?];
if unwrap_dictionary(native_field.data_type())
!= unwrap_dictionary(legacy_field.data_type())
{
return None;
}
let column = DfExpr::Column(datafusion_common::Column::new(
native_qualifier.clone(),
native_field.name().clone(),
));
// A column the two plans publish alike is read as it is; one they carry in different Arrow
// types is cast to the existing planner's type, which keeps the same values under the same
// name - and keeps them when the analyzer rebuilds this projection.
// A cast only adds or removes the dictionary encoding, so the values stay the same strings.
let value = if native_field.data_type() == legacy_field.data_type() {
column
} else {
@@ -395,54 +410,14 @@ fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option<Lo
};
exprs.push(value.alias(legacy_field.name().clone()));
}
// A native rows answer declares the per-row name column, and that is part of what the statement
// answers, so the CTE publishes it too - after the columns above, which keep their names and
// order. A statement whose answer has no such column (a scalar-typed answer, for one) publishes
// none here either: what the CTE exposes is the answer, not a schema chosen for it.
let name_source = native_fields
.iter()
.position(|(_, native_field)| datatypes::schema::is_metric_name_field(native_field));
if let Some(native_index) = name_source {
let (native_qualifier, native_field) = &native_fields[native_index];
exprs.push(
DfExpr::Column(datafusion_common::Column::new(
native_qualifier.clone(),
native_field.name().clone(),
))
.alias(native_field.name().clone()),
);
}
let plan = LogicalPlanBuilder::from(native)
.project(exprs)
.ok()?
.build()
.ok()?;
// The published columns are the ones this set out to publish, or the native plan is not used at
// all: what a CTE exposes may not change for a reason this did not predict. The legacy columns
// come first and in their order; the name column, when the answer declared one, is last.
let published = plan.schema();
let legacy_len = legacy_schema.fields().len();
let expected_len = legacy_len + usize::from(name_source.is_some());
(published.fields().len() == expected_len
&& published.metadata() == legacy_schema.metadata()
&& legacy_schema.iter().zip(published.iter()).all(
|((_, legacy_field), (_, published_field))| {
legacy_field.name() == published_field.name()
&& legacy_field.data_type() == published_field.data_type()
&& legacy_field.is_nullable() == published_field.is_nullable()
&& legacy_field.metadata() == published_field.metadata()
},
)
&& name_source.is_none_or(|native_index| {
let wanted = &native_schema.fields()[native_index];
let published = &published.fields()[legacy_len];
published.name() == wanted.name()
&& published.data_type() == wanted.data_type()
&& published.is_nullable() == wanted.is_nullable()
&& published.metadata() == wanted.metadata()
&& datatypes::schema::is_metric_name_field(published.as_ref())
}))
.then_some(plan)
// all: what a CTE exposes may not change for a reason this did not predict.
publishes_columns(plan.schema().as_ref(), legacy_schema.as_ref()).then_some(plan)
}
pub struct DfLogicalPlanner {
@@ -704,9 +679,9 @@ impl DfLogicalPlanner {
/// Plans a PromQL statement, offering it to the native fused-series route when the statement
/// may take it and the query options it is planned with ask for it.
///
/// `native_route_allowed` states whether the statement may take the route at all: a PromQL
/// statement embedded in a CTE may not (see [`Self::tql_to_logical_plan`]), every other one
/// may. Everything else the route depends on is read from the query options snapshot the
/// `native_route_allowed` states whether the statement may take the route at all: it is off
/// only when [`Self::plan_pql_relation`] plans the existing plan whose columns it publishes.
/// Everything else the route depends on is read from the query options snapshot the
/// statement is planned with, where every option is already resolved as request > session
/// `SET` > engine default.
#[tracing::instrument(skip_all)]
@@ -889,6 +864,27 @@ impl DfLogicalPlanner {
Ok(())
}
/// Plans a PromQL statement whose output is read by SQL: a hybrid CTE or a flow's sink rows.
async fn plan_pql_relation(
&self,
eval: &EvalStmt,
query_ctx: QueryContextRef,
) -> Result<LogicalPlan> {
let plan = self.plan_pql(eval, query_ctx.clone(), true).await?;
if !contains_native_fused(&plan) {
// The route was not taken - it is off for this query, or it declined this shape - so
// this is the existing plan, which already publishes the existing columns.
return Ok(plan);
}
// The relation's columns are SQL-visible, and this route names and orders its output its own
// way, so its own schema cannot stand in for the existing planner's: plan the statement for
// that schema and publish it over the native answer. A statement whose columns that
// projection cannot fill faithfully keeps the existing plan instead of changing the schema
// the relation exposes.
let existing = self.plan_pql(eval, query_ctx, false).await?;
Ok(publish_legacy_schema(plan, &existing).unwrap_or(existing))
}
/// Convert TQL to LogicalPlan directly
async fn tql_to_logical_plan(
&self,
@@ -921,20 +917,7 @@ impl DfLogicalPlanner {
let QueryStatement::Promql(eval, _alias) = &stmt else {
unreachable!("a TQL eval parses to a PromQL statement");
};
let plan = self.plan_pql(eval, query_ctx.clone(), true).await?;
if !contains_native_fused(&plan) {
// The route was not taken - it is off for this query, or it declined this
// shape - so this is the existing plan, which already publishes what a CTE has
// always published.
return Ok(plan);
}
// What the CTE publishes is SQL-visible, and this route names and orders its output
// its own way, so its own schema cannot stand in for the existing planner's: plan
// the statement for that schema and publish it over the native answer. A statement
// whose columns that projection cannot fill faithfully keeps the existing plan
// instead of changing the schema the CTE exposes.
let existing = self.plan_pql(eval, query_ctx, false).await?;
Ok(publish_legacy_schema(plan, &existing).unwrap_or(existing))
self.plan_pql_relation(eval, query_ctx).await
}
Tql::Explain(_) => UnimplementedSnafu {
operation: "TQL EXPLAIN in CTEs",
@@ -1176,6 +1159,17 @@ impl LogicalPlanner for DfLogicalPlanner {
}
}
async fn plan_relation(
&self,
stmt: &QueryStatement,
query_ctx: QueryContextRef,
) -> Result<LogicalPlan> {
match stmt {
QueryStatement::Sql(stmt) => self.plan_sql(stmt, query_ctx).await,
QueryStatement::Promql(stmt, _alias) => self.plan_pql_relation(stmt, query_ctx).await,
}
}
async fn plan_logs_query(
&self,
query: LogQuery,
@@ -2592,16 +2586,12 @@ mod tests {
);
}
/// A native answer that declares the per-row name column publishes it after the existing
/// planner's columns.
/// A native answer's per-row name column is not published by the CTE.
///
/// The name column is text like a label, so pairing by type alone would leave `host` with two
/// candidates and no answer at all; the metadata it carries is what tells the two apart, and
/// what keeps it from standing in for a label. The CTE publishes the existing planner's columns
/// first and in its order, then the name the answer carries: the column is part of what the
/// statement answers.
/// The existing planner publishes no such column, and a column list the CTE declares names
/// exactly the existing planner's columns, so `tql (ts, val)` over one metric must still see two.
#[test]
fn a_cte_publishes_the_name_an_answer_carries_after_the_existing_columns() {
fn a_cte_does_not_publish_the_native_name_column() {
let native = plan_publishing_marked(
&[
("ts", time_value()),
@@ -2617,21 +2607,11 @@ mod tests {
let existing = existing_answer();
let published = publish_legacy_schema(native, &existing)
.expect("the declared name column does not compete with a label");
.expect("the name column does not compete with a label");
assert_eq!(
column_names(&published),
vec!["host", "ts", "lhs.val + rhs.val", "__name__"],
"the CTE publishes the existing planner's columns, then the name the answer carries"
);
assert!(
datatypes::schema::is_metric_name_field(
published
.schema()
.field_with_name(None, "__name__")
.unwrap()
),
"the name column is marked as one: {}",
publishes_columns(published.schema().as_ref(), existing.schema().as_ref()),
"the CTE publishes exactly the existing planner's columns: {}",
published.schema()
);
}
@@ -2668,44 +2648,6 @@ mod tests {
);
}
/// The declared name column survives the analyzer rebuilding the projection as well.
#[test]
fn the_declared_name_column_survives_the_analyzer_rebuilding_the_projection() {
let existing = existing_answer();
let native = plan_publishing_marked(
&[
("ts", time_value()),
("val", ScalarValue::Float64(Some(2.0))),
("host", ScalarValue::Utf8(Some("a".to_string()))),
(
"__name__",
ScalarValue::Utf8(Some("cte_native".to_string())),
),
],
"ts",
);
let published = publish_legacy_schema(native, &existing)
.expect("the name column does not compete with a label");
// The rebuild `DistPlannerAnalyzer` performs on every projection it visits.
let rebuilt = published
.with_new_exprs(
published.expressions(),
published.inputs().into_iter().cloned().collect(),
)
.expect("the analyzer rebuilds a projection from its expressions");
let field = rebuilt
.schema()
.field_with_name(None, "__name__")
.expect("the name column is still published");
assert!(
datatypes::schema::is_metric_name_field(field),
"and is still marked as one: {}",
rebuilt.schema()
);
}
/// A statement whose columns do not pair keeps the existing plan.
///
/// Publishing a column this cannot fill would change what the CTE means, so a shape it cannot
@@ -2725,8 +2667,86 @@ mod tests {
);
assert!(publish_legacy_schema(native_answer(), &two_values).is_none());
// A time index the other route had to rename is marked as the time index on both sides, and
// a column that carries metadata is never reproduced by a cast.
// A label the native answer keeps and the existing answer does not publish has nothing to
// be published under.
let extra_label = plan_publishing_marked(
&[
("ts", time_value()),
("val", ScalarValue::Float64(Some(2.0))),
("host", ScalarValue::Utf8(Some("a".to_string()))),
("dc", ScalarValue::Utf8(Some("x".to_string()))),
],
"ts",
);
assert!(publish_legacy_schema(extra_label, &existing_answer()).is_none());
// A value the existing planner publishes as an integer is not the native float column.
let integer_value = plan_publishing_marked(
&[
("host", dictionary_label("a")),
("ts", time_value()),
("val", ScalarValue::Int64(Some(2))),
],
"ts",
);
assert!(publish_legacy_schema(native_answer(), &integer_value).is_none());
}
/// Labels are paired by name, so a series with several labels of the same type still pairs, and
/// each label keeps its own values.
#[test]
fn labels_of_one_type_are_paired_by_name() {
let native = plan_publishing_marked(
&[
("ts", time_value()),
("rate(pf[2m])", ScalarValue::Float64(Some(2.0))),
("loc", ScalarValue::Utf8(Some("A".to_string()))),
("sensor", ScalarValue::Utf8(Some("s1".to_string()))),
("__name__", ScalarValue::Utf8(Some("pf".to_string()))),
],
"ts",
);
let existing = plan_publishing_marked(
&[
("sensor", dictionary_label("s1")),
("ts", time_value()),
(
"prom_rate(ts_range,value,ts,Int64(120000))",
ScalarValue::Float64(Some(2.0)),
),
("loc", dictionary_label("A")),
],
"ts",
);
let published = publish_legacy_schema(native, &existing)
.expect("each label has one native column of its name");
assert!(
publishes_columns(published.schema().as_ref(), existing.schema().as_ref()),
"{}",
published.schema()
);
let LogicalPlan::Projection(projection) = &published else {
panic!("the native plan is wrapped in a projection: {published}");
};
let sources = projection
.expr
.iter()
.map(|expr| {
let mut columns = expr.column_refs().into_iter();
let column = columns.next().unwrap().name.clone();
assert!(columns.next().is_none());
column
})
.collect::<Vec<_>>();
assert_eq!(sources, vec!["sensor", "ts", "rate(pf[2m])", "loc"]);
}
/// The time index is paired by its marker, so a native answer that had to name its grid
/// differently publishes it under the existing planner's name.
#[test]
fn the_time_index_is_paired_by_its_marker() {
let renamed_time = plan_publishing_marked(
&[
("native_time_0", time_value()),
@@ -2743,7 +2763,11 @@ mod tests {
],
"ts",
);
assert!(publish_legacy_schema(renamed_time, &existing).is_none());
let published = publish_legacy_schema(renamed_time, &existing).unwrap();
assert!(publishes_columns(
published.schema().as_ref(),
existing.schema().as_ref()
));
}
#[tokio::test]
+6 -1
View File
@@ -46,7 +46,7 @@ use common_telemetry::logging::SlowQueryOptions;
use common_test_util::find_workspace_path;
use common_wal::config::DatanodeWalConfig;
use datanode::datanode::{Datanode, DatanodeBuilder};
use flow::{FlownodeBuilder, FrontendClient, GrpcQueryHandlerWithBoxedError};
use flow::{FlowDualEngineRef, FlownodeBuilder, FrontendClient, GrpcQueryHandlerWithBoxedError};
use frontend::frontend::Frontend;
use frontend::instance::Instance;
use frontend::instance::builder::FrontendBuilder;
@@ -74,6 +74,10 @@ pub struct GreptimeDbStandalone {
pub kv_backend: KvBackendRef,
pub procedure_manager: ProcedureManagerRef,
pub event_recorder_handle: EventRecorderHandle,
/// Its consistency-check task is not started: once started it holds the engine on the global
/// runtime until stopped, past this instance and any rebuild. A test that needs
/// `ADMIN FLUSH_FLOW` starts the task and stops it before returning.
pub flow_engine: FlowDualEngineRef,
}
impl GreptimeDbStandalone {
@@ -406,6 +410,7 @@ impl GreptimeDbStandaloneBuilder {
kv_backend,
procedure_manager,
event_recorder_handle,
flow_engine: flownode.flow_engine(),
}
}
+449 -130
View File
@@ -2664,6 +2664,326 @@ fn assert_one_field_native_layout(batches: &common_recordbatch::RecordBatches, q
);
}
/// A TQL flow runs on the native route and writes the same sink table and rows as the existing
/// route.
///
/// The flow creates its sink table from the columns its plan publishes, so a plan that published
/// the native root's columns would create a different table (with a metric-name column) than the
/// same flow planned by the existing route. The aggregates are shapes the native planner places
/// differently: one selector, and two occurrences of a selector. The rest keep one row per series
/// with two labels each, so the published labels are paired with the native ones by name. In
/// `m / scalar(sum(m))` the existing plan's only aggregate groups by time alone, yet both labels of
/// `m` stay sink keys.
#[test]
fn native_promql_tql_flow_matches_the_sink_table() {
// Flushing a flow overflows the default test stack in a debug build.
std::thread::Builder::new()
.stack_size(32 * 1024 * 1024)
.spawn(|| {
tokio::runtime::Builder::new_multi_thread()
.thread_stack_size(32 * 1024 * 1024)
.enable_all()
.build()
.unwrap()
.block_on(native_promql_tql_flow_matches_the_sink_table_impl())
})
.unwrap()
.join()
.unwrap();
}
async fn native_promql_tql_flow_matches_the_sink_table_impl() {
common_telemetry::init_default_ut_logging();
let (standalone, observer) =
native_test_instance(GreptimeDbStandaloneBuilder::new("native_promql_tql_flow")).await;
// `ADMIN FLUSH_FLOW` syncs with this task.
standalone
.flow_engine
.start_flow_consistent_check_task()
.await
.unwrap();
let instance = standalone.fe_instance().clone();
execute_all(
&instance,
"CREATE TABLE native_flow_src (`value` DOUBLE, ts TIMESTAMP TIME INDEX, \
sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)); \
INSERT INTO native_flow_src VALUES \
(20, now() - '30s'::interval, 's1', 'A'), \
(30, now() - '30s'::interval, 's1', 'B'), \
(10, now() - '30s'::interval, 's2', 'A'); \
CREATE TABLE native_flow_part (`value` DOUBLE, ts TIMESTAMP TIME INDEX, \
sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)) \
PARTITION ON COLUMNS (loc) (loc < 'B', loc >= 'B'); \
INSERT INTO native_flow_part SELECT * FROM native_flow_src; \
CREATE TABLE native_flow_series (`value` DOUBLE, ts TIMESTAMP TIME INDEX, \
sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)); \
INSERT INTO native_flow_series VALUES \
(20, now() - '90s'::interval, 's1', 'A'), (25, now() - '30s'::interval, 's1', 'A'), \
(30, now() - '90s'::interval, 's1', 'B'), (40, now() - '30s'::interval, 's1', 'B'), \
(10, now() - '90s'::interval, 's2', 'A'), (10, now() - '30s'::interval, 's2', 'A')",
QueryContext::arc(),
)
.await;
let sql_output = |sql: String| {
let instance = instance.clone();
async move {
let output = instance
.do_query(&sql, QueryContext::arc())
.await
.remove(0)
.unwrap();
native_output_text(output).await
}
};
// Each flush evaluates at its own `now()`, so the rows are compared without the time index.
let rows_without_ts = |table: String| {
let instance = instance.clone();
async move {
let output = instance
.do_query(&format!("SELECT * FROM {table}"), QueryContext::arc())
.await
.remove(0)
.unwrap();
let batches = match output.data {
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
OutputData::RecordBatches(batches) => batches,
_ => unreachable!("a query returns record batches"),
};
let batches = batches
.iter()
.map(|batch| {
let batch = batch.df_record_batch();
let ts = batch.schema().index_of("ts").unwrap();
let keep = (0..batch.num_columns())
.filter(|index| *index != ts)
.collect::<Vec<_>>();
batch.project(&keep).unwrap()
})
.collect::<Vec<_>>();
// Rows are compared as a set: a sink table returns them in no fixed order.
let mut lines = datatypes::arrow::util::pretty::pretty_format_batches(&batches)
.unwrap()
.to_string()
.lines()
.map(str::to_string)
.collect::<Vec<_>>();
lines.sort();
lines.join("\n")
}
};
for (name, query) in [
("avg", "avg by (sensor) (native_flow_src)"),
(
"ratio",
"sum by (sensor) (native_flow_src) / count by (sensor) (native_flow_src)",
),
("partitioned", "avg by (sensor) (native_flow_part)"),
("rate", "rate(native_flow_series[2m])"),
("topk", "topk(1, native_flow_series)"),
(
"offset",
"native_flow_series + native_flow_series offset 1m",
),
(
"label_replace",
"label_replace(native_flow_series, \"dst\", \"$1\", \"sensor\", \"(.*)\")",
),
(
"scalar_ratio",
"native_flow_src / scalar(sum(native_flow_src))",
),
] {
let mut sinks = Vec::new();
for native in [false, true] {
let flow = format!("native_flow_{name}_{native}");
execute_all(
&instance,
&format!(
"CREATE FLOW {flow} SINK TO {flow}_sink EVAL INTERVAL '1m' AS \
TQL EVAL (now() - '1m'::interval, now(), '1m') {query}"
),
native_query_context(native, 4),
)
.await;
observer.clear();
execute_all(
&instance,
&format!("ADMIN FLUSH_FLOW('{flow}')"),
QueryContext::arc(),
)
.await;
assert_eq!(
native,
!cte_native_observed_fused(&observer).is_empty(),
"{flow} runs the fused plan exactly when the route is requested:\n{}",
cte_native_observed_plan_trees(&observer)
);
sinks.push((
sql_output(format!("DESC TABLE {flow}_sink")).await,
rows_without_ts(format!("{flow}_sink")).await,
));
}
let rows = &sinks[0].1;
assert!(rows.contains("| s1 "), "{name}: {rows}");
if ["avg", "ratio", "partitioned"].contains(&name) {
assert!(rows.contains("| 10.0 "), "{name}: {rows}");
}
assert_eq!(sinks[0], sinks[1], "{name}");
}
standalone
.flow_engine
.stop_flow_consistent_check_task()
.await
.unwrap();
}
/// A native TQL flow keeps writing a sink an earlier build auto-created from the native plan's own
/// columns: the time index, the value named by the native route, the labels and `__name__`.
///
/// `__name__` is part of the primary key there, so the flow has to write what it wrote before: the
/// metric name for a selector, and null where PromQL drops the name, as `rate` and an aggregate do.
#[test]
fn native_promql_tql_flow_keeps_writing_a_sink_with_the_name_column() {
// Flushing a flow overflows the default test stack in a debug build.
std::thread::Builder::new()
.stack_size(32 * 1024 * 1024)
.spawn(|| {
tokio::runtime::Builder::new_multi_thread()
.thread_stack_size(32 * 1024 * 1024)
.enable_all()
.build()
.unwrap()
.block_on(native_promql_tql_flow_keeps_writing_a_sink_with_the_name_column_impl())
})
.unwrap()
.join()
.unwrap();
}
async fn native_promql_tql_flow_keeps_writing_a_sink_with_the_name_column_impl() {
common_telemetry::init_default_ut_logging();
let (standalone, _observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
"native_promql_tql_flow_name",
))
.await;
// `ADMIN FLUSH_FLOW` syncs with this task.
standalone
.flow_engine
.start_flow_consistent_check_task()
.await
.unwrap();
let instance = standalone.fe_instance().clone();
execute_all(
&instance,
"CREATE TABLE old_flow_src (`value` DOUBLE, ts TIMESTAMP TIME INDEX, \
sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)); \
INSERT INTO old_flow_src VALUES \
(20, now() - '90s'::interval, 's1', 'A'), (25, now() - '30s'::interval, 's1', 'A'), \
(10, now() - '90s'::interval, 's2', 'A'), (10, now() - '30s'::interval, 's2', 'A')",
QueryContext::arc(),
)
.await;
// The sink tables are the ones the native route auto-created before TQL flows were planned
// with the existing planner's columns.
for (name, query, labels, expected) in [
(
"selector",
"old_flow_src",
["sensor", "loc"].as_slice(),
"+--------------+--------+-----+--------------+\n\
| old_flow_src | sensor | loc | __name__ |\n\
+--------------+--------+-----+--------------+\n\
| 20.0 | s1 | A | old_flow_src |\n\
| 25.0 | s1 | A | old_flow_src |\n\
| 10.0 | s2 | A | old_flow_src |\n\
| 10.0 | s2 | A | old_flow_src |\n\
+--------------+--------+-----+--------------+",
),
(
"rate",
"rate(old_flow_src[2m])",
["sensor", "loc"].as_slice(),
"+------------------------+--------+-----+----------+\n\
| rate(old_flow_src[2m]) | sensor | loc | __name__ |\n\
+------------------------+--------+-----+----------+\n\
| 0.08333333333333333 | s1 | A | NULL |\n\
| 0.0 | s2 | A | NULL |\n\
+------------------------+--------+-----+----------+",
),
(
"sum",
"sum by (sensor) (old_flow_src)",
["sensor"].as_slice(),
"+--------------------------------+--------+----------+\n\
| sum by (sensor) (old_flow_src) | sensor | __name__ |\n\
+--------------------------------+--------+----------+\n\
| 20.0 | s1 | NULL |\n\
| 25.0 | s1 | NULL |\n\
| 10.0 | s2 | NULL |\n\
| 10.0 | s2 | NULL |\n\
+--------------------------------+--------+----------+",
),
] {
let flow = format!("old_native_flow_{name}");
let label_columns = labels
.iter()
.map(|label| format!("\"{label}\" STRING NULL, "))
.collect::<String>();
let keys = labels
.iter()
.chain(&["__name__"])
.map(|label| format!("\"{label}\""))
.collect::<Vec<_>>()
.join(", ");
execute_all(
&instance,
&format!(
"CREATE TABLE {flow}_sink (\"ts\" TIMESTAMP(3) NOT NULL, \"{query}\" DOUBLE NULL, \
{label_columns}\"__name__\" STRING NULL, TIME INDEX (\"ts\"), \
PRIMARY KEY ({keys}))"
),
QueryContext::arc(),
)
.await;
execute_all(
&instance,
&format!(
"CREATE FLOW {flow} SINK TO {flow}_sink EVAL INTERVAL '1m' AS \
TQL EVAL (now() - '1m'::interval, now(), '1m') {query}"
),
native_query_context(true, 4),
)
.await;
execute_all(
&instance,
&format!("ADMIN FLUSH_FLOW('{flow}')"),
QueryContext::arc(),
)
.await;
let columns = labels.join(", ");
let output = instance
.do_query(
&format!(
"SELECT \"{query}\", {columns}, coalesce(__name__, 'NULL') AS __name__ \
FROM {flow}_sink \
ORDER BY {columns}, ts"
),
QueryContext::arc(),
)
.await
.remove(0)
.unwrap();
assert_eq!(expected, native_output_text(output).await, "{name}");
}
standalone
.flow_engine
.stop_flow_consistent_check_task()
.await
.unwrap();
}
/// A `__field__` selection that matches no metric table answers the empty vector.
///
/// The matcher decides which of a scan's field columns a selection keeps, and no table matched this
@@ -11636,13 +11956,7 @@ const CTE_NATIVE_ORDERED_STATEMENT: &str =
const CTE_NATIVE_ALIASED_STATEMENT: &str = "WITH tql (site, t, v) AS (TQL EVAL (0, 3, '1s') cte_native + cte_native) \
SELECT t, v, site FROM tql WHERE v > 5 ORDER BY t";
/// The same statement for the native route, which publishes the name column as a fourth column and
/// therefore needs a fourth name in the list. The outer projection still reads the same three.
const CTE_NATIVE_ALIASED_NAME_STATEMENT: &str = "WITH tql (site, t, v, metric) AS (TQL EVAL (0, 3, '1s') cte_native + cte_native) \
SELECT t, v, site FROM tql WHERE v > 5 ORDER BY t";
/// A CTE over a plain selection: the answer keeps the metric name, so the native route publishes it
/// and the existing route does not.
/// A CTE over a plain selection, whose native answer carries the metric name of every row.
const CTE_NATIVE_NAME_STATEMENT: &str =
"WITH tql AS (TQL EVAL (0, 0, '1s') cte_native) SELECT * FROM tql";
@@ -11726,29 +12040,6 @@ fn cte_native_published_schema_expected() -> ArrowSchema {
)
}
/// The metadata the declared name column carries.
fn cte_native_name_metadata() -> std::collections::HashMap<String, String> {
std::collections::HashMap::from([("greptime:metric_name".to_string(), "true".to_string())])
}
/// The schema [`CTE_NATIVE_STATEMENT`] publishes on the native route: the existing planner's
/// columns, then the per-row name the answer declares.
///
/// The name is part of what the statement answers, so a CTE over a native answer publishes it. The
/// existing planner never publishes it, so the same statement answered by that route has one column
/// fewer: a CTE's columns follow the answer it was planned from.
fn cte_native_published_schema_expected_native() -> ArrowSchema {
let mut fields = cte_native_published_schema_expected()
.fields()
.iter()
.map(|field| field.as_ref().clone())
.collect::<Vec<_>>();
fields.push(
Field::new("__name__", DataType::Utf8, true).with_metadata(cte_native_name_metadata()),
);
ArrowSchema::new_with_metadata(fields, cte_native_schema_metadata())
}
/// The schema [`CTE_NATIVE_ALIASED_STATEMENT`] publishes: the names its CTE declares, in the order it
/// declares them, over the columns of [`CTE_NATIVE_STATEMENT`].
fn cte_native_aliased_schema_expected() -> ArrowSchema {
@@ -11976,23 +12267,8 @@ async fn cte_native_statement_runs_the_fused_plan() {
"the region reads one raw source per occurrence of the repeated selector:\n{trees}"
);
assert_eq!(
native_schema,
cte_native_published_schema_expected_native(),
"the CTE publishes the existing planner's columns, then the name the answer declares"
);
let legacy_fields = legacy_schema
.fields()
.iter()
.map(|field| field.as_ref())
.collect::<Vec<_>>();
let native_prefix = native_schema.fields()[..legacy_fields.len()]
.iter()
.map(|field| field.as_ref())
.collect::<Vec<_>>();
assert_eq!(
native_prefix, legacy_fields,
"and every column the existing route publishes keeps its name, type, nullability and \
metadata: only the name column is added"
native_schema, legacy_schema,
"the CTE publishes the existing planner's columns, and no name column"
);
let native_types = cte_native_arrow_types(
native_tql_output(&instance, CTE_NATIVE_ARROW_TYPE_STATEMENT, true).await,
@@ -12029,10 +12305,9 @@ async fn cte_native_statement_runs_the_fused_plan() {
/// node still answers the statement, and the columns and rows are the ones the existing plan
/// answers with.
///
/// The declared list is positional and exact, so the native answer needs one more name than the
/// existing one: it publishes the per-row name column, and the existing route does not. What the
/// list declares, what the outer projection reads and what the outer filter keeps are all above the
/// node, and none of them moves it.
/// The declared list is positional and exact, so the same three names apply on both routes. What
/// the list declares, what the outer projection reads and what the outer filter keeps are all above
/// the node, and none of them moves it.
#[tokio::test(flavor = "multi_thread")]
async fn cte_native_column_aliases_and_outer_filter_keep_the_fused_plan() {
common_telemetry::init_default_ut_logging();
@@ -12058,29 +12333,7 @@ async fn cte_native_column_aliases_and_outer_filter_keep_the_fused_plan() {
assert_eq!(legacy_rows, cte_native_filtered_rows(), "legacy");
observer.clear();
// The native answer publishes one more column, so the declared list names four. Three names for
// four columns is a hard error, and four names for the existing route's three is one too: the
// list is positional and exact.
let short = instance
.do_query(CTE_NATIVE_ALIASED_STATEMENT, native_query_context(true, 4))
.await
.remove(0);
assert!(
short.is_err(),
"three names for the native answer's four columns"
);
let long = instance
.do_query(
CTE_NATIVE_ALIASED_NAME_STATEMENT,
native_query_context(false, 4),
)
.await
.remove(0);
assert!(
long.is_err(),
"four names for the existing answer's three columns"
);
let native_output = native_tql_output(&instance, CTE_NATIVE_ALIASED_NAME_STATEMENT, true).await;
let native_output = native_tql_output(&instance, CTE_NATIVE_ALIASED_STATEMENT, true).await;
let native_schema = cte_native_published_schema(&native_output);
let native_rows = cte_native_rows(native_output).await;
assert_eq!(
@@ -12107,60 +12360,54 @@ async fn cte_native_column_aliases_and_outer_filter_keep_the_fused_plan() {
assert_eq!(native_rows, legacy_rows);
}
/// The CTE publishes the name column exactly when the answer declares one.
/// The CTE publishes no metric-name column on either route.
///
/// A plain selection keeps its series name, and the native answer declares the column for it, so the
/// CTE publishes it and SQL can read it. The existing answer declares none, so the same statement
/// answered by that route publishes one column fewer and asking for the name is an error - the CTE's
/// columns follow the answer it was planned from. A scalar-typed answer declares no such column on
/// either route, so neither publishes one: the CTE does not invent a column the statement does not
/// answer.
/// A plain selection keeps its series name, and the native answer declares a per-row name column
/// for it, but the existing answer declares none, so the CTE publishes the existing columns only:
/// a column list or outer query written against one route applies to the other. A scalar-typed
/// answer declares no name column on either route.
#[tokio::test(flavor = "multi_thread")]
async fn cte_native_publishes_the_name_column_only_when_the_answer_declares_one() {
async fn cte_native_publishes_no_name_column() {
common_telemetry::init_default_ut_logging();
let (standalone, observer) =
native_test_instance(GreptimeDbStandaloneBuilder::new("cte_native_name")).await;
let instance = standalone.fe_instance().clone();
execute_all(&instance, CTE_NATIVE_FIXTURE, QueryContext::arc()).await;
let legacy = native_tql_output(&instance, CTE_NATIVE_NAME_STATEMENT, false).await;
let legacy_schema = cte_native_published_schema(&legacy);
let legacy_rows = cte_native_rows(legacy).await;
observer.clear();
let native = native_tql_output(&instance, CTE_NATIVE_NAME_STATEMENT, true).await;
let native_schema = cte_native_published_schema(&native);
let name = native_schema
.field_with_name("__name__")
.expect("the native answer declares the name column");
assert!(
datatypes::schema::is_metric_name_field(name),
"and marks it as one: {native_schema:?}"
let native_rows = cte_native_rows(native).await;
assert_eq!(
1,
cte_native_observed_fused(&observer).len(),
"the selection runs one fused node:\n{}",
cte_native_observed_plan_trees(&observer)
);
let rows = cte_native_rows(native).await;
assert!(!rows.is_empty(), "the statement answers rows");
assert!(
rows.iter()
.all(|(_, labels, _)| labels.get("__name__").map(String::as_str) == Some("cte_native")),
"every row names the metric it was read from: {rows:?}"
);
let legacy = native_tql_output(&instance, CTE_NATIVE_NAME_STATEMENT, false).await;
let legacy_schema = cte_native_published_schema(&legacy);
assert!(
legacy_schema.field_with_name("__name__").is_err(),
"the existing answer declares no name column: {legacy_schema:?}"
);
cte_native_rows(legacy).await;
let missing = instance
.do_query(
"WITH tql AS (TQL EVAL (0, 0, '1s') cte_native) SELECT __name__ FROM tql",
native_query_context(false, 4),
)
.await
.remove(0);
assert!(
missing.is_err(),
"a CTE answered by the existing route has no name column to read"
native_schema.field_with_name("__name__").is_err(),
"the CTE publishes no name column: {native_schema:?}"
);
assert_eq!(native_schema, legacy_schema);
assert!(!native_rows.is_empty(), "the statement answers rows");
assert_eq!(native_rows, legacy_rows);
for enabled in [true, false] {
let missing = instance
.do_query(
"WITH tql AS (TQL EVAL (0, 0, '1s') cte_native) SELECT __name__ FROM tql",
native_query_context(enabled, 4),
)
.await
.remove(0);
assert!(
missing.is_err(),
"the CTE has no name column to read (native={enabled})"
);
let scalar = native_tql_output(&instance, CTE_NATIVE_SCALAR_STATEMENT, enabled).await;
let schema = cte_native_published_schema(&scalar);
assert!(
@@ -12170,6 +12417,93 @@ async fn cte_native_publishes_the_name_column_only_when_the_answer_declares_one(
}
}
/// A CTE over a per-series answer runs the fused plan and publishes the existing planner's columns
/// and rows.
///
/// Each statement keeps one row per input series, and every series carries two labels of the same
/// type, so the published labels have to be paired with the native ones by name. The statements
/// cover a range function, a selection that keeps input rows, a binary operation with an offset
/// operand and a label rewrite.
#[tokio::test(flavor = "multi_thread")]
async fn cte_native_per_series_statements_run_the_fused_plan() {
common_telemetry::init_default_ut_logging();
let (standalone, observer) =
native_test_instance(GreptimeDbStandaloneBuilder::new("cte_native_per_series")).await;
let instance = standalone.fe_instance().clone();
execute_all(
&instance,
"CREATE TABLE cte_series (`value` DOUBLE, ts TIMESTAMP TIME INDEX, \
sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)); \
INSERT INTO cte_series VALUES \
(1, 0, 's1', 'A'), (3, 1000, 's1', 'A'), (6, 2000, 's1', 'A'), (10, 3000, 's1', 'A'), \
(2, 0, 's1', 'B'), (4, 1000, 's1', 'B'), (8, 2000, 's1', 'B'), (16, 3000, 's1', 'B'), \
(5, 0, 's2', 'A'), (5, 1000, 's2', 'A'), (7, 2000, 's2', 'A'), (7, 3000, 's2', 'A')",
QueryContext::arc(),
)
.await;
let sorted_rows = |output| async move {
let mut rows = cte_native_rows(output).await;
rows.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
rows
};
for query in [
"rate(cte_series[2s])",
"topk(1, cte_series)",
"cte_series + cte_series offset 1s",
"label_replace(cte_series, \"dst\", \"$1\", \"sensor\", \"(.*)\")",
] {
let statement = format!("WITH tql AS (TQL EVAL (0, 3, '1s') {query}) SELECT * FROM tql");
let legacy = native_tql_output(&instance, &statement, false).await;
let legacy_schema = cte_native_published_schema(&legacy);
let legacy_rows = sorted_rows(legacy).await;
observer.clear();
let native = native_tql_output(&instance, &statement, true).await;
let native_schema = cte_native_published_schema(&native);
let native_rows = sorted_rows(native).await;
assert!(
!cte_native_observed_fused(&observer).is_empty(),
"{query} runs the fused plan:\n{}",
cte_native_observed_plan_trees(&observer)
);
assert_eq!(native_schema, legacy_schema, "{query}");
assert!(!legacy_rows.is_empty(), "{query} answers rows");
assert_eq!(native_rows, legacy_rows, "{query}");
}
}
/// A CTE over a two-field table publishes each native value column under the existing column it
/// answers. The value columns are paired by position, and the two fields hold different values, so a
/// swapped pair changes the rows.
#[tokio::test(flavor = "multi_thread")]
async fn cte_native_two_fields_keep_their_columns() {
common_telemetry::init_default_ut_logging();
let (standalone, observer) =
native_test_instance(GreptimeDbStandaloneBuilder::new("cte_native_two_fields")).await;
let instance = standalone.fe_instance().clone();
execute_all(
&instance,
"CREATE TABLE cte_two_fields (host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, \
a DOUBLE, b DOUBLE); \
INSERT INTO cte_two_fields VALUES \
('h0', 0, 1, 100), ('h0', 1000, 2, 300), ('h0', 2000, 4, 700), ('h0', 3000, 8, 1500)",
QueryContext::arc(),
)
.await;
let statement = "WITH tql AS (TQL EVAL (0, 3, '1s') rate(cte_two_fields[2s])) SELECT * FROM tql ORDER BY ts";
let legacy = native_output_text(native_tql_output(&instance, statement, false).await).await;
observer.clear();
let native = native_output_text(native_tql_output(&instance, statement, true).await).await;
assert!(
!cte_native_observed_fused(&observer).is_empty(),
"the statement runs the fused plan:\n{}",
cte_native_observed_plan_trees(&observer)
);
assert_eq!(native, legacy);
}
/// The control: without the per-request hint the CTE statement keeps the existing plan, so the rows
/// the route is compared against above come from the plan that answered this statement before the
/// route existed.
@@ -12278,24 +12612,9 @@ async fn distributed_cte_native_runs_the_fused_plan_over_raw_sources() {
}
let rows = cte_native_rows(output).await;
assert_eq!(
native_schema,
cte_native_published_schema_expected_native(),
"the CTE publishes the existing planner's columns over the distributed fused plan, then \
the name the answer declares"
);
let legacy_fields = legacy_schema
.fields()
.iter()
.map(|field| field.as_ref())
.collect::<Vec<_>>();
let native_prefix = native_schema.fields()[..legacy_fields.len()]
.iter()
.map(|field| field.as_ref())
.collect::<Vec<_>>();
assert_eq!(
native_prefix, legacy_fields,
"every column the existing route publishes keeps its name, type, nullability and metadata \
on the distributed route too; only the name column is added"
native_schema, legacy_schema,
"the CTE publishes the existing planner's columns over the distributed fused plan, and no \
name column"
);
assert_eq!(rows, cte_native_expected_rows(), "native");
assert_eq!(rows, legacy_rows);
+2
View File
@@ -125,6 +125,7 @@ impl MockInstanceBuilder {
frontend,
datanode,
mito_engine,
flow_engine,
} = instance;
// Procedure loaders retain the old datanode, including its WAL lock.
drop((
@@ -133,6 +134,7 @@ impl MockInstanceBuilder {
mito_engine,
procedure_manager,
event_recorder_handle,
flow_engine,
));
let (procedure_manager, event_recorder_handle) =
standalone::build_procedure_manager(kv_backend.clone(), opts.procedure);