mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
feat(promql): narrow a __field__ scan, and declare the kind a broadcast answers (#10655)
* feat(promql): answer __field__ selectors and same-metric `or` groups natively
Let the native route plan three shapes it used to hand back:
- `__field__` selection (`m{__field__="f"}`) on mito raw scans, metric
logical scans and file-engine row sources: the scan is narrowed to the
selected fields (`field_first_projection`) so `RawSeriesSource` still
sees exactly the canonical frame, text columns are refused as value
kinds, and a matcher naming a column the selection drops is refused
(`row_matchers_need_a_dropped_column`) instead of degrading to a
literal `"" = …` that silently answers nothing.
- `or` groups within one metric (`m{host="a" or host="b"}`) as one scan
with one `Filter`: `AlternativeFilters` merges the groups' conjuncts,
groups that select different fields or tables are refused, and
`discovers_metric_name` learns the alternative groups so the
authorization layer and the planner agree on what a selector
discovers.
- A scalar operand in a composed binary (`(hist * on(job) floats) * 2`):
`native_scalar_operand` binds a scalar side that the composed path
previously required to be a frame.
`field_columns_selected_by` is extracted in `planner.rs` so the legacy
and native routes select the same columns; as a side effect the legacy
route's value-column order for a multi-field `__field__` selection goes
from HashSet order to table order.
Signed-off-by: discord9 <discord9@163.com>
* refactor(promql): share the scalar-binary binder and refuse a histogram over a dynamic scalar
- Fold the composed path's `bind_evaluated_broadcast` into a single
`bind_scalar_binary` shared with `binary_operation`'s scalar tail;
both carry the same modifier refusal and `broadcast(...)` call.
- In `try_plan_native_composed_binary`, decline a histogram frame met
by a *dynamic* scalar (`(hist * on(job) floats) / time()`) with
`histogram_over_a_dynamic_scalar`: the runtime refuses non-float
samples on that branch instead of dropping them. A constant scalar
(`* 2`) keeps planning natively. The refusal can go once the
histogram-aware dynamic kernel lands separately.
- Adapt the tests to the rebased base (#10701): a decline is now an
error carrying its cause, so the `plan_or_refusal` sites assert
`native_decline_reason(..)` and the integration rows that used to
unwrap a declined output assert the cause.
Signed-off-by: discord9 <discord9@163.com>
* refactor(promql): say a refusal is an error and drop the dead pre-or matcher loop
Review follow-ups:
- `histogram_over_a_dynamic_scalar` refused because the dynamic-scalar
kernel on main errors on a non-float sample (#10812), not because
Prometheus lacks a per-point histogram scale — it has one (`h / time()`).
Comment and the three test docs now say so and reference #10812.
- Since #10701 a decline is a planning error with its cause; nothing
falls back to the existing plan. Reword the doc comments and test
docs that still described a fallback.
- `native_promql_or_matchers_narrow_the_scan` asserted the existing
plan's rows for `{host="a" or host="b"}`, which answers `c`: the
parser moves the pre-`or` matchers into the first group and
`matchers_to_expr` reads `matchers.matchers` only, so the existing
plan applies none of them. That is the existing plan's bug, filed
separately; the test no longer states it as an expectation and keeps
only the route check.
- `AlternativeFilters::of_selector` looped over `selector.matchers.matchers`
before the group loop; with any `or` that list is empty, and if it
were not the loop would silently drop every non-selection matcher.
Removed.
Signed-off-by: discord9 <discord9@163.com>
---------
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -484,15 +484,6 @@ fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result<NativeNode
|
||||
let right = compile_expr(context, &binary.rhs)?;
|
||||
return bind_vector_binary(binary, left, right, op);
|
||||
}
|
||||
// One side is a scalar. Prometheus drops an empty `on()`/`ignoring()` here and rejects one with
|
||||
// labels or a fill at parse time; this refuses all of them.
|
||||
if refuses_modifier(binary.modifier.as_ref()) {
|
||||
return Err(not_implemented(&format!(
|
||||
"the vector matching in `{binary}`, which a constant operand has nothing to match: \
|
||||
`on`, `ignoring`, `group_left` and `group_right` name labels of a vector, and a fill \
|
||||
value fills in a match group that could miss"
|
||||
)));
|
||||
}
|
||||
// Prometheus refuses to parse a scalar–scalar comparison without `bool`. Two constants never
|
||||
// reach here: they fold.
|
||||
if binary.lhs.value_type() == ValueType::Scalar
|
||||
@@ -505,12 +496,11 @@ fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result<NativeNode
|
||||
comparison of two scalars is written with `bool` to say whether it holds"
|
||||
)));
|
||||
}
|
||||
Ok(broadcast(
|
||||
let (left, right) = (
|
||||
compile_expr(context, &binary.lhs)?,
|
||||
compile_expr(context, &binary.rhs)?,
|
||||
op,
|
||||
binary.return_bool(),
|
||||
))
|
||||
);
|
||||
bind_scalar_binary(binary, left, right, op)
|
||||
}
|
||||
|
||||
/// Binds the same vector operation over compiled or already evaluated operands.
|
||||
@@ -536,6 +526,26 @@ fn bind_vector_binary(
|
||||
})
|
||||
}
|
||||
|
||||
/// Binds `op` between two operands, at least one of them a scalar, in written order.
|
||||
///
|
||||
/// Prometheus drops an empty `on()`/`ignoring()` here and rejects one with labels or a fill at parse
|
||||
/// time; this refuses all of them.
|
||||
fn bind_scalar_binary(
|
||||
binary: &BinaryExpr,
|
||||
left: NativeNode,
|
||||
right: NativeNode,
|
||||
op: BinaryOp,
|
||||
) -> Result<NativeNode> {
|
||||
if refuses_modifier(binary.modifier.as_ref()) {
|
||||
return Err(not_implemented(&format!(
|
||||
"the vector matching in `{binary}`, which a constant operand has nothing to match: \
|
||||
`on`, `ignoring`, `group_left` and `group_right` name labels of a vector, and a fill \
|
||||
value fills in a match group that could miss"
|
||||
)));
|
||||
}
|
||||
Ok(broadcast(left, right, op, binary.return_bool()))
|
||||
}
|
||||
|
||||
/// Uses the ordinary binary binder for two evaluated frame inputs.
|
||||
pub(crate) fn bind_evaluated_binary(
|
||||
binary: &BinaryExpr,
|
||||
@@ -551,6 +561,23 @@ pub(crate) fn bind_evaluated_binary(
|
||||
NativeTree::try_new(bind_vector_binary(binary, left, right, op)?)
|
||||
}
|
||||
|
||||
/// Uses the ordinary broadcast binder for one evaluated frame and one scalar operand: Prometheus
|
||||
/// broadcasts a scalar over the vector it meets rather than matching series, so such a pair carries
|
||||
/// no `on`, `ignoring`, `group_left`, `group_right` or fill value.
|
||||
pub(crate) fn bind_evaluated_broadcast(
|
||||
binary: &BinaryExpr,
|
||||
left: NativeNode,
|
||||
right: NativeNode,
|
||||
) -> Result<NativeTree> {
|
||||
let op = binary_op(&binary.op).ok_or_else(|| {
|
||||
not_implemented(&format!(
|
||||
"the binary operator `{}` in `{binary}`",
|
||||
binary.op
|
||||
))
|
||||
})?;
|
||||
NativeTree::try_new(bind_scalar_binary(binary, left, right, op)?)
|
||||
}
|
||||
|
||||
/// Compiles `and`, `or` or `unless` between two vectors, matched by the labels the query wrote.
|
||||
///
|
||||
/// The parser already refuses a scalar operand, `bool` and `group_left` / `group_right` on a set
|
||||
|
||||
@@ -2751,6 +2751,73 @@ impl PromPlanner {
|
||||
Ok(Matchers::new(matchers))
|
||||
}
|
||||
|
||||
/// The field columns `field_matchers` select from `field_columns`, in the order `field_columns`
|
||||
/// lists them, for both planner paths.
|
||||
///
|
||||
/// `=` and `!=` must name a column the table carries, while `=~` and `!~` keep or drop what they
|
||||
/// match; a selection without an `=` or `=~` starts from every column, so `!=` and `!~` only drop.
|
||||
fn field_columns_selected_by(
|
||||
field_matchers: &[Matcher],
|
||||
field_columns: &[String],
|
||||
) -> Result<Vec<String>> {
|
||||
let col_set = field_columns.iter().collect::<HashSet<_>>();
|
||||
// opt-in set
|
||||
let mut result_set = HashSet::new();
|
||||
// opt-out set
|
||||
let mut reverse_set = HashSet::new();
|
||||
for matcher in field_matchers {
|
||||
match &matcher.op {
|
||||
MatchOp::Equal => {
|
||||
if col_set.contains(&matcher.value) {
|
||||
let _ = result_set.insert(matcher.value.clone());
|
||||
} else {
|
||||
return Err(ColumnNotFoundSnafu {
|
||||
col: matcher.value.clone(),
|
||||
}
|
||||
.build());
|
||||
}
|
||||
}
|
||||
MatchOp::NotEqual => {
|
||||
if col_set.contains(&matcher.value) {
|
||||
let _ = reverse_set.insert(matcher.value.clone());
|
||||
} else {
|
||||
return Err(ColumnNotFoundSnafu {
|
||||
col: matcher.value.clone(),
|
||||
}
|
||||
.build());
|
||||
}
|
||||
}
|
||||
MatchOp::Re(regex) => {
|
||||
for col in field_columns {
|
||||
if regex.is_match(col) {
|
||||
let _ = result_set.insert(col.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
MatchOp::NotRe(regex) => {
|
||||
for col in field_columns {
|
||||
if regex.is_match(col) {
|
||||
let _ = reverse_set.insert(col.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// merge two set
|
||||
if result_set.is_empty() {
|
||||
result_set = col_set.into_iter().cloned().collect();
|
||||
}
|
||||
for col in reverse_set {
|
||||
let _ = result_set.remove(&col);
|
||||
}
|
||||
|
||||
Ok(field_columns
|
||||
.iter()
|
||||
.filter(|col| result_set.contains(*col))
|
||||
.cloned()
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn selector_to_series_normalize_plan(
|
||||
&mut self,
|
||||
offset_duration: Millisecond,
|
||||
@@ -2779,68 +2846,12 @@ impl PromPlanner {
|
||||
|
||||
// make a projection plan if there is any `__field__` matcher
|
||||
if let Some(field_matchers) = &self.ctx.field_column_matcher {
|
||||
let col_set = self.ctx.field_columns.iter().collect::<HashSet<_>>();
|
||||
// opt-in set
|
||||
let mut result_set = HashSet::new();
|
||||
// opt-out set
|
||||
let mut reverse_set = HashSet::new();
|
||||
for matcher in field_matchers {
|
||||
match &matcher.op {
|
||||
MatchOp::Equal => {
|
||||
if col_set.contains(&matcher.value) {
|
||||
let _ = result_set.insert(matcher.value.clone());
|
||||
} else {
|
||||
return Err(ColumnNotFoundSnafu {
|
||||
col: matcher.value.clone(),
|
||||
}
|
||||
.build());
|
||||
}
|
||||
}
|
||||
MatchOp::NotEqual => {
|
||||
if col_set.contains(&matcher.value) {
|
||||
let _ = reverse_set.insert(matcher.value.clone());
|
||||
} else {
|
||||
return Err(ColumnNotFoundSnafu {
|
||||
col: matcher.value.clone(),
|
||||
}
|
||||
.build());
|
||||
}
|
||||
}
|
||||
MatchOp::Re(regex) => {
|
||||
for col in &self.ctx.field_columns {
|
||||
if regex.is_match(col) {
|
||||
let _ = result_set.insert(col.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
MatchOp::NotRe(regex) => {
|
||||
for col in &self.ctx.field_columns {
|
||||
if regex.is_match(col) {
|
||||
let _ = reverse_set.insert(col.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// merge two set
|
||||
if result_set.is_empty() {
|
||||
result_set = col_set.into_iter().cloned().collect();
|
||||
}
|
||||
for col in reverse_set {
|
||||
let _ = result_set.remove(&col);
|
||||
}
|
||||
let field_columns =
|
||||
Self::field_columns_selected_by(field_matchers, &self.ctx.field_columns)?;
|
||||
|
||||
// mask the field columns in context using computed result set
|
||||
self.ctx.field_columns = self
|
||||
.ctx
|
||||
.field_columns
|
||||
.drain(..)
|
||||
.filter(|col| result_set.contains(col))
|
||||
.collect();
|
||||
|
||||
let exprs = result_set
|
||||
.into_iter()
|
||||
.map(|col| DfExpr::Column(Column::new_unqualified(col)))
|
||||
let exprs = field_columns
|
||||
.iter()
|
||||
.map(|col| DfExpr::Column(Column::new_unqualified(col.as_str())))
|
||||
.chain(self.create_tag_column_exprs()?)
|
||||
.chain(
|
||||
self.ctx
|
||||
@@ -2858,6 +2869,9 @@ impl PromPlanner {
|
||||
.context(DataFusionPlanningSnafu)?
|
||||
.build()
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
|
||||
// mask the field columns in context using the computed selection
|
||||
self.ctx.field_columns = field_columns;
|
||||
}
|
||||
|
||||
// make sort plan
|
||||
|
||||
@@ -86,11 +86,12 @@ use crate::promql::error::{
|
||||
UnsupportedExprSnafu,
|
||||
};
|
||||
use crate::promql::native_compile::{
|
||||
InfoInput, bind_evaluated_binary, compile_selectors_with_grid, compile_statement_with_grid,
|
||||
info_input, statement_grid, subquery_child_grid,
|
||||
InfoInput, bind_evaluated_binary, bind_evaluated_broadcast, compile_selectors_with_grid,
|
||||
compile_statement_with_grid, constant_value, info_input, statement_grid, subquery_child_grid,
|
||||
};
|
||||
use crate::promql::planner::{
|
||||
DEFAULT_FIELD_COLUMN, DEFAULT_TIME_INDEX_COLUMN, GrownStack, PromPlanner,
|
||||
DB_COLUMN_MATCHER, DEFAULT_FIELD_COLUMN, DEFAULT_TIME_INDEX_COLUMN, FIELD_COLUMN_MATCHER,
|
||||
GrownStack, PromPlanner, SCHEMA_COLUMN_MATCHER,
|
||||
};
|
||||
use crate::query_engine::QueryEngineState;
|
||||
|
||||
@@ -299,6 +300,7 @@ impl PromPlanner {
|
||||
async fn prepare_one_scan(
|
||||
&mut self,
|
||||
matchers: Matchers,
|
||||
alternative_groups: &[AlternativeGroup],
|
||||
logical_scan_id: &mut Option<u32>,
|
||||
logical_ids_differ: &mut bool,
|
||||
statement_kind: &mut Option<FieldKind>,
|
||||
@@ -310,14 +312,56 @@ impl PromPlanner {
|
||||
return Ok(declined("selector_without_table_or_time_index"));
|
||||
};
|
||||
let tags = self.ctx.tag_columns.clone();
|
||||
let fields = self.ctx.field_columns.clone();
|
||||
// The raw series scan has no equivalent of the `__field__` projection.
|
||||
if self.ctx.field_column_matcher.is_some() || fields.is_empty() {
|
||||
return Ok(declined("field_selector_without_raw_series_equivalent"));
|
||||
}
|
||||
// A `__field__` matcher selects among the table's field columns, resolved as the existing
|
||||
// plan resolves it; one naming a column the table lacks refuses the statement.
|
||||
let reads_a_field_selection = self.ctx.field_column_matcher.is_some();
|
||||
let selected_fields = match &self.ctx.field_column_matcher {
|
||||
Some(field_matchers) => {
|
||||
let Ok(fields) =
|
||||
Self::field_columns_selected_by(field_matchers, &self.ctx.field_columns)
|
||||
else {
|
||||
return Ok(declined("field_selector_names_a_column_the_table_lacks"));
|
||||
};
|
||||
fields
|
||||
}
|
||||
None => self.ctx.field_columns.clone(),
|
||||
};
|
||||
// Built by the existing path's method so both paths read the same columns.
|
||||
let table_ref = self.table_ref()?;
|
||||
let mut input = self.create_table_scan_plan(table_ref).await?;
|
||||
// This route declares no text value and one value column per field kind, so a text column
|
||||
// is read only where the table keys by it, as a label; otherwise it has no place here.
|
||||
let mut fields = Vec::with_capacity(selected_fields.len());
|
||||
let mut reads_a_text_column = false;
|
||||
for name in &selected_fields {
|
||||
let Some(data_type) = Self::field_column_type(input.schema(), name) else {
|
||||
return Ok(declined("field_missing_from_source_schema"));
|
||||
};
|
||||
if Self::string_value_data_type(data_type).is_some() {
|
||||
reads_a_text_column = true;
|
||||
} else {
|
||||
fields.push(name.clone());
|
||||
}
|
||||
}
|
||||
if reads_a_text_column {
|
||||
return Ok(declined(if reads_a_field_selection {
|
||||
"field_selector_names_a_text_column"
|
||||
} else {
|
||||
"text_field_is_not_a_table_key"
|
||||
}));
|
||||
}
|
||||
if fields.is_empty() {
|
||||
return Ok(declined("selector_reads_no_field"));
|
||||
}
|
||||
let mut read: Vec<&str> = tags.iter().map(String::as_str).collect();
|
||||
read.push(time.as_str());
|
||||
read.extend(fields.iter().map(String::as_str));
|
||||
if row_matchers_need_a_dropped_column(&matchers, alternative_groups, input.schema(), &read)
|
||||
{
|
||||
return Ok(declined(
|
||||
"field_selector_and_row_matcher_need_different_columns",
|
||||
));
|
||||
}
|
||||
let logical_scan = metric_scan_and_table_id(&input);
|
||||
let has_verified_metric_rewrite = logical_scan.is_some();
|
||||
// Two logical tables over one physical table scan the same table; only their ids tell the
|
||||
@@ -331,31 +375,14 @@ impl PromPlanner {
|
||||
}
|
||||
let scan = match logical_scan {
|
||||
Some((mut scan, predicate, _)) => {
|
||||
// Preserve logical field order and the table restriction on the direct
|
||||
// physical scan.
|
||||
let source_schema = scan.source.schema();
|
||||
let Some(mut ordered_projection) = fields
|
||||
.iter()
|
||||
.map(|field| source_schema.index_of(field).ok())
|
||||
.collect::<Option<Vec<_>>>()
|
||||
let Some(projection) =
|
||||
field_first_projection(&scan, &selected_fields, &self.ctx.field_columns)
|
||||
else {
|
||||
return Ok(declined("field_missing_from_source_schema"));
|
||||
};
|
||||
let original_projection = scan.projection.as_ref();
|
||||
let selected_indices = original_projection
|
||||
.cloned()
|
||||
.unwrap_or_else(|| (0..source_schema.fields().len()).collect());
|
||||
for index in selected_indices {
|
||||
let is_field = fields
|
||||
.iter()
|
||||
.any(|field| field == source_schema.field(index).name());
|
||||
if !is_field && !ordered_projection.contains(&index) {
|
||||
ordered_projection.push(index);
|
||||
}
|
||||
}
|
||||
scan.filters.push(predicate);
|
||||
scan = TableScanBuilder::from(scan)
|
||||
.with_projection(Some(ordered_projection))
|
||||
.with_projection(Some(projection))
|
||||
.build()
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
input = LogicalPlan::TableScan(scan.clone());
|
||||
@@ -371,7 +398,29 @@ impl PromPlanner {
|
||||
input = LogicalPlan::TableScan(scan.clone());
|
||||
}
|
||||
match &input {
|
||||
LogicalPlan::TableScan(scan) => scan.clone(),
|
||||
LogicalPlan::TableScan(plain) => {
|
||||
let plain = plain.clone();
|
||||
// A plain scan reads every column; narrowing it means projecting the
|
||||
// selection, since the raw series scan reports one field per field column it
|
||||
// is handed.
|
||||
if !reads_a_field_selection {
|
||||
plain
|
||||
} else {
|
||||
let Some(projection) = field_first_projection(
|
||||
&plain,
|
||||
&selected_fields,
|
||||
&self.ctx.field_columns,
|
||||
) else {
|
||||
return Ok(declined("field_missing_from_source_schema"));
|
||||
};
|
||||
let scan = TableScanBuilder::from(plain)
|
||||
.with_projection(Some(projection))
|
||||
.build()
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
input = LogicalPlan::TableScan(scan.clone());
|
||||
scan
|
||||
}
|
||||
}
|
||||
_ => return Ok(declined("selector_plan_is_not_a_table_scan")),
|
||||
}
|
||||
}
|
||||
@@ -435,7 +484,7 @@ impl PromPlanner {
|
||||
.partition_column_names()
|
||||
.all(|column| tags.iter().any(|tag| tag == column));
|
||||
// Every field must read as one kind: `Float64` or the native histogram struct; any other
|
||||
// type, or a statement whose fields disagree, keeps the existing plan. The raw scan casts
|
||||
// type, or a statement whose fields disagree, refuses the statement. The raw scan casts
|
||||
// numeric fields to `Float64`, and the answer publishes `Float64` even where the existing
|
||||
// plan keeps the field's own type, as in the Prometheus data model.
|
||||
let read_types = fields
|
||||
@@ -471,7 +520,7 @@ impl PromPlanner {
|
||||
return Ok(declined("selector_plan_is_not_a_table_scan"));
|
||||
}
|
||||
if reads_rows {
|
||||
input = row_source_input(input, &tags, &time, &fields, matchers)?;
|
||||
input = row_source_input(input, &tags, &time, &fields, matchers, alternative_groups)?;
|
||||
input = LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(
|
||||
RowSeriesSource::try_new(
|
||||
@@ -486,6 +535,7 @@ impl PromPlanner {
|
||||
});
|
||||
} else {
|
||||
let mut filters = Self::matchers_to_expr(matchers, input.schema())?;
|
||||
filters.extend(alternative_conjuncts(alternative_groups, input.schema())?);
|
||||
if let LogicalPlan::TableScan(table_scan) = &mut input {
|
||||
table_scan.filters.append(&mut filters);
|
||||
}
|
||||
@@ -698,8 +748,8 @@ impl PromPlanner {
|
||||
|
||||
/// Combines two native operands without a legacy join.
|
||||
///
|
||||
/// Each operand of a binary expression is planned as an evaluated series frame. Declines when
|
||||
/// the grids differ or the kernels cannot answer the matching or output kind.
|
||||
/// A scalar operand enters the node as the compiled scalar rather than as an input; a shape the
|
||||
/// kernels refuse declines with the cause the route records, never to the existing plan.
|
||||
async fn try_plan_native_composed_binary(
|
||||
&mut self,
|
||||
expr: &PromExpr,
|
||||
@@ -721,55 +771,34 @@ impl PromPlanner {
|
||||
return Ok(None);
|
||||
};
|
||||
let saved = self.ctx.clone();
|
||||
let _ = take_native_decline();
|
||||
let left = self
|
||||
.try_plan_native(
|
||||
&binary.lhs,
|
||||
query_engine_state,
|
||||
FusedOutputFormat::SeriesFrame,
|
||||
)
|
||||
.await;
|
||||
let left_cause = take_native_decline();
|
||||
self.ctx = saved.clone();
|
||||
let Some(NativePlanned::Frame(left)) = left? else {
|
||||
return Ok(declined(
|
||||
left_cause.unwrap_or("left_operand_is_not_a_frame"),
|
||||
));
|
||||
};
|
||||
let _ = take_native_decline();
|
||||
let right = self
|
||||
.try_plan_native(
|
||||
&binary.rhs,
|
||||
query_engine_state,
|
||||
FusedOutputFormat::SeriesFrame,
|
||||
)
|
||||
.await;
|
||||
let right_cause = take_native_decline();
|
||||
self.ctx = saved;
|
||||
let Some(NativePlanned::Frame(right)) = right? else {
|
||||
return Ok(declined(
|
||||
right_cause.unwrap_or("right_operand_is_not_a_frame"),
|
||||
));
|
||||
};
|
||||
if left.grid.spec() != right.grid.spec() {
|
||||
return Ok(declined("operand_grids_differ"));
|
||||
// Only vector sides are offered as frames below: a scalar is bound afterwards, against the
|
||||
// grid the frame it meets answers on.
|
||||
let is_scalar = |operand: &PromExpr| operand.value_type() == ValueType::Scalar;
|
||||
let (left_scalar, right_scalar) = (is_scalar(&binary.lhs), is_scalar(&binary.rhs));
|
||||
if left_scalar && right_scalar {
|
||||
return Ok(None);
|
||||
}
|
||||
let NativeFramePlan {
|
||||
plan: left_plan,
|
||||
output: left_output,
|
||||
tags: left_tags,
|
||||
kind: left_kind,
|
||||
time: left_time,
|
||||
grid: left_grid,
|
||||
} = left;
|
||||
let NativeFramePlan {
|
||||
plan: right_plan,
|
||||
output: right_output,
|
||||
tags: right_tags,
|
||||
kind: right_kind,
|
||||
..
|
||||
} = right;
|
||||
let source_tags = [left_tags, right_tags];
|
||||
let mut frames: [Option<NativeFramePlan>; 2] = [None, None];
|
||||
for (index, operand) in [&binary.lhs, &binary.rhs].into_iter().enumerate() {
|
||||
if is_scalar(operand) {
|
||||
continue;
|
||||
}
|
||||
let _ = take_native_decline();
|
||||
let planned = self
|
||||
.try_plan_native(operand, query_engine_state, FusedOutputFormat::SeriesFrame)
|
||||
.await;
|
||||
let cause = take_native_decline();
|
||||
self.ctx = saved.clone();
|
||||
let Some(NativePlanned::Frame(frame)) = planned? else {
|
||||
return Ok(declined(cause.unwrap_or(if index == 0 {
|
||||
"left_operand_is_not_a_frame"
|
||||
} else {
|
||||
"right_operand_is_not_a_frame"
|
||||
})));
|
||||
};
|
||||
frames[index] = Some(frame);
|
||||
}
|
||||
self.ctx = saved;
|
||||
let evaluated = |source_index, output: &NativeType| NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index,
|
||||
@@ -779,23 +808,162 @@ impl PromPlanner {
|
||||
}),
|
||||
output: output.clone(),
|
||||
};
|
||||
let tree = match bind_evaluated_binary(
|
||||
binary,
|
||||
evaluated(0, &left_output),
|
||||
evaluated(1, &right_output),
|
||||
) {
|
||||
let [left_frame, right_frame] = frames;
|
||||
let (tree, children, source_tags, time, grid, kinds) = match (left_frame, right_frame) {
|
||||
(Some(left), Some(right)) => {
|
||||
if left.grid.spec() != right.grid.spec() {
|
||||
return Ok(declined("operand_grids_differ"));
|
||||
}
|
||||
let NativeFramePlan {
|
||||
plan: left_plan,
|
||||
output: left_output,
|
||||
tags: left_tags,
|
||||
kind: left_kind,
|
||||
time: left_time,
|
||||
grid: left_grid,
|
||||
} = left;
|
||||
let NativeFramePlan {
|
||||
plan: right_plan,
|
||||
output: right_output,
|
||||
tags: right_tags,
|
||||
kind: right_kind,
|
||||
..
|
||||
} = right;
|
||||
let tree = match bind_evaluated_binary(
|
||||
binary,
|
||||
evaluated(0, &left_output),
|
||||
evaluated(1, &right_output),
|
||||
) {
|
||||
Ok(tree) => tree,
|
||||
Err(DataFusionError::NotImplemented(_)) => {
|
||||
return Ok(declined("no_kernel_for_the_operator_pair"));
|
||||
}
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
(
|
||||
tree,
|
||||
vec![left_plan, right_plan],
|
||||
vec![left_tags, right_tags],
|
||||
left_time,
|
||||
left_grid,
|
||||
(left_kind, right_kind),
|
||||
)
|
||||
}
|
||||
// One side is a scalar: a broadcast over the frame side, which is then the node's only
|
||||
// input, while the scalar enters as the compiled node beside it.
|
||||
(left, right) => {
|
||||
let Some(frame) = left.or(right) else {
|
||||
return Ok(declined("composition_has_no_frame_operand"));
|
||||
};
|
||||
let scalar_expr = if left_scalar {
|
||||
&binary.lhs
|
||||
} else {
|
||||
&binary.rhs
|
||||
};
|
||||
let Some(scalar) = self.native_scalar_operand(scalar_expr, &frame.grid)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Prometheus does define a per-point scale of a histogram (`h / time()`), but the
|
||||
// dynamic-scalar kernel errors on a non-float sample instead of scaling it
|
||||
// (`#10812`), so the pair is refused until that kernel answers histograms.
|
||||
if frame.kind == FieldKind::Histogram && constant_value(scalar_expr).is_none() {
|
||||
return Ok(declined("histogram_over_a_dynamic_scalar"));
|
||||
}
|
||||
let NativeFramePlan {
|
||||
plan,
|
||||
output,
|
||||
tags,
|
||||
kind,
|
||||
time,
|
||||
grid,
|
||||
} = frame;
|
||||
let vector = evaluated(0, &output);
|
||||
let (left, right) = if left_scalar {
|
||||
(scalar, vector)
|
||||
} else {
|
||||
(vector, scalar)
|
||||
};
|
||||
let kinds = if left_scalar {
|
||||
(FieldKind::Float, kind)
|
||||
} else {
|
||||
(kind, FieldKind::Float)
|
||||
};
|
||||
let tree = match bind_evaluated_broadcast(binary, left, right) {
|
||||
Ok(tree) => tree,
|
||||
Err(DataFusionError::NotImplemented(_)) => {
|
||||
return Ok(declined("no_kernel_for_the_operator_pair"));
|
||||
}
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
(tree, vec![plan], vec![tags], time, grid, kinds)
|
||||
}
|
||||
};
|
||||
Self::publish_native_composition(
|
||||
expr,
|
||||
format,
|
||||
tree,
|
||||
&source_tags,
|
||||
children,
|
||||
time,
|
||||
grid,
|
||||
kinds,
|
||||
)
|
||||
}
|
||||
|
||||
/// The scalar node a composition broadcasts over its vector side, or `None` when this route
|
||||
/// does not bind one.
|
||||
fn native_scalar_operand(
|
||||
&self,
|
||||
expr: &PromExpr,
|
||||
grid: &Arc<EvalGrid>,
|
||||
) -> Result<Option<NativeNode>> {
|
||||
let Some(stmt) = self.native_statement(expr) else {
|
||||
return Ok(declined("scalar_operand_has_no_evaluation_grid"));
|
||||
};
|
||||
let Ok(statement) = statement_grid(&stmt) else {
|
||||
return Ok(declined("statement_grid_unavailable"));
|
||||
};
|
||||
if statement.spec() != grid.spec() {
|
||||
return Ok(declined("operand_grids_differ"));
|
||||
}
|
||||
let tree = match compile_statement_with_grid(&stmt, statement) {
|
||||
Ok(tree) => tree,
|
||||
Err(DataFusionError::NotImplemented(_)) => {
|
||||
return Ok(declined("no_kernel_for_the_operator_pair"));
|
||||
return Ok(declined("scalar_operand_has_no_kernel"));
|
||||
}
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
let evaluated = matches!(
|
||||
&tree.root().output,
|
||||
NativeType::Scalar(scalar) if scalar.spec() == grid.spec()
|
||||
);
|
||||
if !evaluated {
|
||||
return Ok(declined("scalar_operand_is_not_a_scalar"));
|
||||
}
|
||||
Ok(Some(tree.root().clone()))
|
||||
}
|
||||
|
||||
/// Publishes a bound composition as one node over `children`.
|
||||
///
|
||||
/// `kinds` are the pair's kinds in the order the operands were written, a scalar side being a
|
||||
/// float; `source_tags` names each child's labels.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn publish_native_composition(
|
||||
expr: &PromExpr,
|
||||
format: FusedOutputFormat,
|
||||
tree: NativeTree,
|
||||
source_tags: &[Vec<String>],
|
||||
children: Vec<LogicalPlan>,
|
||||
time: String,
|
||||
grid: Arc<EvalGrid>,
|
||||
kinds: (FieldKind, FieldKind),
|
||||
) -> Result<Option<NativePlanned>> {
|
||||
let NativeExpr::Binary { matching, .. } = &tree.root().expr else {
|
||||
return Ok(declined("bound_root_is_not_the_binary"));
|
||||
};
|
||||
let Some(root_kind) = binary_output_field_kind(
|
||||
left_kind,
|
||||
right_kind,
|
||||
kinds.0,
|
||||
kinds.1,
|
||||
matching.op,
|
||||
matching.return_bool,
|
||||
matching.fill,
|
||||
@@ -809,7 +977,7 @@ impl PromPlanner {
|
||||
let metadata = match format {
|
||||
FusedOutputFormat::PlainRows => None,
|
||||
FusedOutputFormat::SeriesFrame => {
|
||||
let Some(tags) = fused_output_tags(tree.root(), &source_tags) else {
|
||||
let Some(tags) = fused_output_tags(tree.root(), source_tags) else {
|
||||
return Ok(declined("composition_has_no_output_labels"));
|
||||
};
|
||||
Some((tree.root().output.clone(), tags))
|
||||
@@ -817,13 +985,8 @@ impl PromPlanner {
|
||||
};
|
||||
let output_schema = match format {
|
||||
FusedOutputFormat::PlainRows => {
|
||||
let Some(schema) = Self::fused_root_schema(
|
||||
&expression,
|
||||
&tree,
|
||||
&source_tags,
|
||||
&left_time,
|
||||
root_kind,
|
||||
)?
|
||||
let Some(schema) =
|
||||
Self::fused_root_schema(&expression, &tree, source_tags, &time, root_kind)?
|
||||
else {
|
||||
return Ok(declined("composition_has_no_value_columns"));
|
||||
};
|
||||
@@ -846,12 +1009,12 @@ impl PromPlanner {
|
||||
Arc::from(expression.as_str()),
|
||||
tree,
|
||||
FusedSeriesBinding {
|
||||
grid: Arc::clone(&left_grid),
|
||||
time_index: left_time.clone(),
|
||||
grid: Arc::clone(&grid),
|
||||
time_index: time.clone(),
|
||||
tags: Vec::new(),
|
||||
metric_name: None,
|
||||
},
|
||||
vec![left_plan, right_plan],
|
||||
children,
|
||||
output_schema,
|
||||
format,
|
||||
) else {
|
||||
@@ -860,12 +1023,10 @@ impl PromPlanner {
|
||||
let plan = LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(node),
|
||||
});
|
||||
Ok(Some(native_planned(
|
||||
plan, metadata, root_kind, left_time, left_grid,
|
||||
)))
|
||||
Ok(Some(native_planned(plan, metadata, root_kind, time, grid)))
|
||||
}
|
||||
|
||||
/// Plans `prom_expr` as one native node, or returns `None` to keep the existing plan.
|
||||
/// Plans `prom_expr` as one native node, or returns `None` with the cause the route recorded.
|
||||
///
|
||||
/// The expression text names the value columns. Table, time index, tag and field columns come
|
||||
/// from the planner's resolved selector context.
|
||||
@@ -961,7 +1122,8 @@ impl PromPlanner {
|
||||
}
|
||||
Err(error) => return Err(error).context(DataFusionPlanningSnafu),
|
||||
};
|
||||
// A scalar root has no labels to match, so it cannot be a frame operand.
|
||||
// A frame consumer decodes series, and a composition binds a scalar side as the scalar
|
||||
// it is, so a scalar published as a frame could not be read.
|
||||
let evaluated = matches!(
|
||||
&tree.root().output,
|
||||
NativeType::Samples(schema) if schema.eval_grid.is_some()
|
||||
@@ -1042,14 +1204,17 @@ impl PromPlanner {
|
||||
let mut statement_kind: Option<FieldKind> = None;
|
||||
for selector in &selectors {
|
||||
self.ctx = original_context.clone();
|
||||
if !selector.matchers.or_matchers.is_empty() {
|
||||
return Ok(declined("or_matchers_have_no_single_raw_scan"));
|
||||
let Some(alternatives) = AlternativeFilters::of_selector(selector) else {
|
||||
return Ok(declined("or_matchers_name_different_tables"));
|
||||
};
|
||||
if let Some(reason) = alternatives.merge_refusal() {
|
||||
return Ok(declined(reason));
|
||||
}
|
||||
// A nameless selector enumerates the schema's logical metric tables, one scan each,
|
||||
// unioned into one input.
|
||||
if discovers_metric_name(selector) {
|
||||
let name_matchers = selector.matchers.find_matchers(METRIC_NAME);
|
||||
let mut ordinary_matchers = selector.matchers.clone();
|
||||
let name_matchers = alternatives.shared.find_matchers(METRIC_NAME);
|
||||
let mut ordinary_matchers = alternatives.shared.clone();
|
||||
ordinary_matchers
|
||||
.matchers
|
||||
.retain(|matcher| matcher.name != METRIC_NAME);
|
||||
@@ -1111,10 +1276,19 @@ impl PromPlanner {
|
||||
// rows, so a matcher that rejects the empty string cannot match anything there.
|
||||
metrics.retain(|table| {
|
||||
let schema = table.schema();
|
||||
matchers.matchers.iter().all(|matcher| {
|
||||
matcher.is_match("")
|
||||
|| schema.column_schema_by_name(&matcher.name).is_some()
|
||||
})
|
||||
let keeps = |matchers: &Matchers| {
|
||||
matchers.matchers.iter().all(|matcher| {
|
||||
matcher.is_match("")
|
||||
|| schema.column_schema_by_name(&matcher.name).is_some()
|
||||
})
|
||||
};
|
||||
keeps(&matchers)
|
||||
&& (alternatives.groups.is_empty()
|
||||
|| alternatives
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| &group.rows)
|
||||
.any(keeps))
|
||||
});
|
||||
metrics.sort_by_key(|table| table.table_info().name.clone());
|
||||
if metrics.len() > MAX_DISCOVERED_METRICS {
|
||||
@@ -1164,6 +1338,7 @@ impl PromPlanner {
|
||||
)) = self
|
||||
.prepare_one_scan(
|
||||
matchers.clone(),
|
||||
&alternatives.groups,
|
||||
&mut logical_scan_id,
|
||||
&mut logical_ids_differ,
|
||||
&mut statement_kind,
|
||||
@@ -1258,7 +1433,7 @@ impl PromPlanner {
|
||||
continue;
|
||||
}
|
||||
let matchers =
|
||||
match self.preprocess_label_matchers(&selector.matchers, &selector.name) {
|
||||
match self.preprocess_label_matchers(&alternatives.shared, &selector.name) {
|
||||
Ok(m) => m,
|
||||
Err(_) => return Ok(declined("selector_matchers_cannot_be_preprocessed")),
|
||||
};
|
||||
@@ -1278,6 +1453,7 @@ impl PromPlanner {
|
||||
let Some(one) = self
|
||||
.prepare_one_scan(
|
||||
matchers,
|
||||
&alternatives.groups,
|
||||
&mut logical_scan_id,
|
||||
&mut logical_ids_differ,
|
||||
&mut statement_kind,
|
||||
@@ -2110,6 +2286,7 @@ fn row_source_input(
|
||||
time: &str,
|
||||
fields: &[String],
|
||||
matchers: Matchers,
|
||||
alternative_groups: &[AlternativeGroup],
|
||||
) -> Result<LogicalPlan> {
|
||||
let column = |name: &str| DfExpr::Column(datafusion::common::Column::from_name(name));
|
||||
let mut exprs = tags
|
||||
@@ -2129,7 +2306,11 @@ fn row_source_input(
|
||||
.context(DataFusionPlanningSnafu)?
|
||||
.build()
|
||||
.context(DataFusionPlanningSnafu)?;
|
||||
let filters = PromPlanner::matchers_to_expr(matchers, projected.schema())?;
|
||||
let mut filters = PromPlanner::matchers_to_expr(matchers, projected.schema())?;
|
||||
filters.extend(alternative_conjuncts(
|
||||
alternative_groups,
|
||||
projected.schema(),
|
||||
)?);
|
||||
let Some(predicate) = datafusion_expr::utils::conjunction(filters) else {
|
||||
return Ok(projected);
|
||||
};
|
||||
@@ -2552,8 +2733,163 @@ pub(crate) fn same_table_scans<'a>(plans: impl IntoIterator<Item = &'a LogicalPl
|
||||
/// The most metric tables one discovered selector will scan; more is a planning error.
|
||||
const MAX_DISCOVERED_METRICS: usize = 1024;
|
||||
|
||||
/// What a selector reads, and the rows each of its `or` alternatives keeps.
|
||||
///
|
||||
/// Alternatives are row filters over one table, so they become one scan's predicate rather than one
|
||||
/// scan each: a scan per group would report a twice-kept series twice and hand rows in group order.
|
||||
/// What the groups must agree on is what is read: an alternative's `__field__` selection and its
|
||||
/// `__name__` / `__schema__` / `__database__` are its own, so one scan refuses what they disagree on.
|
||||
#[derive(Debug, Clone)]
|
||||
struct AlternativeFilters {
|
||||
shared: Matchers,
|
||||
/// One per alternative; empty when the selector states no alternatives.
|
||||
groups: Vec<AlternativeGroup>,
|
||||
alternative_names_a_table: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct AlternativeGroup {
|
||||
rows: Matchers,
|
||||
/// The `__field__` matchers this group states; `None` reads every field.
|
||||
fields: Option<Vec<Matcher>>,
|
||||
}
|
||||
|
||||
fn names_what_is_read(matcher: &Matcher) -> bool {
|
||||
matches!(
|
||||
matcher.name.as_str(),
|
||||
FIELD_COLUMN_MATCHER | METRIC_NAME | SCHEMA_COLUMN_MATCHER | DB_COLUMN_MATCHER
|
||||
)
|
||||
}
|
||||
|
||||
/// The selection plus `matcher`'s column, or `None` when it disagrees about the table.
|
||||
fn merge_into_selection(selection: &mut Vec<Matcher>, matcher: &Matcher) -> Option<()> {
|
||||
match matcher.name.as_str() {
|
||||
FIELD_COLUMN_MATCHER => {
|
||||
if !selection.contains(matcher) {
|
||||
selection.push(matcher.clone());
|
||||
}
|
||||
}
|
||||
_ => match selection.iter().find(|held| held.name == matcher.name) {
|
||||
Some(held) if held != matcher => return None,
|
||||
Some(_) => {}
|
||||
None => selection.push(matcher.clone()),
|
||||
},
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
impl AlternativeFilters {
|
||||
/// Splits `selector`'s matchers into what it reads and the rows each group keeps.
|
||||
fn of_selector(selector: &VectorSelector) -> Option<Self> {
|
||||
if selector.matchers.or_matchers.is_empty() {
|
||||
return Some(Self {
|
||||
shared: selector.matchers.clone(),
|
||||
groups: Vec::new(),
|
||||
alternative_names_a_table: false,
|
||||
});
|
||||
}
|
||||
// promql-parser moves the matchers before the first `or` into that `or`'s own group, so
|
||||
// `selector.matchers.matchers` is empty here and every matcher arrives through a group.
|
||||
let mut selection = Vec::new();
|
||||
let mut alternative_names_a_table = false;
|
||||
let mut groups: Vec<AlternativeGroup> =
|
||||
Vec::with_capacity(selector.matchers.or_matchers.len());
|
||||
for group in &selector.matchers.or_matchers {
|
||||
let mut rows = Vec::new();
|
||||
let mut fields = Vec::new();
|
||||
for matcher in group {
|
||||
if matcher.name == FIELD_COLUMN_MATCHER {
|
||||
merge_into_selection(&mut selection, matcher)?;
|
||||
fields.push(matcher.clone());
|
||||
} else if names_what_is_read(matcher) {
|
||||
merge_into_selection(&mut selection, matcher)?;
|
||||
alternative_names_a_table = true;
|
||||
} else {
|
||||
rows.push(matcher.clone());
|
||||
}
|
||||
}
|
||||
let group = AlternativeGroup {
|
||||
rows: Matchers::new(rows),
|
||||
fields: (!fields.is_empty()).then_some(fields),
|
||||
};
|
||||
if !groups.contains(&group) {
|
||||
groups.push(group);
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
shared: Matchers::new(selection),
|
||||
groups,
|
||||
alternative_names_a_table,
|
||||
})
|
||||
}
|
||||
|
||||
fn merge_refusal(&self) -> Option<&'static str> {
|
||||
if self.alternative_names_a_table {
|
||||
return Some("or_alternatives_name_a_table");
|
||||
}
|
||||
if !self
|
||||
.groups
|
||||
.windows(2)
|
||||
.all(|pair| pair[0].fields == pair[1].fields)
|
||||
{
|
||||
return Some("or_alternatives_select_different_fields");
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The conjuncts a selector's alternatives add to its scan.
|
||||
///
|
||||
/// A group with no row filter keeps every row the shared matchers keep, so nothing narrows the scan.
|
||||
fn alternative_conjuncts(groups: &[AlternativeGroup], schema: &DFSchemaRef) -> Result<Vec<DfExpr>> {
|
||||
let conjunctions = groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
Ok(PromPlanner::matchers_to_expr(group.rows.clone(), schema)?
|
||||
.into_iter()
|
||||
.reduce(|left, right| left.and(right)))
|
||||
})
|
||||
.collect::<Result<Vec<Option<DfExpr>>>>()?;
|
||||
match conjunctions.len() {
|
||||
0 => Ok(Vec::new()),
|
||||
1 => Ok(conjunctions.into_iter().flatten().collect()),
|
||||
_ => {
|
||||
if conjunctions.iter().any(Option::is_none) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(conjunctions
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.reduce(|left, right| left.or(right))
|
||||
.into_iter()
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a row matcher names a column the selector's own projection drops: `read` is what the
|
||||
/// projection keeps, and a column the table lacks stays the empty label Prometheus compares against.
|
||||
fn row_matchers_need_a_dropped_column(
|
||||
matchers: &Matchers,
|
||||
groups: &[AlternativeGroup],
|
||||
schema: &DFSchemaRef,
|
||||
read: &[&str],
|
||||
) -> bool {
|
||||
let named = matchers
|
||||
.matchers
|
||||
.iter()
|
||||
.chain(groups.iter().flat_map(|group| group.rows.matchers.iter()))
|
||||
.filter(|matcher| !names_what_is_read(matcher))
|
||||
.filter_map(|matcher| PromPlanner::find_case_sensitive_column(schema, &matcher.name));
|
||||
named
|
||||
.into_iter()
|
||||
.any(|column| !read.contains(&column.as_str()))
|
||||
}
|
||||
|
||||
/// Whether a selector names no single table and has to enumerate the schema's metric tables.
|
||||
///
|
||||
/// The matchers inside a selector's `or` alternatives are row filters, so it still needs discovery.
|
||||
///
|
||||
/// Public so the authorization layer gives the same answer as the planner.
|
||||
pub fn discovers_metric_name(selector: &VectorSelector) -> bool {
|
||||
let name_matchers = selector.matchers.find_matchers(METRIC_NAME);
|
||||
@@ -2563,13 +2899,22 @@ pub fn discovers_metric_name(selector: &VectorSelector) -> bool {
|
||||
let has_exact_name_matcher = name_matchers.len() == 1 && !has_non_equal_name_matcher;
|
||||
selector.name.is_none()
|
||||
&& !has_exact_name_matcher
|
||||
&& selector.matchers.or_matchers.is_empty()
|
||||
&& (name_matchers.len() > 1
|
||||
|| has_non_equal_name_matcher
|
||||
|| selector.matchers.matchers.iter().any(|matcher| {
|
||||
!["__schema__", "__database__", "__field__", METRIC_NAME]
|
||||
|| selector
|
||||
.matchers
|
||||
.matchers
|
||||
.iter()
|
||||
.chain(selector.matchers.or_matchers.iter().flatten())
|
||||
.any(|matcher| {
|
||||
![
|
||||
SCHEMA_COLUMN_MATCHER,
|
||||
DB_COLUMN_MATCHER,
|
||||
FIELD_COLUMN_MATCHER,
|
||||
METRIC_NAME,
|
||||
]
|
||||
.contains(&matcher.name.as_str())
|
||||
}))
|
||||
}))
|
||||
}
|
||||
|
||||
/// One side of a set operation, as the slice of the pre-order selector list it reads.
|
||||
@@ -2814,6 +3159,34 @@ fn metric_scan_and_table_id(
|
||||
Some((scan.clone(), filter.predicate.clone(), *table_id))
|
||||
}
|
||||
|
||||
/// The scan projection that reads `fields` followed by the scan's non-field columns: the region scan
|
||||
/// requires the requested field sequence to match its projection exactly, so a field column `fields`
|
||||
/// does not name is dropped rather than read beside the selection.
|
||||
fn field_first_projection(
|
||||
scan: &datafusion::logical_expr::TableScan,
|
||||
fields: &[String],
|
||||
table_fields: &[String],
|
||||
) -> Option<Vec<usize>> {
|
||||
let source_schema = scan.source.schema();
|
||||
let mut projection = fields
|
||||
.iter()
|
||||
.map(|field| source_schema.index_of(field).ok())
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let read_indices = scan
|
||||
.projection
|
||||
.clone()
|
||||
.unwrap_or_else(|| (0..source_schema.fields().len()).collect());
|
||||
for index in read_indices {
|
||||
let is_field = table_fields
|
||||
.iter()
|
||||
.any(|field| field == source_schema.field(index).name());
|
||||
if !is_field && !projection.contains(&index) {
|
||||
projection.push(index);
|
||||
}
|
||||
}
|
||||
Some(projection)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2651,8 +2651,8 @@ async fn native_aggregate_complete_over_four_nonempty_mito_partitions() {
|
||||
const GROUP_B: &[(&str, &str)] = &[("job", "b")];
|
||||
[(GROUP_A, a), (GROUP_B, b)]
|
||||
}
|
||||
// Both tables have exactly one value field (`v`), so a bare table selector reads it. A
|
||||
// `__field__` matcher would narrow the field set, and the native route declines such a query.
|
||||
// Both tables have exactly one value field (`v`), so a bare table selector reads it, and a
|
||||
// `__field__` matcher naming it would select the same field.
|
||||
let cases = [
|
||||
case(format!("sum by (job) ({GAUGE_TABLE})"), &by_job(18.0, 12.0)),
|
||||
// The gauge's groups average to 6 and 6, and the producer's plan line has to name the
|
||||
|
||||
@@ -2752,6 +2752,194 @@ async fn native_tql_discovers_metrics_like_the_prometheus_handler() {
|
||||
assert_eq!(2, rows);
|
||||
}
|
||||
|
||||
/// A selector's `or` alternatives narrow the one scan below the node.
|
||||
///
|
||||
/// The groups are row filters over one table, so a series both groups keep is read once. The existing
|
||||
/// plan pushes none of them down: promql-parser moves the matchers before the first `or` into that
|
||||
/// `or`'s own group, and `matchers_to_expr` reads only `matchers.matchers`, so for this query it
|
||||
/// applies no matcher at all and answers every series of the table - hence `native_or_pair`'s third
|
||||
/// series, which the fixture states rather than hides.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_or_matchers_narrow_the_scan() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
|
||||
"native_promql_or_matchers",
|
||||
))
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE native_or_phy (ts TIMESTAMP TIME INDEX, v DOUBLE) \
|
||||
ENGINE=metric WITH (\"physical_metric_table\" = \"\"); \
|
||||
CREATE TABLE native_or_pair (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \
|
||||
TIME INDEX (ts), PRIMARY KEY (host)) \
|
||||
ENGINE=metric WITH (on_physical_table = 'native_or_phy'); \
|
||||
CREATE TABLE native_or_overlap (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \
|
||||
TIME INDEX (ts), PRIMARY KEY (host)) \
|
||||
ENGINE=metric WITH (on_physical_table = 'native_or_phy'); \
|
||||
INSERT INTO native_or_pair (host, ts, v) VALUES ('a', 0, 2), ('b', 0, 4), ('c', 0, 8); \
|
||||
INSERT INTO native_or_overlap (host, ts, v) VALUES ('a', 0, 6)",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// A repeated alternative is one filter, not a second reading of the same rows.
|
||||
for (query, expected) in [
|
||||
(
|
||||
r#"native_or_pair{host="a" or host="b"}"#,
|
||||
vec![(0, "a".to_string(), 2.0), (0, "b".to_string(), 4.0)],
|
||||
),
|
||||
(
|
||||
r#"native_or_pair{host="a" or host="b" or host="a"}"#,
|
||||
vec![(0, "a".to_string(), 2.0), (0, "b".to_string(), 4.0)],
|
||||
),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (0, 0, '1s') {query}");
|
||||
observer.clear();
|
||||
let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_native_rows_plan(&observer);
|
||||
assert_eq!(expected, native, "{query}");
|
||||
observer.clear();
|
||||
// Only the route is pinned here: the existing plan applies no alternative, so its rows are
|
||||
// not an expectation this test states.
|
||||
let _ = native_result_rows(native_tql_output(&instance, &sql, false).await).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"{query} must keep the existing plan when the native route is off"
|
||||
);
|
||||
}
|
||||
|
||||
// The one series both alternatives keep is read once, not once per alternative.
|
||||
let query = r#"native_or_overlap{host=~"a" or host="a"}"#;
|
||||
let sql = format!("TQL EVAL (0, 0, '1s') {query}");
|
||||
observer.clear();
|
||||
let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_native_rows_plan(&observer);
|
||||
assert_eq!(vec![(0, "a".to_string(), 6.0)], native, "{query}");
|
||||
observer.clear();
|
||||
let legacy = native_result_rows(native_tql_output(&instance, &sql, false).await).await;
|
||||
assert_eq!(native, legacy, "{query}");
|
||||
|
||||
// A `__field__` alternative names a column rather than a row, so the groups' selections are one
|
||||
// selection and the scan reads the field it names.
|
||||
let query = r#"native_or_pair{__field__="v" or __field__="v"}"#;
|
||||
let sql = format!("TQL EVAL (0, 0, '1s') {query}");
|
||||
observer.clear();
|
||||
let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_native_rows_plan(&observer);
|
||||
assert_eq!(
|
||||
vec![
|
||||
(0, "a".to_string(), 2.0),
|
||||
(0, "b".to_string(), 4.0),
|
||||
(0, "c".to_string(), 8.0),
|
||||
],
|
||||
native,
|
||||
"{query}: a selection of the field column keeps every series reading it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every sample a statement answers, as the host and the value of its one value column.
|
||||
///
|
||||
/// A statement that publishes one value column names it after the query rather than after the field,
|
||||
/// so the sample's field is the one the statement selected, not the column's name.
|
||||
async fn native_host_value_rows(output: Output) -> Vec<(String, f64)> {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
_ => unreachable!("TQL EVAL returns record batches"),
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for batch in batches.iter() {
|
||||
let values = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.filter(|column| column.data_type() == &DataType::Float64)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(1, values.len(), "expected one value column");
|
||||
let values = values[0]
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.expect("a value column is a float");
|
||||
let hosts = cast(
|
||||
batch.column_by_name("host").unwrap().as_ref(),
|
||||
&DataType::Utf8,
|
||||
)
|
||||
.unwrap();
|
||||
let hosts = hosts.as_any().downcast_ref::<StringArray>().unwrap();
|
||||
for row in 0..batch.num_rows() {
|
||||
if !values.is_null(row) {
|
||||
rows.push((hosts.value(row).to_string(), values.value(row)));
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
rows
|
||||
}
|
||||
|
||||
/// Alternatives that read their own field or name their own table are refused by the native route:
|
||||
/// a single scan carries one field list, and reads one table, for all of them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_or_alternatives_with_their_own_field_or_table_are_refused() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
|
||||
"native_promql_or_field_alternatives",
|
||||
))
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE native_or_field (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \
|
||||
w DOUBLE NULL, PRIMARY KEY (host), TIME INDEX (ts)); \
|
||||
INSERT INTO native_or_field (host, ts, v, w) VALUES ('a', 0, 2, 6), ('c', 0, 4, 8)",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
for (query, refusal) in [
|
||||
(
|
||||
r#"native_or_field{__field__="v", host="a" or __field__="w", host="c"}"#,
|
||||
"or_alternatives_select_different_fields",
|
||||
),
|
||||
(
|
||||
r#"native_or_field{__field__="v", host="a" or __field__="w"}"#,
|
||||
"or_alternatives_select_different_fields",
|
||||
),
|
||||
// A schema named by one alternative is that alternative's own: one scan would read it for
|
||||
// the other, which never asked for it.
|
||||
(
|
||||
r#"native_or_field{__schema__="public", host="a" or host="b"}"#,
|
||||
"or_alternatives_name_a_table",
|
||||
),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (0, 0, '1s') {query}");
|
||||
observer.clear();
|
||||
assert_native_decline(&instance, &sql, refusal, query).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"{query}: one scan cannot answer these alternatives as they are written"
|
||||
);
|
||||
}
|
||||
|
||||
// One alternative on its own reads its own field of its own rows: the row of `host="a"` carries
|
||||
// `v=2` and `w=6`, and the selection answers `2` only.
|
||||
for (query, expected) in [
|
||||
(
|
||||
r#"native_or_field{__field__="v", host="a"}"#,
|
||||
vec![("a".to_string(), 2.0)],
|
||||
),
|
||||
(
|
||||
r#"native_or_field{__field__="w", host="c"}"#,
|
||||
vec![("c".to_string(), 8.0)],
|
||||
),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (0, 0, '1s') {query}");
|
||||
observer.clear();
|
||||
let native = native_host_value_rows(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_native_rows_plan(&observer);
|
||||
assert_eq!(expected, native, "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A native rows result names each row after the metric it came from.
|
||||
///
|
||||
/// The name is part of what the statement answers, not of how a result is displayed: `sum by
|
||||
@@ -5640,6 +5828,227 @@ async fn native_promql_kind_rules_match_legacy() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A scalar operand broadcasts over the vector it meets on both routes, row for row.
|
||||
///
|
||||
/// `(scalar_hist * on(job) scalar_float) * 2` composes because its selectors carry different field
|
||||
/// kinds, and its scalar right side broadcasts over the vector it meets: a histogram times a float
|
||||
/// stays a histogram, and the existing plan's rows say so. Prometheus also defines a per-point scale
|
||||
/// of a histogram, but the dynamic-scalar kernel errors on a non-float sample instead of scaling it
|
||||
/// (`#10812`), so the same pair under `time()` is refused and only the existing plan answers it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_composed_scalar_operand_matches_legacy() {
|
||||
use api::greptime_proto::io::prometheus::write::v2::histogram::{Count, ZeroCount};
|
||||
use api::greptime_proto::io::prometheus::write::v2::{Histogram, Sample};
|
||||
use axum::body::{Body, to_bytes};
|
||||
use http::Request;
|
||||
use prost::Message;
|
||||
use servers::prom_remote_write::v2::test_util as remote_write_v2;
|
||||
use servers::prom_store::snappy_compress;
|
||||
use tower::ServiceExt;
|
||||
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new(
|
||||
"native_promql_composed_scalar",
|
||||
))
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
let server = crate::test_util::build_test_prom_server(instance.clone(), false, None).build();
|
||||
let router = server.build(server.make_app()).unwrap();
|
||||
// One histogram metric and one float metric, written through the remote-write endpoint so both
|
||||
// tables carry one layout: a difference in the answers is then not a difference in the fixture.
|
||||
for request in [
|
||||
remote_write_v2::request_with_labels_and_histograms(
|
||||
vec![("__name__", "scalar_hist"), ("job", "api"), ("host", "a")],
|
||||
[600_000, 1_200_000]
|
||||
.into_iter()
|
||||
.map(|timestamp| Histogram {
|
||||
timestamp,
|
||||
count: Some(Count::CountInt(4)),
|
||||
zero_count: Some(ZeroCount::ZeroCountInt(4)),
|
||||
sum: 8.0,
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
remote_write_v2::request_with_labels_and_samples(
|
||||
vec![("__name__", "scalar_float"), ("job", "api"), ("host", "a")],
|
||||
[(600_000, 2.0), (1_200_000, 3.0)]
|
||||
.into_iter()
|
||||
.map(|(timestamp, value)| Sample {
|
||||
timestamp,
|
||||
value,
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
] {
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::post("/v1/prometheus/write")
|
||||
.header("Content-Encoding", "snappy")
|
||||
.header(
|
||||
"Content-Type",
|
||||
"application/x-protobuf;proto=io.prometheus.write.v2.Request",
|
||||
)
|
||||
.body(Body::from(
|
||||
snappy_compress(&request.encode_to_vec()).unwrap(),
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
204,
|
||||
"{:?}",
|
||||
to_bytes(response.into_body(), usize::MAX).await.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
// The histogram side is `count = 4, sum = 8` and the float side `2` then `3`, so the match answers
|
||||
// `8/16` then `12/24`, labelled by `job` alone. A constant scalar scales the histogram it is
|
||||
// broadcast over, so the pair runs natively and the existing plan answers it row for row.
|
||||
let expression = "(scalar_hist * on(job) scalar_float) * 2";
|
||||
let expected = vec![
|
||||
(600_000, vec!["job=api".to_string()], 16.0, 32.0),
|
||||
(1_200_000, vec!["job=api".to_string()], 24.0, 48.0),
|
||||
];
|
||||
let sql = format!("TQL EVAL (600, 1200, '600s') {expression}");
|
||||
observer.clear();
|
||||
let native = native_tql_output(&instance, &sql, true).await;
|
||||
assert!(
|
||||
observer.fused().is_some(),
|
||||
"{expression} did not run natively: {:#?}",
|
||||
observer.root_plan()
|
||||
);
|
||||
let native_rows = histogram_label_rows(native).await;
|
||||
assert_eq!(expected, native_rows, "{expression}");
|
||||
observer.clear();
|
||||
let legacy = native_tql_output(&instance, &sql, false).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"{expression} must keep the existing plan when the native route is off"
|
||||
);
|
||||
assert_eq!(
|
||||
histogram_label_rows(legacy).await,
|
||||
native_rows,
|
||||
"{expression} must answer the existing plan's rows row for row"
|
||||
);
|
||||
|
||||
// `time()` is the step in seconds - `600` and `1200` here - so the divisor meets the histogram's
|
||||
// samples one point at a time. That per-point scale is what Prometheus defines, but the
|
||||
// dynamic-scalar kernel errors on a non-float sample instead of scaling it (`#10812`), so the
|
||||
// native route refuses the pair and the rows read through `native = false` are the expectations
|
||||
// below.
|
||||
let expression = "(scalar_hist * on(job) scalar_float) / time()";
|
||||
let expected = vec![
|
||||
(
|
||||
600_000,
|
||||
vec!["job=api".to_string()],
|
||||
8.0 / 600.0,
|
||||
16.0 / 600.0,
|
||||
),
|
||||
(
|
||||
1_200_000,
|
||||
vec!["job=api".to_string()],
|
||||
12.0 / 1200.0,
|
||||
24.0 / 1200.0,
|
||||
),
|
||||
];
|
||||
let sql = format!("TQL EVAL (600, 1200, '600s') {expression}");
|
||||
assert_native_decline(
|
||||
&instance,
|
||||
&sql,
|
||||
"histogram_over_a_dynamic_scalar",
|
||||
expression,
|
||||
)
|
||||
.await;
|
||||
observer.clear();
|
||||
let rows = histogram_label_rows(native_tql_output(&instance, &sql, false).await).await;
|
||||
assert_eq!(expected, rows, "{expression}");
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"{expression} must keep the existing plan when the native route is off"
|
||||
);
|
||||
|
||||
// A scalar over a float metric still runs natively, and a composed operand of one keeps its node.
|
||||
let float_expression = "(scalar_float * 2) * 2";
|
||||
let sql = format!("TQL EVAL (600, 1200, '600s') {float_expression}");
|
||||
observer.clear();
|
||||
let native = native_tql_output(&instance, &sql, true).await;
|
||||
assert!(
|
||||
observer.fused().is_some(),
|
||||
"{float_expression} did not run natively: {:#?}",
|
||||
observer.root_plan()
|
||||
);
|
||||
let native_rows = native_rows_value(native).await;
|
||||
observer.clear();
|
||||
let legacy = native_tql_output(&instance, &sql, false).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"{float_expression} must keep the existing plan when the native route is off"
|
||||
);
|
||||
assert_eq!(
|
||||
vec![
|
||||
(600_000, "api".to_string(), 8.0),
|
||||
(1_200_000, "api".to_string(), 12.0)
|
||||
],
|
||||
native_rows,
|
||||
"{float_expression}"
|
||||
);
|
||||
assert_eq!(
|
||||
native_rows_value(legacy).await,
|
||||
native_rows,
|
||||
"{float_expression} must answer the existing plan's rows row for row"
|
||||
);
|
||||
}
|
||||
|
||||
/// The `(time, job, value)` rows of a labelled float answer, matched by values rather than names.
|
||||
async fn native_rows_value(output: Output) -> Vec<(i64, String, f64)> {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
_ => unreachable!("TQL EVAL returns record batches"),
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for batch in batches.iter() {
|
||||
let time = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.find(|column| {
|
||||
matches!(
|
||||
column.data_type(),
|
||||
DataType::Timestamp(TimeUnit::Millisecond, _)
|
||||
)
|
||||
})
|
||||
.expect("a PromQL result carries its time index");
|
||||
let time = cast(time.as_ref(), &DataType::Int64).unwrap();
|
||||
let time = time.as_any().downcast_ref::<Int64Array>().unwrap();
|
||||
let job = batch
|
||||
.column_by_name("job")
|
||||
.expect("the answer carries the label it matched on");
|
||||
let job = cast(job.as_ref(), &DataType::Utf8).unwrap();
|
||||
let job = job.as_any().downcast_ref::<StringArray>().unwrap();
|
||||
let values = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.filter(|column| column.data_type() == &DataType::Float64)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(values.len(), 1, "expected one Float64 value column");
|
||||
let values = values[0].as_any().downcast_ref::<Float64Array>().unwrap();
|
||||
for row in 0..batch.num_rows() {
|
||||
rows.push((
|
||||
time.value(row),
|
||||
job.value(row).to_string(),
|
||||
values.value(row),
|
||||
));
|
||||
}
|
||||
}
|
||||
rows.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
|
||||
rows
|
||||
}
|
||||
|
||||
/// A float function above a split `sum` over native histograms runs natively and answers what the
|
||||
/// existing plan and Prometheus answer.
|
||||
///
|
||||
@@ -14507,6 +14916,35 @@ async fn native_promql_answers_numeric_fields_as_float64() {
|
||||
);
|
||||
}
|
||||
|
||||
// A `__field__` matcher narrows what the scan reads: the selection is the scan's projection, so
|
||||
// the statement publishes one value column.
|
||||
for (query, fused) in [
|
||||
(format!(r#"{TABLE}{{__field__="f"}}"#), true),
|
||||
// Every numeric field is answered as a `Float64`, the integer one included.
|
||||
(format!(r#"{TABLE}{{__field__="i"}}"#), true),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (2, 2, '1s') {query}");
|
||||
observer.clear();
|
||||
let native = native_answer(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_eq!(
|
||||
fused,
|
||||
observer.fused().is_some(),
|
||||
"`{query}`: {}",
|
||||
observer.answering_node().unwrap_or_default()
|
||||
);
|
||||
assert_eq!(
|
||||
vec![DataType::Float64],
|
||||
native.value_types,
|
||||
"`{query}`: only the selected field is a value column"
|
||||
);
|
||||
let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await;
|
||||
assert_eq!(
|
||||
numeric_rows(&native),
|
||||
numeric_rows(&legacy),
|
||||
"`{query}`: the selected field's rows"
|
||||
);
|
||||
}
|
||||
|
||||
// A field the raw series preflight refuses has no float to publish, whatever the shape is. These
|
||||
// keep the existing plan, which is where their answer comes from - for some of them an error
|
||||
// (`sum` of a string has no fold), and that error is the answer the route must not replace.
|
||||
@@ -14524,34 +14962,52 @@ async fn native_promql_answers_numeric_fields_as_float64() {
|
||||
for query in [
|
||||
TEXT_TABLE.to_string(),
|
||||
format!("sum({TEXT_TABLE})"),
|
||||
format!("{TEXT_TABLE} * 2"),
|
||||
format!("rate({TEXT_TABLE}[2s])"),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (2, 2, '1s') {query}");
|
||||
observer.clear();
|
||||
native_run_ignoring_the_answer(&instance, &sql, true).await;
|
||||
assert_native_decline(&instance, &sql, "text_field_is_not_a_table_key", &query).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"`{query}`: a string field has no raw representation"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a TQL statement and drops whatever it answered.
|
||||
///
|
||||
/// A statement the existing planner refuses is answered by that refusal - `sum` of a string has no
|
||||
/// fold - and the route must not replace it with an answer of its own, so a test that only means to
|
||||
/// hold the route to the existing plan must not unwrap the answer.
|
||||
async fn native_run_ignoring_the_answer(instance: &Arc<Instance>, sql: &str, enabled: bool) {
|
||||
let Ok(output) = instance
|
||||
.do_query(sql, native_query_context(enabled, 4))
|
||||
.await
|
||||
.remove(0)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let OutputData::Stream(stream) = output.data {
|
||||
let _ = collect_batches(stream).await;
|
||||
// A text column beside a numeric one is the same answer: no frame carries a text value.
|
||||
const MIXED_TABLE: &str = "native_numeric_shape_mixed";
|
||||
execute_all(
|
||||
&instance,
|
||||
&format!(
|
||||
"CREATE TABLE {MIXED_TABLE} (host STRING, ts TIMESTAMP(3) TIME INDEX, l STRING, v DOUBLE, PRIMARY KEY (host)); \
|
||||
INSERT INTO {MIXED_TABLE} (host, ts, l, v) VALUES ('a', 0, 'x', 1), ('a', 1000, 'y', 2); \
|
||||
ADMIN FLUSH_TABLE('{MIXED_TABLE}');"
|
||||
),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
for (query, refusal) in [
|
||||
(MIXED_TABLE.to_string(), "text_field_is_not_a_table_key"),
|
||||
(
|
||||
format!("sum({MIXED_TABLE})"),
|
||||
"text_field_is_not_a_table_key",
|
||||
),
|
||||
(
|
||||
format!("rate({MIXED_TABLE}[2s])"),
|
||||
"text_field_is_not_a_table_key",
|
||||
),
|
||||
(
|
||||
format!(r#"{MIXED_TABLE}{{__field__="l"}}"#),
|
||||
"field_selector_names_a_text_column",
|
||||
),
|
||||
] {
|
||||
let sql = format!("TQL EVAL (2, 2, '1s') {query}");
|
||||
observer.clear();
|
||||
assert_native_decline(&instance, &sql, refusal, &query).await;
|
||||
assert!(
|
||||
observer.fused().is_none(),
|
||||
"`{query}`: a text column is a value column of the existing plan, and no raw frame \
|
||||
carries one"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user