From 187facb58f77c5b1916eea4296ec7f44d6be7f31 Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Mon, 30 Nov 2026 14:56:49 +0000 Subject: [PATCH] feat(promql): let TQL discover metrics on the native route (#10674) * feat(promql): let TQL discover metrics on the native route TQL statements never prepared a metric discovery scope, so the native route declined nameless and regex `__name__` selectors in TQL (`metric_discovery_unavailable`) and the legacy planner then rejected them, while the same query worked over the Prometheus HTTP API. SQL statement authorization now prepares the scope for the PromQL a statement evaluates (TQL EVAL/EXPLAIN/ANALYZE and TQL CTEs), keeping each discovered table that the statement's own permission request may read, and resolves the statement's table targets from the named tables plus that scope, as the HTTP path does. The returned context is the one the statement is planned with. A TQL CTE that discovers metrics publishes the native answer's columns: the legacy planner refuses such selectors, so there is no legacy schema to publish over it. Signed-off-by: Dennis Zhuang * test(frontend): pin TQL discovery to the statement's own permission request Signed-off-by: Dennis Zhuang * refactor(query): plan a metric-discovering TQL relation natively once Signed-off-by: Dennis Zhuang --------- Signed-off-by: Dennis Zhuang --- src/frontend/src/instance.rs | 304 ++++++++++++++++----- src/query/src/planner.rs | 56 +++- src/sql/src/util.rs | 36 +++ tests-integration/src/tests/promql_test.rs | 147 +++++----- 4 files changed, 390 insertions(+), 153 deletions(-) diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index f637c026388..9d10591fba1 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -105,7 +105,8 @@ use sql::statements::statement::Statement; use sql::statements::tql::Tql; use sql::util::{ extract_tables_from_prom_expr_checked, extract_tables_from_prom_expr_partial, - extract_tables_from_statement_checked, + extract_tables_from_statement_checked, extract_tables_from_statement_partial, + extract_tql_exprs_from_statement, }; use sqlparser::ast::{AnalyzeFormat, ObjectName}; use tracing::Span; @@ -700,11 +701,13 @@ impl Instance { } } + /// Authorizes `stmt` and returns the context to plan it with: the one given, carrying the + /// metric discovery scope this authorization resolved when the statement evaluates TQL. async fn check_sql_permission( &self, stmt: &Statement, query_ctx: &QueryContextRef, - ) -> Result<()> { + ) -> Result { self.check_unselected_mysql_database(stmt, query_ctx) .await?; self.plugins @@ -719,41 +722,63 @@ impl Instance { // Database COPY needs the full table set before table-target authorization. if matches!(stmt, Statement::Copy(Copy::CopyDatabase(_))) { - return Ok(()); + return Ok(query_ctx.clone()); } - let targets = match extract_tables_from_statement_checked(stmt) { - Some(tables) => PermissionTableTargets::resolved( - tables - .map(|name| { - table_idents_to_full_name(&name, query_ctx).map( - |(catalog, schema, table)| { - PermissionTableTarget::new(catalog, schema, table) - }, - ) + let full_names = |names: Vec, query_ctx: &QueryContextRef| { + names + .into_iter() + .map(|name| { + table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| { + PermissionTableTarget::new(catalog, schema, table) }) - .collect::, _>>() - .map_err(BoxedError::new) - .context(ExternalSnafu)?, - ), + }) + .collect::, _>>() + .map_err(BoxedError::new) + .context(ExternalSnafu) + }; + let mut targets = match extract_tables_from_statement_checked(stmt) { + Some(tables) => { + PermissionTableTargets::resolved(full_names(tables.collect(), query_ctx)?) + } None => PermissionTableTargets::Unresolved, }; let req = PermissionReq::SqlStatement(stmt); + let mut query_ctx = query_ctx.clone(); + // TQL discovers metrics the way the Prometheus handler does, bounded by the tables this + // statement's own permission request may read. + if let Some(exprs) = extract_tql_exprs_from_statement(stmt) + && !exprs.is_empty() + { + self.prepare_metric_discovery_scope_with(&exprs, req.clone(), &mut query_ctx) + .await?; + if matches!(targets, PermissionTableTargets::Unresolved) + && let Some(discovered) = + MetricDiscoveryVisitor::walk(&exprs, query_ctx.current_schema()) + .discovery_targets(query_ctx.metric_discovery_scope()) + { + let mut resolved = + full_names(extract_tables_from_statement_partial(stmt), &query_ctx)?; + resolved.extend(discovered); + targets = PermissionTableTargets::resolved(resolved); + } + } if matches!( stmt, Statement::Copy(Copy::CopyTable(CopyTable::To(_)) | Copy::CopyQueryTo(_)) ) { // COPY retains its write permission requirement and also reads source data. self.check_resolved_table_permissions( - query_ctx, + &query_ctx, [PermissionReq::Action(COPY_TO), req], targets, ) - .await + .await?; } else { - self.check_resolved_table_permission(query_ctx, req, targets) - .await + self.check_resolved_table_permission(&query_ctx, req, targets) + .await?; } + Ok(query_ctx) } #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_analyze_stream_query")] @@ -780,7 +805,7 @@ impl Instance { validate_analyze_stream_statement(&mut stmt)?; query_ctx.set_explain_format(AnalyzeFormat::JSON.to_string()); - self.check_sql_permission(&stmt, &query_ctx).await?; + let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?; check_permission(self.plugins.clone(), &stmt, &query_ctx)?; let catalog_name = query_ctx.current_catalog().to_string(); let schema_name = query_ctx.current_schema(); @@ -928,12 +953,15 @@ impl Instance { let mut results = Vec::with_capacity(stmts.len()); for stmt in stmts { - if let Err(e) = self.check_sql_permission(&stmt, &query_ctx).await { - results.push(Err(e)); - break; - } + let stmt_ctx = match self.check_sql_permission(&stmt, &query_ctx).await { + Ok(stmt_ctx) => stmt_ctx, + Err(e) => { + results.push(Err(e)); + break; + } + }; - match self.query_statement(stmt.clone(), query_ctx.clone()).await { + match self.query_statement(stmt.clone(), stmt_ctx).await { Ok(output) => { let output_result = query_interceptor.post_execute(output, query_ctx.clone()); @@ -1181,7 +1209,8 @@ impl Instance { if let Statement::Tql(tql) = stmt { // TQL produces a logical plan; describe it from the plan so the // extended-protocol RowDescription matches the executed DataRows. - self.check_sql_permission(&Statement::Tql(tql.clone()), &query_ctx) + let query_ctx = self + .check_sql_permission(&Statement::Tql(tql.clone()), &query_ctx) .await?; let plan = self.statement_executor.plan_tql(tql, &query_ctx).await?; return self @@ -1210,7 +1239,7 @@ impl Instance { } if plannable { - self.check_sql_permission(&stmt, &query_ctx).await?; + let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?; let plan = self .query_engine @@ -1653,6 +1682,33 @@ impl MetricDiscoveryVisitor { } } + fn walk(exprs: &[promql_parser::parser::Expr], current_schema: String) -> Self { + let mut visitor = Self::new(current_schema); + for expr in exprs { + let _ = walk_expr(&mut visitor, expr); + } + visitor + } + + /// The tables discovery adds to the statically named ones of a query whose table extraction + /// is unresolved, or `None` when something other than discovery left it unresolved. + fn discovery_targets( + &self, + scope: &MetricDiscoveryScope, + ) -> Option> { + if !self.needs_discovery || !self.all_unresolved_are_discoverable { + return None; + } + match scope { + MetricDiscoveryScope::Allowed(allowed) => Some(allowed.iter().cloned().collect()), + // The named tables alone, because a selector that cannot be resolved statically is + // what left the query unresolved: the complete extraction would answer "no tables", + // dropping the named ones that the same query also reads. + MetricDiscoveryScope::Unrestricted => Some(Vec::new()), + MetricDiscoveryScope::Unavailable => None, + } + } + /// The planner reads the info table this selector stands for and never discovers with it, so /// it must not authorize a schema here. A shape the table extractor leaves unresolved keeps /// the whole expression unresolved. @@ -1741,6 +1797,26 @@ impl Instance { expr: &promql_parser::parser::Expr, query_ctx: &mut QueryContextRef, ) -> server_error::Result<()> { + self.prepare_metric_discovery_scope_with( + std::slice::from_ref(expr), + PermissionReq::Action(PROMQL_QUERY), + query_ctx, + ) + .await + .or_else(|error| match error { + Error::Permission { source, .. } => Err(source).context(AuthSnafu), + error => Err(BoxedError::new(error)).context(ExecuteQuerySnafu), + }) + } + + /// [`Self::prepare_metric_discovery_scope`] for the expressions one request evaluates, keeping + /// each discovered table that `req` may read. + async fn prepare_metric_discovery_scope_with( + &self, + exprs: &[promql_parser::parser::Expr], + req: PermissionReq<'_>, + query_ctx: &mut QueryContextRef, + ) -> Result<()> { // Discovery scope is read by the native PromQL route only, so a query that does not ask // for it pays nothing here beyond resolving the switch: the value is read through the // query engine's own resolver, which takes what the query states (a request hint, or the @@ -1755,7 +1831,7 @@ impl Instance { .experimental_native_promql(), ) .map_err(BoxedError::new) - .context(ExecuteQuerySnafu)?; + .context(ExternalSnafu)?; if !native_requested { Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted); return Ok(()); @@ -1765,8 +1841,7 @@ impl Instance { Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted); return Ok(()); } - let mut visitor = MetricDiscoveryVisitor::new(query_ctx.current_schema()); - let _ = walk_expr(&mut visitor, expr); + let visitor = MetricDiscoveryVisitor::walk(exprs, query_ctx.current_schema()); if !visitor.needs_discovery { return Ok(()); } @@ -1778,8 +1853,7 @@ impl Instance { .tables(query_ctx.current_catalog(), &schema, Some(query_ctx)) .try_collect::>() .await - .map_err(BoxedError::new) - .context(ExecuteQuerySnafu)?; + .context(CatalogSnafu)?; tables.sort_by_key(|table| table.table_info().name.clone()); for table in tables { let info = table.table_info(); @@ -1796,16 +1870,12 @@ impl Instance { &schema, info.name.as_str(), ); - match checker - .as_ref() - .check_permission_with_table_targets( - query_ctx.current_user(), - PermissionReq::Action(PROMQL_QUERY), - PermissionTableTargets::resolved(vec![target.clone()]), - Some(schema.as_str()), - ) - .context(AuthSnafu) - { + match checker.as_ref().check_permission_with_table_targets( + query_ctx.current_user(), + req.clone(), + PermissionTableTargets::resolved(vec![target.clone()]), + Some(schema.as_str()), + ) { Ok(_) => { allowed.insert(target); } @@ -1818,7 +1888,7 @@ impl Instance { Err(error) if error.status_code() == common_error::status_code::StatusCode::PermissionDenied => {} - Err(error) => return Err(error), + Err(error) => return Err(error).context(PermissionSnafu), } } } @@ -1908,28 +1978,17 @@ impl PrometheusHandler for Instance { Self::validate_metric_discovery_scope(parsed_expr, query_ctx.metric_discovery_scope())?; let mut targets = self.prom_queries_permission_targets(std::slice::from_ref(&query), &query_ctx)?; - if matches!(targets, PermissionTableTargets::Unresolved) { - let mut visitor = MetricDiscoveryVisitor::new(query_ctx.current_schema()); - let _ = walk_expr(&mut visitor, parsed_expr); - if visitor.needs_discovery && visitor.all_unresolved_are_discoverable { - match query_ctx.metric_discovery_scope() { - MetricDiscoveryScope::Allowed(allowed) => { - let mut resolved = - self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?; - resolved.extend(allowed.iter().cloned()); - targets = PermissionTableTargets::resolved(resolved); - } - // The partial answer, because a selector that cannot be resolved statically - // is what brought the query here: the complete one would answer "no tables", - // dropping the named ones that the same query also reads. - MetricDiscoveryScope::Unrestricted => { - targets = PermissionTableTargets::resolved( - self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?, - ); - } - MetricDiscoveryScope::Unavailable => {} - } - } + if matches!(targets, PermissionTableTargets::Unresolved) + && let Some(discovered) = MetricDiscoveryVisitor::walk( + std::slice::from_ref(parsed_expr), + query_ctx.current_schema(), + ) + .discovery_targets(query_ctx.metric_discovery_scope()) + { + let mut resolved = + self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?; + resolved.extend(discovered); + targets = PermissionTableTargets::resolved(resolved); } self.check_query_target_permission(targets, &query_ctx) .await?; @@ -6615,6 +6674,119 @@ mod tests { Ok(()) } + /// TQL discovers metrics as the Prometheus handler does: bounded by the tables the statement's + /// own request may read, and that scope reaches planning. A table the statement names is still + /// checked by name. + #[tokio::test] + async fn test_tql_discovery_is_bounded_by_the_statement_grants() -> TestResult<()> { + let plugins = Plugins::new(); + plugins.insert::(Arc::new(RejectUnresolvedPermissionChecker)); + let instance = test_instance_with_plugins_and_metric_names( + test_logical_table(1024, "denied")?, + test_logical_table(1025, "target")?, + plugins, + None, + ) + .await?; + let ctx = test_query_ctx(1); + ctx.configuration_parameter() + .set_query_option(NATIVE_PROMQL_OPTION, "true") + .unwrap(); + + for sql in [ + r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#, + r#"TQL EXPLAIN (0, 10, '5s') sum({__name__=~".+"})"#, + r#"WITH t AS (TQL EVAL (0, 10, '5s') {__name__=~".+"}) SELECT * FROM t"#, + ] { + let planning_ctx = instance + .check_sql_permission(&parse_one_sql(sql), &ctx) + .await + .unwrap(); + assert_eq!( + vec!["target".to_string()], + allowed_tables(planning_ctx.metric_discovery_scope()), + "{sql}" + ); + } + + let err = instance + .check_sql_permission( + &parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"} + denied"#), + &ctx, + ) + .await + .unwrap_err(); + assert_eq!(StatusCode::PermissionDenied, err.status_code()); + + Ok(()) + } + + /// A TQL statement discovers only the tables its own SQL request may read, even where a + /// PromQL grant would also allow one: the HTTP action must not widen what TQL reads. + #[tokio::test] + async fn test_tql_discovery_checks_the_statement_request() -> TestResult<()> { + struct PromqlOnlyDenied; + + impl PermissionChecker for PromqlOnlyDenied { + fn check_permission( + &self, + _user_info: UserInfoRef, + _req: PermissionReq, + ) -> auth::error::Result { + Ok(PermissionResp::Allow) + } + + fn check_permission_with_table_targets( + &self, + _user_info: UserInfoRef, + req: PermissionReq, + targets: PermissionTableTargets, + _current_schema: Option<&str>, + ) -> auth::error::Result { + let reject = match targets { + PermissionTableTargets::Unresolved => true, + PermissionTableTargets::Resolved(targets) => { + matches!(req, PermissionReq::SqlStatement(_)) + && targets.iter().any(|target| target.table == "denied") + } + }; + Ok(if reject { + PermissionResp::Reject + } else { + PermissionResp::Allow + }) + } + } + + let plugins = Plugins::new(); + plugins.insert::(Arc::new(PromqlOnlyDenied)); + let instance = test_instance_with_plugins_and_metric_names( + test_logical_table(1024, "denied")?, + test_logical_table(1025, "target")?, + plugins, + None, + ) + .await?; + let ctx = test_query_ctx(1); + ctx.configuration_parameter() + .set_query_option(NATIVE_PROMQL_OPTION, "true") + .unwrap(); + + let planning_ctx = instance + .check_sql_permission( + &parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#), + &ctx, + ) + .await + .unwrap(); + assert_eq!( + vec!["target".to_string()], + allowed_tables(planning_ctx.metric_discovery_scope()) + ); + + Ok(()) + } + struct CountingCatalogManager { inner: Arc, table_calls: atomic::AtomicUsize, diff --git a/src/query/src/planner.rs b/src/query/src/planner.rs index 275dad2cc9e..5b73e9ef0a4 100644 --- a/src/query/src/planner.rs +++ b/src/query/src/planner.rs @@ -72,7 +72,8 @@ pub trait LogicalPlanner: Send + Sync { /// 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. + /// existing planner's columns on either route, as a TQL CTE does. A selector that names no metric + /// has no existing columns and publishes the native route's own. async fn plan_relation( &self, stmt: &QueryStatement, @@ -238,6 +239,53 @@ fn contains_native_fused(plan: &LogicalPlan) -> bool { .any(|input| contains_native_fused(input)) } +/// Whether `expr` holds a selector that names no metric and is answered by discovering metric +/// tables. The label selector of `info` names no metric either, but it stands for the info table +/// rather than a discovery. +fn discovers_any_metric(expr: &promql_parser::parser::Expr) -> bool { + use promql_parser::parser::Expr as PromExpr; + + #[derive(Default)] + struct Visitor { + discovers: bool, + /// Addresses of `info` label selectors, compared only. + info_label_selectors: Vec, + } + + impl promql_parser::util::ExprVisitor for Visitor { + type Error = std::convert::Infallible; + + fn pre_visit(&mut self, expr: &PromExpr) -> std::result::Result { + match expr { + PromExpr::Call(call) if call.func.name == "info" => { + if let Some(PromExpr::VectorSelector(labels)) = + call.args.args.get(1).map(|labels| labels.as_ref()) + { + self.info_label_selectors + .push(std::ptr::from_ref(labels) as usize); + } + } + PromExpr::VectorSelector(selector) + if !self + .info_label_selectors + .contains(&(std::ptr::from_ref(selector) as usize)) => + { + self.discovers |= crate::promql::planner::discovers_metric_name(selector); + } + PromExpr::MatrixSelector(selector) => { + self.discovers |= crate::promql::planner::discovers_metric_name(&selector.vs); + } + _ => {} + } + Ok(!self.discovers) + } + } + + let mut visitor = Visitor::default(); + let _ = promql_parser::util::walk_expr(&mut visitor, expr); + visitor.discovers +} + /// Whether `schema` is a series frame's declaration, which describes the columns below it. fn publishes_series_frame(schema: &DFSchema) -> bool { schema @@ -876,6 +924,12 @@ impl DfLogicalPlanner { // this is the existing plan, which already publishes the existing columns. return Ok(plan); } + // The existing planner refuses a selector that names no metric, so the native answer's own + // columns are the relation's. A series frame is not a table SQL reads, so it still goes to + // the existing planner, which refuses it. + if discovers_any_metric(&eval.expr) && !publishes_series_frame(plan.schema()) { + 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 diff --git a/src/sql/src/util.rs b/src/sql/src/util.rs index 59e7379ec8f..21b193d8365 100644 --- a/src/sql/src/util.rs +++ b/src/sql/src/util.rs @@ -234,6 +234,42 @@ pub fn extract_tables_from_statement_checked( extract_tables_from_statement(stmt, &mut names).then_some(names.into_iter()) } +/// Extracts the tables referenced by a [`Statement`] that can be resolved statically, +/// ignoring the ones that cannot. +pub fn extract_tables_from_statement_partial(stmt: &Statement) -> Vec { + let mut names = HashSet::new(); + extract_tables_from_statement(stmt, &mut names); + names.into_iter().collect() +} + +/// The PromQL expressions a query statement evaluates through TQL: its own, or those of its TQL +/// CTEs, looking through `EXPLAIN`. Returns `None` when one of them does not parse. +pub fn extract_tql_exprs_from_statement(stmt: &Statement) -> Option> { + fn parse(tql: &Tql) -> Option { + let promql = match tql { + Tql::Eval(eval) => &eval.query, + Tql::Explain(explain) => &explain.query, + Tql::Analyze(analyze) => &analyze.query, + }; + promql_parser::parser::parse(promql).ok() + } + + match stmt { + Statement::Tql(tql) => parse(tql).map(|expr| vec![expr]), + Statement::Query(query) => query + .hybrid_cte + .iter() + .flat_map(|hybrid_cte| &hybrid_cte.cte_tables) + .filter_map(|cte| match &cte.content { + CteContent::Tql(tql) => Some(parse(tql)), + CteContent::Sql(_) => None, + }) + .collect(), + Statement::Explain(explain) => extract_tql_exprs_from_statement(&explain.statement), + _ => Some(Vec::new()), + } +} + fn extract_tables_from_statement(stmt: &Statement, names: &mut HashSet) -> bool { match stmt { Statement::Tql(tql) => extract_tables_from_tql(tql, names), diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 32ce428d28d..a7043766b06 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -42,7 +42,7 @@ use query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY; use rstest::rstest; use rstest_reuse::apply; use servers::query_handler::sql::SqlQueryHandler; -use session::context::{MetricDiscoveryScope, QueryContext}; +use session::context::QueryContext; use sql::ast::{Ident, ObjectName, ObjectNamePart}; use sql::statements::create::CreateView; use sql::statements::statement::Statement as SqlStatement; @@ -2396,6 +2396,59 @@ async fn native_promql_clamp_aggregates_execute_on_native_segments() { } } +/// TQL answers a selector that names no metric as the Prometheus handler does, with no scope +/// supplied by the caller: authorizing the statement prepares it. +#[tokio::test(flavor = "multi_thread")] +async fn native_tql_discovers_metrics_like_the_prometheus_handler() { + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = + native_test_instance(GreptimeDbStandaloneBuilder::new("native_tql_discovery")).await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE tql_disc_phy (ts TIMESTAMP TIME INDEX, v DOUBLE) \ + ENGINE=metric WITH (\"physical_metric_table\" = \"\"); \ + CREATE TABLE tql_disc_a (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'tql_disc_phy'); \ + CREATE TABLE tql_disc_b (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'tql_disc_phy'); \ + INSERT INTO tql_disc_a (host, ts, v) VALUES ('a', 0, 2); \ + INSERT INTO tql_disc_b (host, ts, v) VALUES ('b', 0, 8)", + QueryContext::arc(), + ) + .await; + + for query in [ + r#"{__name__=~"tql_disc_a|tql_disc_b"}"#, + r#"{host=~"a|b"}"#, + r#"sum by (__name__) ({host=~"a|b"})"#, + ] { + observer.clear(); + let output = + native_tql_output(&instance, &format!("TQL EVAL (0, 0, '1s') {query}"), true).await; + assert_native_rows_plan(&observer); + let rows = native_rows(output, None).await; + assert_eq!(2, rows.len(), "{query}: {rows:?}"); + let expected = native_rows(discovery_query(&instance, query).await, None).await; + assert_eq!(expected, rows, "{query}"); + } + + let output = native_tql_output( + &instance, + r#"WITH t AS (TQL EVAL (0, 0, '1s') {host=~"a|b"}) SELECT * FROM t"#, + true, + ) + .await; + let rows = rows_batches(output) + .await + .iter() + .map(|batch| batch.num_rows()) + .sum::(); + assert_eq!(2, rows); +} + /// 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 @@ -2431,25 +2484,11 @@ async fn native_promql_rows_name_each_row_after_its_metric() { // right side's series, so each row keeps the labels its own selector read - `host` among them - // and reports the name of the metric it came from. // A selector that names no metric is answered from the metric tables discovery is authorized to - // read, and a caller prepares that scope for the statement: the Prometheus handler passes the - // schema's tables, and this fixture passes its two. Without a scope the planner declines the - // selector, so the statement would keep the existing plan, which refuses it outright. + // read; authorizing the statement prepares that scope. let scoped = || { let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([ - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_name_demo".to_string(), - ), - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_name_other".to_string(), - ), - ])); Arc::new(ctx) }; for (query, expected, native) in [ @@ -3001,24 +3040,11 @@ async fn native_promql_field_selector_over_no_table_answers_empty() { ) .await; // A selector that names no metric is answered from the metric tables discovery is authorized to - // read, which the caller states: this fixture passes its two, and the selector's own name - // matcher is what leaves it with no table at all. + // read, and the selector's own name matcher is what leaves it with no table at all. let scoped = || { let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([ - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_fs_demo".to_string(), - ), - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_fs_other".to_string(), - ), - ])); Arc::new(ctx) }; for (query, answered) in [ @@ -7315,14 +7341,11 @@ async fn native_promql_rewrites_the_metric_name() { } }; // A nameless selector is answered by enumerating the schema's metric tables, which the - // frontend's PromQL entry point bounds by the caller's grants before it plans. A SQL - // `TQL EVAL` statement prepares no such scope, so the test states the unrestricted one a - // caller with every grant would get. + // frontend bounds by the caller's grants before it plans. let discovery_ctx = Arc::new({ let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, 4.to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true"); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted); ctx }); let run_discovery = |expr: &str, range: &str| { @@ -7639,12 +7662,8 @@ async fn native_promql_executes_fused_node_and_matches_legacy() { } } -/// `promql` over `start..=end` at `step`, through the Prometheus handler. -/// -/// The handler is the path that authorizes and plans a selector naming no metric: a `TQL EVAL` -/// statement reaches the planner through the statement executor instead, and that path prepares no -/// discovery scope, so it keeps declining such a selector. Its times are Prometheus timestamps, so -/// a bare number is a count of seconds. +/// `promql` over `start..=end` at `step`, through the Prometheus handler. Its times are Prometheus +/// timestamps, so a bare number is a count of seconds. async fn promql_output( instance: &Arc, promql: &str, @@ -9434,16 +9453,9 @@ async fn native_promql_zero_match_or_real_tql() { (r#"{__name__=~"no_such_metric_.+"} or alpha_total"#, 0), (r#"alpha_total or {__name__=~"no_such_metric_.+"}"#, 1), ] { - // TQL does not prepare discovery scope itself; provide the same authorized scope that - // the Prometheus handler would provide, without comparing to the unsupported legacy path. let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "alpha_total".to_string(), - )])); let sql = format!("TQL EVAL (0, 2, '1s', '1s') {query}"); observer.clear(); let output = instance @@ -9503,16 +9515,9 @@ async fn native_promql_zero_match_or_real_tql() { r#"{__name__=~"no_such_metric_.+"} + on(host) alpha_total"#, r#"alpha_total * on(host) group_left {__name__=~"no_such_metric_.+"}"#, ] { - // TQL does not prepare discovery scope itself; provide the same authorized scope that - // the Prometheus handler would provide, without comparing to the unsupported legacy path. let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "alpha_total".to_string(), - )])); let sql = format!("TQL EVAL (0, 2, '1s', '1s') {query}"); observer.clear(); let output = instance @@ -9661,23 +9666,9 @@ async fn native_promql_zero_match_takes_the_layout_of_its_operand() { }; let mut answers = Vec::new(); for (query, empty_selectors) in queries { - // TQL does not prepare discovery scope itself; provide the same authorized scope that the - // Prometheus handler would provide, without comparing to the unsupported legacy path. let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([ - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_local_wide".to_string(), - ), - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_local_narrow".to_string(), - ), - ])); let sql = format!("TQL EVAL (1, 2, '1s', '1s') {query}"); observer.clear(); let output = instance @@ -9737,18 +9728,6 @@ async fn native_promql_zero_match_takes_the_layout_of_its_operand() { let mut ctx = QueryContext::with_db_name(None); ctx.set_extension(QUERY_PARALLELISM_HINT, "4".to_string()); ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "true".to_string()); - ctx.set_metric_discovery_scope(MetricDiscoveryScope::allowed([ - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_local_wide".to_string(), - ), - ( - DEFAULT_CATALOG_NAME.to_string(), - DEFAULT_SCHEMA_NAME.to_string(), - "native_local_narrow".to_string(), - ), - ])); let sql = format!("TQL EVAL (1, 2, '1s', '1s') {query}"); observer.clear(); let output = instance @@ -9781,12 +9760,8 @@ async fn native_promql_zero_match_takes_the_layout_of_its_operand() { ); } -/// `promql` evaluated at one instant through the Prometheus handler, which is the path that -/// authorizes and plans a discovered selector. -/// -/// A `TQL EVAL` statement reaches the planner through the statement executor instead, and that path -/// prepares no discovery scope, so it keeps declining a selector that names no metric. The trait is -/// named in full because this module already calls the SQL handler's `do_query`. +/// `promql` evaluated at one instant through the Prometheus handler. The trait is named in full +/// because this module already calls the SQL handler's `do_query`. async fn discovery_query(instance: &Arc, promql: &str) -> Output { let query = PromQuery { query: promql.to_string(),