From 3b97e3c26bf8b2647bd236fb7506121ff4a586e9 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 23 Nov 2026 13:26:25 -0800 Subject: [PATCH 1/7] Resolve Yardstick projection aliases and group-all measure grain --- sqlctx-rs/src/sql/rewriter/yardstick.rs | 62 +++++++++++++++++-- sqlctx/sql/query_rewriter.py | 52 +++++++++++++++- .../queries/test_yardstick_measures_replay.py | 24 +++++++ 3 files changed, 133 insertions(+), 5 deletions(-) diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index d1ba1bcdb..baa32914e 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -6,14 +6,14 @@ use std::collections::{HashMap, HashSet}; -use super::{parse_sql_with_dialect, table_name_and_alias, QueryRewriter}; +use super::{QueryRewriter, parse_sql_with_dialect, table_name_and_alias}; use crate::core::MetricType; use crate::error::{Result, SqlctxError}; use crate::semantic_input::dialects; use polyglot_sql::dialects::{DialectImpl, SnowflakeDialect}; use polyglot_sql::expressions::{GroupBy, Identifier, Select, Where}; use polyglot_sql::tokens::{Token, TokenType, Tokenizer}; -use polyglot_sql::{generate as polyglot_generate, Dialect, DialectType, Expression}; +use polyglot_sql::{Dialect, DialectType, Expression, generate as polyglot_generate}; use serde_json::Value; #[derive(Clone)] @@ -562,6 +562,40 @@ impl Lowerer<'_, '_> { }); } } + if select + .group_by + .as_ref() + .is_some_and(|group| group.all == Some(true)) + && !select + .expressions + .iter() + .any(|projection| matches!(projection, Expression::Star(_))) + { + let mut groups = Vec::new(); + for projection in &select.expressions { + let expression = match projection { + Expression::Alias(alias) => &alias.this, + other => other, + }; + if !contains_call(expression)? + && !has_aggregate_semantics(&encode(expression)?) + && !matches!( + expression, + Expression::Literal(_) | Expression::Null(_) | Expression::Boolean(_) + ) + { + groups.push(expression.clone()); + } + } + if !groups.is_empty() { + select.group_by = Some(GroupBy { + expressions: groups, + all: None, + totals: false, + comments: vec![], + }); + } + } if let Some(group) = &mut select.group_by { for expression in &mut group.expressions { if let Ok(index) = self.sql(expression)?.parse::() { @@ -616,6 +650,18 @@ impl Lowerer<'_, '_> { } } } + let mut having_calls = HashSet::new(); + if let Some(having) = &select.having { + map_columns(&mut encode(&having.this)?, &mut |node| { + if let Some((None, name)) = reference(&node) { + if scope_calls.contains(&name) { + having_calls.insert(name); + } + } + Ok(node) + })?; + } + let no_aliases = HashMap::new(); let mut replacements = HashMap::new(); for name in &scope_calls { let call = &self.calls[name]; @@ -636,7 +682,11 @@ impl Lowerer<'_, '_> { &groups, select.where_clause.as_ref(), single, - &context_aliases, + if having_calls.contains(name) { + &no_aliases + } else { + &context_aliases + }, &mut HashSet::new(), &mut correlated, )?; @@ -1139,7 +1189,11 @@ impl Lowerer<'_, '_> { || contains_kind(&encode(&expression)?, "window_function") { let message = name.replace('\'', "''"); - format!("(SELECT CASE WHEN COUNT(*) = 0 THEN NULL WHEN COUNT(DISTINCT __ys_window_value) = 1 THEN MIN(__ys_window_value) ELSE error('Window measure {message} returned multiple values for the evaluation context') END FROM (SELECT _inner.*, {aggregate} AS __ys_window_value FROM {source} AS _inner{}) AS _inner{})", predicate_clause(&base), predicate_clause(&post)) + format!( + "(SELECT CASE WHEN COUNT(*) = 0 THEN NULL WHEN COUNT(DISTINCT __ys_window_value) = 1 THEN MIN(__ys_window_value) ELSE error('Window measure {message} returned multiple values for the evaluation context') END FROM (SELECT _inner.*, {aggregate} AS __ys_window_value FROM {source} AS _inner{}) AS _inner{})", + predicate_clause(&base), + predicate_clause(&post) + ) } else { format!( "(SELECT {aggregate} FROM {source} AS _inner{})", diff --git a/sqlctx/sql/query_rewriter.py b/sqlctx/sql/query_rewriter.py index 9a38fbae6..9a46aa6ed 100644 --- a/sqlctx/sql/query_rewriter.py +++ b/sqlctx/sql/query_rewriter.py @@ -3683,6 +3683,34 @@ def _rewrite_yardstick_select_scope( if not scope_placeholders: return select_scope + if single_model_scope and self.dialect == "duckdb": + model = self.graph.get_model(source_models[default_alias]) + known_columns = {dimension.name.lower() for dimension in model.dimensions} + measure_aliases: dict[str, exp.Expression] = {} + for projection in select_scope.expressions: + expression = projection.this if isinstance(projection, exp.Alias) else projection + replacements = { + id(column): measure_aliases[column.name.lower()] + for column in self._columns_without_nested_scopes(expression) + if not column.table + and column.name.lower() in measure_aliases + and column.name.lower() not in known_columns + } + if replacements: + expanded = expression.transform( + lambda node: replacements[id(node)].copy() if id(node) in replacements else node, + copy=False, + ) + if isinstance(projection, exp.Alias): + projection.set("this", expanded) + expression = expanded + if isinstance(projection, exp.Alias): + alias = projection.alias.lower() + if self._expression_contains_yardstick_placeholder(expression, scope_placeholders): + measure_aliases[alias] = expression + else: + measure_aliases.pop(alias, None) + select_scope = self._expand_yardstick_dimension_references( select_scope, source_models=source_models, @@ -3747,6 +3775,22 @@ def _rewrite_yardstick_select_scope( if group_clause: self._resolve_yardstick_group_ordinals(group_clause, select_scope.expressions) if group_clause and default_alias and single_model_scope: + model = self.graph.get_model(source_models[default_alias]) + group_aliases = { + item.alias.lower(): item.this for item in select_scope.expressions if isinstance(item, exp.Alias) + } + group_clause.set( + "expressions", + [ + group_aliases[expr.name.lower()].copy() + if isinstance(expr, exp.Column) + and not expr.table + and expr.name.lower() in group_aliases + and not model.get_dimension(expr.name) + else expr + for expr in group_clause.expressions + ], + ) group_clause.set( "expressions", [ @@ -3775,13 +3819,19 @@ def _rewrite_yardstick_select_scope( signature = self._expr_signature_without_tables(projection.this) projection_aliases[signature] = projection.alias + having = select_scope.args.get("having") + having_placeholders = ( + {column.name for column in self._columns_without_nested_scopes(having) if not column.table} + if having + else set() + ) replacement_sql: dict[str, str] = {} for placeholder in scope_placeholders: replacement_sql[placeholder] = self._build_yardstick_call_sql( call=call_map[placeholder], source_models=source_models, group_expressions=group_expressions, - projection_aliases=projection_aliases, + projection_aliases={} if placeholder in having_placeholders else projection_aliases, outer_where=outer_where, default_alias=default_alias, single_model_scope=single_model_scope, diff --git a/tests/queries/test_yardstick_measures_replay.py b/tests/queries/test_yardstick_measures_replay.py index c00607cca..45cef3989 100644 --- a/tests/queries/test_yardstick_measures_replay.py +++ b/tests/queries/test_yardstick_measures_replay.py @@ -859,6 +859,30 @@ def test_yardstick_upstream_sql_replay(): _replay_yardstick_sql_test(path) +def test_replay_binds_measure_and_grouping_projection_aliases(tmp_path): + path = tmp_path / "aliases.test" + path.write_text( + """statement ok +CREATE TABLE sales(region VARCHAR, amount INT); + +statement ok +INSERT INTO sales VALUES ('N', 10), ('N', 20), ('S', 50); + +statement ok +CREATE VIEW sales_v AS SELECT region, SUM(amount) AS MEASURE revenue, + COUNT(*) AS MEASURE orders FROM sales; + +query TIIR rowsort +SELECT LOWER(region) AS area, AGGREGATE(revenue) AS r, AGGREGATE(orders) AS n, r/n AS mean +FROM sales_v GROUP BY area; +---- +n\t30\t2\t15.0 +s\t50\t1\t50.0 +""" + ) + _replay_yardstick_sql_test(path) + + def test_parse_statement_record_preserves_batch_and_unterminated_error(tmp_path): path = tmp_path / "batch.test" path.write_text( From f85bd459ebc49a9fb36eb2c1defb2e5f26b59d72 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 23 Nov 2026 13:32:45 -0800 Subject: [PATCH 2/7] Fix Yardstick star exclusions and quoted AT predicate literals --- sqlctx/sql/query_rewriter.py | 71 ++++++++++++++++++- .../queries/test_yardstick_measures_replay.py | 36 ++++++++++ 2 files changed, 105 insertions(+), 2 deletions(-) diff --git a/sqlctx/sql/query_rewriter.py b/sqlctx/sql/query_rewriter.py index 9a46aa6ed..6b72e009a 100644 --- a/sqlctx/sql/query_rewriter.py +++ b/sqlctx/sql/query_rewriter.py @@ -3578,6 +3578,8 @@ def _contains_implicit_yardstick_measure_query(self, parsed: exp.Select) -> bool candidate_expressions.extend(order_expr.this for order_expr in order_clause.expressions) for candidate_expr in candidate_expressions: + if candidate_expr.is_star: + continue for column in candidate_expr.find_all(exp.Column): if self._resolve_implicit_yardstick_measure_reference( column, @@ -3711,6 +3713,7 @@ def _rewrite_yardstick_select_scope( else: measure_aliases.pop(alias, None) + select_scope = self._expand_yardstick_measure_exclusions(select_scope, source_models, default_alias) select_scope = self._expand_yardstick_dimension_references( select_scope, source_models=source_models, @@ -4471,6 +4474,10 @@ def maybe_replace_column(node: exp.Expression) -> exp.Expression: rewritten_projections: list[exp.Expression] = [] for projection in rewritten.expressions: + if projection.is_star: + rewritten_projections.append(projection) + continue + if isinstance(projection, exp.Alias): projection.set("this", projection.this.transform(maybe_replace_column)) rewritten_projections.append(projection) @@ -4556,6 +4563,60 @@ def _resolve_yardstick_dimension_expression( ) return expr, column.name + def _expand_yardstick_measure_exclusions( + self, select: exp.Select, source_models: dict[str, str], default_alias: str | None + ) -> exp.Select: + """Expand an explicitly declared view when its star excludes logical measures.""" + if self.dialect != "duckdb" or not default_alias: + return select + + model = self.graph.get_model(source_models[default_alias]) + view_sql = (model.metadata or {}).get("yardstick", {}).get("view_sql") + if not view_sql: + return select + + projections = [] + metrics = {metric.name.lower() for metric in model.metrics} + dims = {dimension.name.lower() for dimension in model.dimensions} + explicit_view = None + for projection in select.expressions: + star = projection.this if isinstance(projection, exp.Column) else projection + if ( + not isinstance(star, exp.Star) + or (isinstance(projection, exp.Column) and projection.table != default_alias) + or not star.args.get("except_") + or star.args.get("replace") + or star.args.get("rename") + ): + projections.append(projection) + continue + + excludes = {item.name.lower() for item in star.args["except_"]} + if not metrics or metrics - excludes or len(excludes) != len(star.args["except_"]): + projections.append(projection) + continue + + if explicit_view is None: + view = sqlglot.parse_one(view_sql, read=self.dialect) + explicit_view = not any(item.is_star for item in view.expressions) + if not explicit_view: + projections.append(projection) + continue + + unknown = excludes - (dims | metrics) + if unknown: + unknown_name = sorted(unknown)[0] + raise ValueError(f'Binder Error: Column "{unknown_name}" in EXCLUDE list not found in {default_alias}') + + visible = [dimension for dimension in model.dimensions if dimension.name.lower() not in excludes] + if not visible: + projections.append(projection) + continue + projections.extend(exp.column(dimension.name, table=default_alias, quoted=True) for dimension in visible) + + select.set("expressions", projections) + return select + def _expand_yardstick_dimension_references( self, select_scope: exp.Select, @@ -4581,6 +4642,10 @@ def replace_columns(node: exp.Expression) -> exp.Expression: rewritten = select_scope.copy() rewritten_projections: list[exp.Expression] = [] for projection in rewritten.expressions: + if projection.is_star: + rewritten_projections.append(projection) + continue + if isinstance(projection, exp.Alias): projection.set("this", projection.this.transform(replace_columns)) rewritten_projections.append(projection) @@ -5040,7 +5105,7 @@ def _split_compound_yardstick_modifier(self, modifier_sql: str) -> list[str]: if not tokens: return [] - modifier_heads = {"ALL", "SET", "WHERE", "VISIBLE"} + modifier_heads = {TokenType.ALL, TokenType.SET, TokenType.WHERE} split_indexes = [0] depth = 0 @@ -5053,7 +5118,9 @@ def _split_compound_yardstick_modifier(self, modifier_sql: str) -> list[str]: if idx == 0 or depth != 0: continue - if token.text.upper() in modifier_heads: + if token.token_type in modifier_heads or ( + token.token_type == TokenType.VAR and token.text.upper() == "VISIBLE" + ): split_indexes.append(idx) parts: list[str] = [] diff --git a/tests/queries/test_yardstick_measures_replay.py b/tests/queries/test_yardstick_measures_replay.py index 45cef3989..2721b4846 100644 --- a/tests/queries/test_yardstick_measures_replay.py +++ b/tests/queries/test_yardstick_measures_replay.py @@ -1131,3 +1131,39 @@ def test_definition_coverage_is_corpus_wide_without_dropping_plain_sql(tmp_path) _replay_yardstick_sql_test(ordinary) with pytest.raises(AssertionError, match="eligible upstream corpus"): _assert_definition_corpus_matches([ordinary]) + + +@pytest.mark.parametrize("keyword", ["ALL", "SET", "WHERE", "VISIBLE"]) +def test_at_where_quoted_modifier_word(keyword): + from tests.queries.yardstick_replay_runtime import replay_runtime + + layer = SemanticLayer(connection="duckdb:///:memory:") + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + f"CREATE TABLE lexical(k VARCHAR, amount INTEGER); INSERT INTO lexical VALUES ('{keyword}', 1), ('other', 150)" + ) + runtime.execute("CREATE VIEW lexical_v AS SELECT k, SUM(amount) AS MEASURE revenue FROM lexical") + assert runtime.execute(f"SELECT AGGREGATE(revenue) AT (WHERE k = '{keyword}') FROM lexical_v") == [(1,)] + + +@pytest.mark.parametrize("star", ["*", "v.*"]) +def test_explicit_yardstick_star_can_exclude_logical_measures(star): + from tests.queries.yardstick_replay_runtime import replay_runtime + + layer = SemanticLayer(connection="duckdb:///:memory:") + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + "CREATE TABLE named(year INTEGER, region VARCHAR, amount INTEGER, revenue INTEGER); " + "INSERT INTO named VALUES (2023,'N',1,100), (2024,'S',3,200)" + ) + runtime.execute( + "CREATE VIEW named_v AS SELECT year, region, amount, SUM(amount) AS MEASURE revenue, " + "COUNT(*) AS MEASURE tally FROM named" + ) + query = ( + f"SELECT {star} EXCLUDE(amount, revenue, tally), AGGREGATE(revenue) AT (ALL) " + "FROM named_v v GROUP BY ALL ORDER BY year" + ) + assert runtime.execute(query) == [(2023, "N", 4), (2024, "S", 4)] + with pytest.raises(Exception, match="missing_column"): + runtime.execute(query.replace("amount,", "missing_column,")) From d9d20dddab71e4da8f8540a74d8d8df3c8d64e0e Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 23 Nov 2026 14:04:22 -0800 Subject: [PATCH 3/7] Evaluate Yardstick measures at each grouping-set grain --- docs/compatibility/yardstick.md | 2 +- sqlctx-rs/src/sql/rewriter/yardstick.rs | 113 ++++++++++++++---- sqlctx/sql/query_rewriter.py | 56 +++++---- tests/fixtures/sql/yardstick/measures.test | 2 +- .../queries/test_yardstick_measures_replay.py | 41 +++++++ .../queries/test_yardstick_query_rewriter.py | 3 +- 6 files changed, 163 insertions(+), 54 deletions(-) diff --git a/docs/compatibility/yardstick.md b/docs/compatibility/yardstick.md index bd356d4c3..cc30625c2 100644 --- a/docs/compatibility/yardstick.md +++ b/docs/compatibility/yardstick.md @@ -231,7 +231,7 @@ Bare measure names in non-SEMANTIC queries default to evaluating at the full tab | Explicit `GROUP BY col1, col2` | Supported | | Positional `GROUP BY 1, 2` | Supported (ordinals resolved to SELECT dimensions) | | `GROUP BY` with extra whitespace | Supported | -| `GROUP BY ROLLUP(...)` | Supported | +| `GROUP BY ROLLUP(...)`, `CUBE(...)`, or `GROUPING SETS (...)` | Supported on DuckDB. Measures evaluate at each grouping set’s grain; a subtotal is distinct from a grouped NULL value. | | Omitted `GROUP BY` (grouping inferred from SELECT dimensions) | Supported | --- diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index baa32914e..b065d04db 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -929,8 +929,8 @@ impl Lowerer<'_, '_> { let mut context = Vec::new(); for group in groups { let mut expanded = Vec::new(); - expand_groups(group, &mut expanded)?; - for group in expanded { + expand_groups(group, false, &mut expanded)?; + for (group, optional) in expanded { let mut columns = Vec::new(); map_columns(&mut encode(&group)?, &mut |node| { if let Some(reference) = reference(&node) { @@ -957,16 +957,21 @@ impl Lowerer<'_, '_> { continue; } let signature = self.signature(group.clone())?; - if context.iter().any(|(key, _, _)| key == &signature) { - continue; - } let aliases = columns .iter() .filter_map(|(table, _)| table.as_deref()) .collect::>(); let inner = self.remap(group.clone(), &aliases, "_inner", single)?; let mut outer = self.remap(group, &[model_name], alias, single)?; - if let Some(output_alias) = context_aliases.get(&signature) { + // A subtotal omits this expression, rather than grouping its NULL values. + // GROUPING must refer to the group expression, not its output alias. + let grouping = optional.then(|| self.sql(&outer)).transpose()?; + if context.iter().any(|(key, _, _, existing_grouping)| { + key == &signature && existing_grouping == &grouping + }) { + continue; + } + if let Some(output_alias) = context_aliases.get(&signature).filter(|_| !optional) { // SELECT * imports can expose physical grouping columns // without declaring dimensions. An unqualified output // alias with that same name would bind to the inner source @@ -988,12 +993,12 @@ impl Lowerer<'_, '_> { outer = Expression::Identifier(Identifier::new(output_alias)); } } - context.push((signature, self.sql(&inner)?, self.sql(&outer)?)); + context.push((signature, self.sql(&inner)?, self.sql(&outer)?, grouping)); } } let mut current = context .iter() - .map(|(key, _, _)| key.clone()) + .map(|(key, _, _, _)| key.clone()) .collect::>(); if let Some(predicate) = outer_where { self.fixed_context(&predicate.this, &mut current)?; @@ -1026,7 +1031,7 @@ impl Lowerer<'_, '_> { "ALL" => { for target in self.all_targets(body)? { let key = self.signature(target)?; - active.retain(|(signature, _, _)| signature != &key); + active.retain(|(signature, _, _, _)| signature != &key); removed.insert(key); } } @@ -1064,7 +1069,7 @@ impl Lowerer<'_, '_> { Ok(node) })?; if self_reference - && !context.iter().any(|(signature, _, _)| signature == &key) + && !context.iter().any(|(signature, _, _, _)| signature == &key) { return Err(SqlctxError::YardstickBinding(format!( "AT ({modifier}) references {dimension}, but the query does not group by {dimension}. Add {dimension} to SELECT/GROUP BY or use a constant SET value." @@ -1077,7 +1082,7 @@ impl Lowerer<'_, '_> { match expression { Expression::Eq(eq) => { let key = self.signature(eq.left.clone())?; - active.retain(|(signature, _, _)| signature != &key); + active.retain(|(signature, _, _, _)| signature != &key); if removed.contains(&key) { continue; } @@ -1119,7 +1124,7 @@ impl Lowerer<'_, '_> { if removed.contains(&key) { continue; } - active.retain(|(signature, _, _)| signature != &key); + active.retain(|(signature, _, _, _)| signature != &key); let expression = self.remap( Expression::In(in_expr), &[model_name], @@ -1163,11 +1168,13 @@ impl Lowerer<'_, '_> { base.push(self.sql(&expression)?); } let mut post = set_predicates.into_values().collect::>(); - post.extend( - active - .into_iter() - .map(|(_, inner, outer)| format!("({inner}) IS NOT DISTINCT FROM ({outer})")), - ); + post.extend(active.into_iter().map(|(_, inner, outer, grouping)| { + let equality = format!("({inner}) IS NOT DISTINCT FROM ({outer})"); + match grouping { + Some(group) => format!("GROUPING({group}) = 1 OR ({equality})"), + None => equality, + } + })); let source = model .sql .as_ref() @@ -1212,7 +1219,7 @@ impl Lowerer<'_, '_> { name: &str, call: &Call, outer_where: Option<&Where>, - active: &[(String, String, String)], + active: &[(String, String, String, Option)], where_predicates: &[String], set_predicates: &std::collections::BTreeMap, visible: bool, @@ -1267,7 +1274,7 @@ impl Lowerer<'_, '_> { return Ok(()); } let mut encoded = HashSet::new(); - for (_, inner, _) in active { + for (_, inner, _, _) in active { let expression = self.expression(inner)?; if reference(&expression).is_some() { encoded.extend(source_columns(&expression)?); @@ -1513,7 +1520,11 @@ fn has_aggregate_semantics(value: &Value) -> bool { } } -fn expand_groups(expression: &Expression, output: &mut Vec) -> Result<()> { +fn expand_groups( + expression: &Expression, + optional: bool, + output: &mut Vec<(Expression, bool)>, +) -> Result<()> { // The pinned parser represents inline ROLLUP/CUBE as ordinary functions, // but WITH ROLLUP/CUBE as the typed variants handled below. if let Expression::Function(function) = expression { @@ -1522,7 +1533,7 @@ fn expand_groups(expression: &Expression, output: &mut Vec) -> Resul .any(|name| function.name.eq_ignore_ascii_case(name)) { for child in &function.args { - expand_groups(child, output)?; + expand_groups(child, true, output)?; } return Ok(()); } @@ -1531,18 +1542,18 @@ fn expand_groups(expression: &Expression, output: &mut Vec) -> Resul let Some(fields) = value.as_object() else { return Ok(()); }; - if let Some(group) = ["rollup", "cube", "grouping_sets", "tuple"] - .iter() - .find_map(|kind| fields.get(*kind)) + if let Some((kind, group)) = ["rollup", "cube", "grouping_sets", "tuple"] + .into_iter() + .find_map(|kind| fields.get(kind).map(|group| (kind, group))) { if let Some(children) = group.get("expressions").and_then(Value::as_array) { for child in children { - expand_groups(&decode(child.clone())?, output)?; + expand_groups(&decode(child.clone())?, optional || kind != "tuple", output)?; } return Ok(()); } } - output.push(expression.clone()); + output.push((expression.clone(), optional)); Ok(()) } @@ -1651,6 +1662,56 @@ mod tests { "{sql}" ); assert!(!sql.contains("IS NOT DISTINCT FROM (product)"), "{sql}"); + assert_eq!( + sql.contains("GROUPING(o.product) = 1"), + grouping != "o.product", + "{sql}" + ); + } + } + + #[test] + fn grouping_sets_keep_visible_filters_outside_grouping_guard() { + let mut model = Model::new("orders_v", "id") + .with_table("raw_orders") + .with_metric(Metric::sum("revenue", "amount")); + model.metadata = Some(serde_json::json!({"yardstick": {}})); + let mut graph = SemanticGraph::new(); + graph.add_model(model).unwrap(); + let rewriter = QueryRewriter::new(&graph); + for grouping in [ + "ROLLUP(o.product, o.year)", + "CUBE(o.product, o.year)", + "GROUPING SETS ((o.product), (o.year), ())", + ] { + let sql = rewriter.rewrite(&format!( + "SELECT o.product, o.year, COUNT(*) AS c, AGGREGATE(o.revenue) AS vis, o.revenue AS plain FROM orders_v o WHERE o.customer <> 'Bob' GROUP BY {grouping}" + )).unwrap(); + assert_eq!(sql.matches("GROUPING(o.product) = 1").count(), 2, "{sql}"); + assert_eq!(sql.matches("GROUPING(o.year) = 1").count(), 2, "{sql}"); + assert_eq!(sql.matches("_inner.customer <> 'Bob'").count(), 1, "{sql}"); + assert!( + sql.contains("(_inner.product) IS NOT DISTINCT FROM (o.product)"), + "{sql}" + ); + } + } + + #[test] + fn optional_grouping_retains_relation_identity_and_ignores_output_aliases() { + let mut model = Model::new("orders_v", "id") + .with_table("raw_orders") + .with_dimension(crate::core::Dimension::categorical("year")) + .with_metric(Metric::count("orders")); + model.metadata = Some(serde_json::json!({"yardstick": {}})); + let mut graph = SemanticGraph::new(); + graph.add_model(model).unwrap(); + let rewriter = QueryRewriter::new(&graph); + let sql = rewriter.rewrite( + "SELECT o.year AS order_year, y.year AS joined_year, AGGREGATE(o.orders) FROM orders_v o JOIN (SELECT DISTINCT year FROM raw_orders) y ON o.year = y.year GROUP BY GROUPING SETS ((o.year), (y.year), ())" + ).unwrap(); + for qualifier in ["o", "y"] { + assert!(sql.contains(&format!("GROUPING({qualifier}.year) = 1 OR ((_inner.year) IS NOT DISTINCT FROM ({qualifier}.year))")), "{sql}"); } } } diff --git a/sqlctx/sql/query_rewriter.py b/sqlctx/sql/query_rewriter.py index 6b72e009a..d6f4cd43f 100644 --- a/sqlctx/sql/query_rewriter.py +++ b/sqlctx/sql/query_rewriter.py @@ -4872,7 +4872,10 @@ def replace_measure_refs(node: exp.Expression) -> exp.Expression: correlation_predicates: list[str] = [] for dim in active_dimensions: - correlation_predicates.append(f"({dim['inner_sql']}) IS NOT DISTINCT FROM ({dim['outer_sql']})") + equality = f"({dim['inner_sql']}) IS NOT DISTINCT FROM ({dim['outer_sql']})" + if grouping_sql := dim.get("grouping_sql"): + equality = f"(GROUPING({grouping_sql}) = 1 OR ({equality}))" + correlation_predicates.append(equality) base_predicates = list(where_modifier_predicates) if include_visible and outer_where is not None: @@ -4994,11 +4997,11 @@ def _build_yardstick_context_dimensions( ) -> list[dict[str, str]]: context_dimensions: list[dict[str, str]] = [] model = self.graph.get_model(model_name) - seen_signatures: set[str] = set() + seen_signatures: set[tuple[str, str]] = set() for raw_group_expr in group_expressions: expanded_group_expressions = self._expand_group_expression_for_yardstick_context(raw_group_expr) - for group_expr in expanded_group_expressions: + for group_expr, optional in expanded_group_expressions: outer_base_expr = group_expr.copy() expr_obj = group_expr.copy() if default_alias and single_model_scope: @@ -5027,10 +5030,14 @@ def _build_yardstick_context_dimensions( default_table="_inner" if single_model_scope else None, ) signature = self._expr_signature_without_tables(inner_base_expr) - if signature in seen_signatures: - continue - seen_signatures.add(signature) outer_sql = outer_expr.sql(dialect=self.dialect) + # GROUPING distinguishes a subtotal (dimension omitted) from + # a detail row with a real NULL grouping key. + grouping_sql = outer_sql if optional and self.dialect == "duckdb" else "" + context_key = (signature, grouping_sql) + if context_key in seen_signatures: + continue + seen_signatures.add(context_key) projection_alias = projection_aliases.get(signature) unsafe_aliases: set[str] = set() for dimension in model.dimensions: @@ -5051,31 +5058,30 @@ def _build_yardstick_context_dimensions( "signature": signature, "outer_sql": outer_sql, "inner_sql": inner_expr.sql(dialect=self.dialect), + "grouping_sql": grouping_sql, } ) return context_dimensions - def _expand_group_expression_for_yardstick_context(self, group_expr: exp.Expression) -> list[exp.Expression]: - if isinstance(group_expr, (exp.Rollup, exp.Cube)): - expanded: list[exp.Expression] = [] - for sub_expr in group_expr.expressions: - expanded.extend(self._expand_group_expression_for_yardstick_context(sub_expr)) - return expanded - - if isinstance(group_expr, exp.GroupingSets): - expanded: list[exp.Expression] = [] - for sub_expr in group_expr.expressions: - expanded.extend(self._expand_group_expression_for_yardstick_context(sub_expr)) - return expanded - + def _expand_group_expression_for_yardstick_context( + self, group_expr: exp.Expression, optional: bool = False + ) -> list[tuple[exp.Expression, bool]]: + if isinstance(group_expr, (exp.Rollup, exp.Cube, exp.GroupingSets)): + return [ + item + for child in group_expr.expressions + for item in self._expand_group_expression_for_yardstick_context(child, optional=True) + ] if isinstance(group_expr, exp.Tuple): - expanded: list[exp.Expression] = [] - for sub_expr in group_expr.expressions: - expanded.extend(self._expand_group_expression_for_yardstick_context(sub_expr)) - return expanded - - return [group_expr] + return [ + item + for child in group_expr.expressions + for item in self._expand_group_expression_for_yardstick_context(child, optional) + ] + if isinstance(group_expr, exp.Paren): + return self._expand_group_expression_for_yardstick_context(group_expr.this, optional) + return [(group_expr, optional)] def _split_set_modifier(self, modifier_sql: str) -> tuple[str, str]: tokens = sqlglot.tokenize(modifier_sql, read=self.dialect) diff --git a/tests/fixtures/sql/yardstick/measures.test b/tests/fixtures/sql/yardstick/measures.test index 80560c5ce..5ba55da92 100644 --- a/tests/fixtures/sql/yardstick/measures.test +++ b/tests/fixtures/sql/yardstick/measures.test @@ -1634,7 +1634,7 @@ GROUP BY ROLLUP(o.prodName) ORDER BY o.prodName; ---- Happy 2 13 13 17 -NULL 3 NULL NULL NULL +NULL 3 16 16 20 Whizz 1 3 3 3 # Measures/CSEs should be valid in HAVING, and respect context semantics. diff --git a/tests/queries/test_yardstick_measures_replay.py b/tests/queries/test_yardstick_measures_replay.py index 2721b4846..a1010d980 100644 --- a/tests/queries/test_yardstick_measures_replay.py +++ b/tests/queries/test_yardstick_measures_replay.py @@ -1167,3 +1167,44 @@ def test_explicit_yardstick_star_can_exclude_logical_measures(star): assert runtime.execute(query) == [(2023, "N", 4), (2024, "S", 4)] with pytest.raises(Exception, match="missing_column"): runtime.execute(query.replace("amount,", "missing_column,")) + + +@pytest.mark.parametrize("grouping", ["ROLLUP(region)", "CUBE(region)", "GROUPING SETS ((region), ())"]) +def test_yardstick_subtotal_preserves_filter_mode_and_real_null(grouping): + from tests.queries.yardstick_replay_runtime import replay_runtime + + layer = SemanticLayer(connection="duckdb:///:memory:") + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + "CREATE TABLE subtotal(region VARCHAR, amount INTEGER, included BOOLEAN); " + "INSERT INTO subtotal VALUES (NULL,2,true), (NULL,7,false), ('N',3,true), ('S',5,true)" + ) + runtime.execute("CREATE VIEW subtotal_v AS SELECT region, included, SUM(amount) AS MEASURE revenue FROM subtotal") + assert runtime.execute( + "SELECT region, GROUPING(region) AS subtotal_flag, AGGREGATE(revenue), " + "revenue AT (VISIBLE), revenue FROM subtotal_v WHERE included " + f"GROUP BY {grouping} ORDER BY subtotal_flag, region NULLS FIRST" + ) == [(None, 0, 2, 2, 9), ("N", 0, 3, 3, 3), ("S", 0, 5, 5, 5), (None, 1, 10, 10, 17)] + + +def test_yardstick_grouping_set_keeps_other_dimensions_and_ctas(): + from tests.queries.yardstick_replay_runtime import replay_runtime + + layer = SemanticLayer(connection="duckdb:///:memory:") + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + "CREATE TABLE mixed(year INTEGER, region VARCHAR, amount INTEGER); " + "INSERT INTO mixed VALUES (2023,NULL,2), (2023,'N',3), (2024,'N',5)" + ) + runtime.execute( + "CREATE VIEW mixed_v AS SELECT year, region, COUNT(*) AS MEASURE tally FROM mixed; " + "CREATE TABLE subtotals AS SELECT year, region, GROUPING(region) AS subtotal_flag, " + "AGGREGATE(tally) AS n FROM mixed_v GROUP BY year, GROUPING SETS ((region), ())" + ) + assert runtime.execute("SELECT * FROM subtotals ORDER BY year, subtotal_flag, region NULLS FIRST") == [ + (2023, None, 0, 1), + (2023, "N", 0, 1), + (2023, None, 1, 2), + (2024, "N", 0, 1), + (2024, None, 1, 1), + ] diff --git a/tests/queries/test_yardstick_query_rewriter.py b/tests/queries/test_yardstick_query_rewriter.py index 450cf772f..505fb7af3 100644 --- a/tests/queries/test_yardstick_query_rewriter.py +++ b/tests/queries/test_yardstick_query_rewriter.py @@ -489,7 +489,7 @@ def test_yardstick_listing8_rollup_parity(yardstick_paper_layer, grouping): ] == [ ("Happy", 2, 13.0, 13.0, 17.0), ("Whizz", 1, 3.0, 3.0, 3.0), - (None, 3, None, None, None), + (None, 3, 16.0, 16.0, 20.0), ] @@ -2534,3 +2534,4 @@ def test_yardstick_subquery_placeholder_rewrite_stays_in_inner_scope(yardstick_l assert len(rows) == 1 assert rows[0]["total_revenue"] == pytest.approx(375.0) + From 9dea26a1bcfb21d7d62506a33db855deb8d7a59a Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 23 Nov 2026 14:10:56 -0800 Subject: [PATCH 4/7] Match upstream Yardstick AT context and joined visibility semantics --- docs/compatibility/yardstick.md | 11 +- sqlctx-rs/src/sql/rewriter/yardstick.rs | 575 ++++++++++--- sqlctx/sql/query_rewriter.py | 775 ++++++++++++------ tests/fixtures/sql/yardstick/measures.test | 4 +- .../test_yardstick_joined_visibility.py | 76 ++ .../queries/test_yardstick_measures_replay.py | 42 +- .../queries/test_yardstick_query_rewriter.py | 131 ++- tests/queries/test_yardstick_warnings.py | 20 +- 8 files changed, 1269 insertions(+), 365 deletions(-) create mode 100644 tests/queries/test_yardstick_joined_visibility.py diff --git a/docs/compatibility/yardstick.md b/docs/compatibility/yardstick.md index cc30625c2..ba39c0a2a 100644 --- a/docs/compatibility/yardstick.md +++ b/docs/compatibility/yardstick.md @@ -172,10 +172,10 @@ and temporary measure views, and applies warning policy when prepared statements execute. Query expansion uses sqlctx's production rewriter. This test setup does not enable multi-statement execution on the public query API. -sqlctx emits `YardstickWarning` when `AT (ALL ...)` drops an outer filter that +sqlctx emits `YardstickWarning` when `AT (ALL ...)` or `AT (SET ...)` drops an outer filter that the remaining evaluation context does not preserve. Python callers can treat that warning as an error using the standard `warnings` module. Repeated queries -observe the current warning policy. The literal `yardstick('SELECT ...')` table +observe the current warning policy. The literal `yardstick('SELECT ...')` or `yardstick($$SELECT ...$$)` table wrapper uses the same read-only query rewriting and warning behavior. Optional environment variables: @@ -199,11 +199,11 @@ AT modifiers control the evaluation context of a measure, enabling semi-additive | `AT (WHERE condition)` | Supported (filters the measure's evaluation context independently of the outer WHERE) | | `AT (SET dim = value)` | Supported (pins a dimension to a constant value) | | `AT (SET dim = dim - 1)` | Supported (pins a dimension to a computed expression, e.g., prior period) | -| `AT (SET dim = CURRENT dim - 1)` | Supported (`CURRENT` resolves to the outer query's current value of the dimension) | +| `AT (SET dim = CURRENT dim - 1)` | Supported (`CURRENT` reads the effective context before this modifier) | | `AT (SET dim IN (values))` | Supported (predicate-form SET, filters the dimension to a set of values) | | `AT (VISIBLE)` | Supported (evaluates the measure considering the outer WHERE clause) | -| `AT (SET ... VISIBLE)` | Supported (compound modifier combining SET with VISIBLE) | -| Chained AT: `AT (...) AT (...)` | Supported (modifiers applied left to right) | +| Compound AT: `AT (VISIBLE SET ...)` | Supported (parts apply left to right; SET keeps independently visible predicates) | +| Chained AT: `AT (...) AT (...)` | Supported (rightmost clause transforms the context first, then each clause to its left) | | `AT (ALL expression)` with ad-hoc expressions (e.g., `AT (ALL MONTH(order_date))`) | Supported | | `AT (SET expression = value)` with ad-hoc expressions | Supported | @@ -223,6 +223,7 @@ Bare measure names in non-SEMANTIC queries default to evaluating at the full tab |---------|--------| | `FROM view_a JOIN view_b ON ...` in SEMANTIC queries | Supported (measures from different views evaluated against their own base tables) | | AT modifiers on joined measures | Supported | +| One leading Yardstick source joined to a projection-known non-semantic relation | The Python DuckDB rewriter evaluates visible row membership without multiplying measure inputs. The join itself does not remove rows from the measure's input. | ### GROUP BY Variants diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index b065d04db..81a663eec 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -6,14 +6,14 @@ use std::collections::{HashMap, HashSet}; -use super::{QueryRewriter, parse_sql_with_dialect, table_name_and_alias}; +use super::{parse_sql_with_dialect, table_name_and_alias, QueryRewriter}; use crate::core::MetricType; use crate::error::{Result, SqlctxError}; use crate::semantic_input::dialects; use polyglot_sql::dialects::{DialectImpl, SnowflakeDialect}; use polyglot_sql::expressions::{GroupBy, Identifier, Select, Where}; use polyglot_sql::tokens::{Token, TokenType, Tokenizer}; -use polyglot_sql::{Dialect, DialectType, Expression, generate as polyglot_generate}; +use polyglot_sql::{generate as polyglot_generate, Dialect, DialectType, Expression}; use serde_json::Value; #[derive(Clone)] @@ -235,7 +235,7 @@ impl Lowerer<'_, '_> { index += 1; continue; }; - let mut modifiers = Vec::new(); + let mut clauses = Vec::new(); while stream .get(end + 1) .is_some_and(|token| token.text.eq_ignore_ascii_case("AT")) @@ -245,7 +245,7 @@ impl Lowerer<'_, '_> { { let open = end + 2; end = matching(&stream, open)?; - modifiers.extend(split_modifiers( + clauses.push(split_modifiers( &sql[stream[open].span.end..stream[end].span.start], self.source_dialect, )?); @@ -253,7 +253,7 @@ impl Lowerer<'_, '_> { output.push_str(&sql[cursor..stream[start].span.start]); output.push_str(&self.register(Call { argument, - modifiers, + modifiers: clauses.into_iter().rev().flatten().collect(), visible, })); cursor = stream[end].span.end; @@ -996,72 +996,113 @@ impl Lowerer<'_, '_> { context.push((signature, self.sql(&inner)?, self.sql(&outer)?, grouping)); } } - let mut current = context - .iter() - .map(|(key, _, _, _)| key.clone()) - .collect::>(); + let mut active = context.clone(); + let implicit_visible = call.visible && call.modifiers.is_empty(); + let mut ambient = HashMap::new(); if let Some(predicate) = outer_where { - self.fixed_context(&predicate.this, &mut current)?; + self.fixed_context(&predicate.this, &mut ambient)?; } - let mut active = context.clone(); - let mut visible = call.visible && call.modifiers.is_empty(); - let mut where_predicates = Vec::new(); + let mut filters: Vec<(Expression, HashSet)> = Vec::new(); let mut set_predicates = std::collections::BTreeMap::new(); - let mut removed = HashSet::new(); - let has_set = call.modifiers.iter().any(|modifier| { - modifier - .split_whitespace() - .next() - .is_some_and(|head| head.eq_ignore_ascii_case("SET")) - }); - let mut global_all = false; - for modifier in call.modifiers.iter().rev() { + let mut set_bindings = HashMap::new(); + let mut visible = implicit_visible; + let mut has_all = false; + let mut has_global_all = false; + let mut has_set = false; + if implicit_visible { + if let Some(predicate) = outer_where { + filters.push(( + self.remap( + predicate.this.clone(), + &[model_name, alias], + "_inner", + single, + )?, + HashSet::new(), + )); + } + } + for modifier in &call.modifiers { let stream = tokens(modifier, self.source_dialect)?; let Some(head) = stream.first() else { continue }; let body = modifier[head.span.end..].trim(); + + let current = || -> Result> { + let mut effective = ambient.clone(); + for (filter, removed) in &filters { + let mut fixed = HashMap::new(); + self.fixed_context(filter, &mut fixed)?; + for (key, expr) in fixed { + if !removed.contains(&key) { + effective.insert(key, expr); + } + } + } + for (key, _, outer, _) in &active { + effective.insert(key.clone(), self.expression(outer)?); + } + effective.extend(set_bindings.clone()); + Ok(effective) + }; + match head.text.to_ascii_uppercase().as_str() { "ALL" if body.is_empty() => { + has_all = true; + has_global_all = true; active.clear(); set_predicates.clear(); - where_predicates.clear(); + set_bindings.clear(); + filters.clear(); + ambient.clear(); visible = false; - global_all = true; } - _ if global_all => {} "ALL" => { + has_all = true; for target in self.all_targets(body)? { let key = self.signature(target)?; active.retain(|(signature, _, _, _)| signature != &key); - removed.insert(key); + set_predicates.remove(&key); + set_bindings.remove(&key); + ambient.remove(&key); + for (_, removed) in &mut filters { + removed.insert(key.clone()); + } } } "VISIBLE" => { - if !has_set { - visible = true; - where_predicates.clear(); + visible = true; + if let Some(predicate) = outer_where { + filters.push(( + self.remap( + predicate.this.clone(), + &[model_name, alias], + "_inner", + single, + )?, + HashSet::new(), + )); } } "WHERE" => { - let expression = self.remap( - self.authored_expression(body)?, - &[model_name], - "_inner", - single, - )?; - where_predicates = vec![self.sql(&expression)?]; + let (expression, bindings) = self.current(body, ¤t()?)?; + active.clear(); + set_predicates.clear(); + set_bindings.clear(); + filters.clear(); + ambient.clear(); visible = false; - if call.modifiers.len() == 1 { - active.clear(); - } + // Apply outer bindings only after mapping the authored filter + // columns to the measure's source. + let predicate = + self.remap(expression, &[model_name, alias], "_inner", single)?; + filters.push((self.replace_current(predicate, &bindings)?, HashSet::new())); } "SET" => { - visible = false; - let direct = self.authored_expression(&self.current(body, &HashSet::new())?)?; + has_set = true; + let (direct, empty) = self.current(body, &HashMap::new())?; + let direct = self.replace_current(direct, &empty)?; if let Expression::Eq(eq) = direct { let key = self.signature(eq.left.clone())?; - if removed.contains(&key) { - continue; - } if let Some((_, dimension)) = reference(&eq.left) { let mut self_reference = false; map_columns(&mut encode(eq.right)?, &mut |node| { @@ -1077,15 +1118,21 @@ impl Lowerer<'_, '_> { } } } - let rewritten = self.current(body, ¤t)?; - let expression = self.authored_expression(&rewritten)?; + + let (expression, bindings) = self.current(body, ¤t()?)?; + let key = match &expression { + Expression::Eq(eq) => self.signature(eq.left.clone())?, + Expression::In(set) => self.signature(set.this.clone())?, + _ => return Err(invalid(format!("Unsupported SET modifier: {modifier}"))), + }; + active.retain(|(signature, _, _, _)| signature != &key); + set_bindings.remove(&key); + ambient.remove(&key); + for (_, removed) in &mut filters { + removed.insert(key.clone()); + } match expression { Expression::Eq(eq) => { - let key = self.signature(eq.left.clone())?; - active.retain(|(signature, _, _, _)| signature != &key); - if removed.contains(&key) { - continue; - } let left = self.remap(eq.left, &[model_name, alias], "_inner", single)?; let mut right = encode(eq.right)?; @@ -1110,6 +1157,8 @@ impl Lowerer<'_, '_> { Ok(node) })?; let right = self.remap(decode(right)?, &[model_name], alias, single)?; + let right = self.replace_current(right, &bindings)?; + set_bindings.insert(key.clone(), right.clone()); set_predicates.insert( key, format!( @@ -1120,48 +1169,53 @@ impl Lowerer<'_, '_> { ); } Expression::In(in_expr) => { - let key = self.signature(in_expr.this.clone())?; - if removed.contains(&key) { - continue; - } - active.retain(|(signature, _, _, _)| signature != &key); let expression = self.remap( Expression::In(in_expr), - &[model_name], + &[model_name, alias], "_inner", single, )?; + let expression = self.replace_current(expression, &bindings)?; set_predicates.insert(key, self.sql(&expression)?); } - _ => return Err(invalid(format!("Unsupported SET modifier: {modifier}"))), + _ => unreachable!(), } } _ => return Err(invalid(format!("Unsupported AT modifier: {modifier}"))), } } + let mut base = Vec::new(); + for (filter, removed) in filters { + if let Some(predicate) = self.project_at_filter(filter, &removed)? { + base.push(self.sql(&predicate)?); + } + } + let no_replacements = std::collections::BTreeMap::new(); + // Like upstream, a global ALL is a deliberate reset of the visible + // filters, even if a later clause adds an explicit replacement. + let warning_modifier = if visible { + None + } else if has_all { + Some("ALL") + } else if has_set { + Some("SET") + } else { + None + }; self.warn_dropped_filters( model, alias, name, - call, outer_where, &active, - &where_predicates, - &set_predicates, - visible, + if has_global_all { &[] } else { &base }, + if has_global_all { + &no_replacements + } else { + &set_predicates + }, + warning_modifier, )?; - let mut base = where_predicates; - if visible { - if let Some(predicate) = outer_where { - let expression = self.remap( - predicate.this.clone(), - &[model_name, alias], - "_inner", - single, - )?; - base.push(self.sql(&expression)?); - } - } for filter in &metric.filters { let expression = self.expression(&filter.replace("{model}", "_inner"))?; let expression = self.remap(expression, &[model_name, alias], "_inner", single)?; @@ -1217,26 +1271,15 @@ impl Lowerer<'_, '_> { model: &crate::core::Model, alias: &str, name: &str, - call: &Call, outer_where: Option<&Where>, active: &[(String, String, String, Option)], where_predicates: &[String], set_predicates: &std::collections::BTreeMap, - visible: bool, + warning_modifier: Option<&str>, ) -> Result<()> { - let Some(outer_where) = outer_where else { + let (Some(outer_where), Some(warning_modifier)) = (outer_where, warning_modifier) else { return Ok(()); }; - if visible - || !call.modifiers.iter().any(|modifier| { - modifier - .split_whitespace() - .next() - .is_some_and(|head| head.eq_ignore_ascii_case("ALL")) - }) - { - return Ok(()); - } let mut source_names = model .dimensions .iter() @@ -1308,7 +1351,7 @@ impl Lowerer<'_, '_> { dropped.sort(); if !dropped.is_empty() { self.rewriter.warnings.borrow_mut().push(format!( - "AT (ALL ...) on AGGREGATE({name}) does not preserve outer WHERE filter(s) on ungrouped dimension(s): {}. Add the filter dimension(s) to SELECT/GROUP BY or use an explicit AT modifier that encodes the intended denominator.", dropped.join(", ") + "AT ({warning_modifier} ...) on AGGREGATE({name}) does not preserve outer WHERE filter(s) on ungrouped dimension(s): {}. Add the filter dimension(s) to SELECT/GROUP BY or use an explicit AT modifier that encodes the intended denominator.", dropped.join(", ") )); } Ok(()) @@ -1341,18 +1384,23 @@ impl Lowerer<'_, '_> { Ok(()) } - fn fixed_context(&self, expression: &Expression, fixed: &mut HashSet) -> Result<()> { + fn fixed_context( + &self, + expression: &Expression, + fixed: &mut HashMap, + ) -> Result<()> { match expression { + Expression::Paren(paren) => self.fixed_context(&paren.this, fixed)?, Expression::And(and) => { self.fixed_context(&and.left, fixed)?; self.fixed_context(&and.right, fixed)?; } Expression::Eq(eq) => { if matches!(eq.right, Expression::Literal(_)) { - fixed.insert(self.signature(eq.left.clone())?); + fixed.insert(self.signature(eq.left.clone())?, eq.right.clone()); } if matches!(eq.left, Expression::Literal(_)) { - fixed.insert(self.signature(eq.right.clone())?); + fixed.insert(self.signature(eq.right.clone())?, eq.left.clone()); } } _ => {} @@ -1360,13 +1408,22 @@ impl Lowerer<'_, '_> { Ok(()) } - fn current(&self, sql: &str, context: &HashSet) -> Result { + fn current( + &self, + sql: &str, + context: &HashMap, + ) -> Result<(Expression, HashMap)> { let stream = tokens(sql, self.source_dialect)?; let mut output = String::new(); + let mut bindings = HashMap::new(); let mut cursor = 0; let mut index = 0; while index + 1 < stream.len() { - if !stream[index].text.eq_ignore_ascii_case("CURRENT") { + if !matches!( + stream[index].token_type, + TokenType::Current | TokenType::Var + ) || !stream[index].text.eq_ignore_ascii_case("CURRENT") + { index += 1; continue; } @@ -1396,16 +1453,211 @@ impl Lowerer<'_, '_> { }; output.push_str(&sql[cursor..stream[index].span.start]); let key = self.signature(self.authored_expression(target)?)?; - output.push_str(if context.contains(&key) { - target - } else { - "NULL" - }); + let placeholder = (bindings.len()..) + .map(|n| format!("__ys_at_current_{n}")) + .find(|name| { + !bindings.contains_key(name) + && !stream + .iter() + .any(|token| token.text.eq_ignore_ascii_case(name)) + }) + .expect("unbounded placeholder iterator"); + output.push_str(&placeholder); + let value = context + .get(&key) + .cloned() + .map(Ok) + .unwrap_or_else(|| self.expression("NULL"))?; + bindings.insert(placeholder, value); cursor = stream[end].span.end; index = end + 1; } output.push_str(&sql[cursor..]); - Ok(output) + Ok((self.authored_expression(&output)?, bindings)) + } + + fn replace_current( + &self, + expression: Expression, + bindings: &HashMap, + ) -> Result { + let mut value = encode(&expression)?; + map_columns(&mut value, &mut |node| { + if let Some((_, name)) = reference(&node) { + if let Some(bound) = bindings.get(&name) { + return Ok(bound.clone()); + } + } + Ok(node) + })?; + decode(value) + } + + fn repeatable_at_filter(expression: &Expression) -> bool { + // The offline semantic graph cannot prove the stability of unknown + // functions or subqueries. Normalize only known repeatable operators. + match expression { + Expression::Column(_) + | Expression::Literal(_) + | Expression::Null(_) + | Expression::Boolean(_) => true, + Expression::And(binary) + | Expression::Or(binary) + | Expression::Eq(binary) + | Expression::Neq(binary) + | Expression::Lt(binary) + | Expression::Lte(binary) + | Expression::Gt(binary) + | Expression::Gte(binary) + | Expression::NullSafeEq(binary) + | Expression::NullSafeNeq(binary) => { + Self::repeatable_at_filter(&binary.left) + && Self::repeatable_at_filter(&binary.right) + } + Expression::Paren(paren) => Self::repeatable_at_filter(&paren.this), + Expression::Not(unary) => Self::repeatable_at_filter(&unary.this), + Expression::IsNull(is_null) => Self::repeatable_at_filter(&is_null.this), + _ => false, + } + } + + fn normalize_at_filter(expression: Expression) -> Result { + use polyglot_sql::expressions::{BinaryOp, UnaryOp}; + + fn and(left: Expression, right: Expression) -> Expression { + Expression::And(Box::new(BinaryOp::new(left, right))) + } + fn or(left: Expression, right: Expression) -> Expression { + Expression::Or(Box::new(BinaryOp::new(left, right))) + } + fn not(inner: Expression) -> Expression { + Expression::Not(Box::new(UnaryOp::new(inner))) + } + fn conjuncts(expression: Expression, output: &mut Vec) { + match expression { + Expression::And(binary) => { + conjuncts(binary.left, output); + conjuncts(binary.right, output); + } + Expression::Paren(paren) => conjuncts(paren.this, output), + expression => output.push(expression), + } + } + Ok(match expression { + Expression::Paren(paren) => Self::normalize_at_filter(paren.this)?, + Expression::Not(unary) => match Self::normalize_at_filter(unary.this)? { + Expression::Or(binary) => and( + Self::normalize_at_filter(not(binary.left))?, + Self::normalize_at_filter(not(binary.right))?, + ), + Expression::And(binary) => or( + Self::normalize_at_filter(not(binary.left))?, + Self::normalize_at_filter(not(binary.right))?, + ), + Expression::Not(inner) => inner.this, + inner => not(inner), + }, + Expression::And(binary) => and( + Self::normalize_at_filter(binary.left)?, + Self::normalize_at_filter(binary.right)?, + ), + Expression::Or(binary) => { + let left = Self::normalize_at_filter(binary.left)?; + let right = Self::normalize_at_filter(binary.right)?; + let mut left_terms = Vec::new(); + let mut right_terms = Vec::new(); + conjuncts(left.clone(), &mut left_terms); + conjuncts(right.clone(), &mut right_terms); + let mut common = Vec::new(); + left_terms.retain(|candidate| { + if Self::repeatable_at_filter(candidate) { + if let Some(index) = right_terms.iter().position(|term| term == candidate) { + common.push(candidate.clone()); + right_terms.remove(index); + return false; + } + } + true + }); + let Some(shared) = common.into_iter().reduce(and) else { + return Ok(or(left, right)); + }; + match ( + left_terms.into_iter().reduce(and), + right_terms.into_iter().reduce(and), + ) { + (Some(left), Some(right)) => and(shared, or(left, right)), + // (C AND P) OR C = C in SQL's three-valued logic. + _ => shared, + } + } + expression => expression, + }) + } + + fn project_at_filter( + &self, + expression: Expression, + removed: &HashSet, + ) -> Result> { + if removed.is_empty() { + return Ok(Some(expression)); + } + let dependencies = |expression: &Expression| -> Result<(bool, bool)> { + let mut retained = false; + let mut dropped = false; + map_columns(&mut encode(expression)?, &mut |node| { + if let Some((table, _)) = reference(&node) { + let own = table.as_deref().is_none_or(|table| table == "_inner"); + if own && removed.contains(&self.signature(node.clone())?) { + dropped = true; + } else { + retained = true; + } + } + Ok(node) + })?; + Ok((dropped, retained)) + }; + let (dropped, _) = dependencies(&expression)?; + if !dropped { + return Ok(Some(expression)); // Preserve unrelated predicate shape and evaluation. + } + let expression = match expression { + Expression::Paren(paren) => return self.project_at_filter(paren.this, removed), + Expression::And(mut and) => { + return match ( + self.project_at_filter(and.left.clone(), removed)?, + self.project_at_filter(and.right.clone(), removed)?, + ) { + (Some(left), Some(right)) => { + and.left = left; + and.right = right; + Ok(Some(Expression::And(and))) + } + (left, right) => Ok(left.or(right)), + }; + } + expression => expression, + }; + let value = encode(&expression)?; + let boolean_complex = contains_kind(&value, "and") || contains_kind(&value, "or"); + if boolean_complex && !Self::repeatable_at_filter(&expression) { + return Err(invalid( + "AT dimension replacement cannot safely normalize a volatile or unproven predicate; use an explicit AT WHERE predicate", + )); + } + let normalized = Self::normalize_at_filter(expression)?; + if matches!(normalized, Expression::And(_)) { + return self.project_at_filter(normalized, removed); + } + match dependencies(&normalized)? { + (true, true) => Err(invalid( + "mixed VISIBLE predicate: use an explicit AT context", + )), + (true, false) => Ok(None), + _ => Ok(Some(normalized)), + } } fn all_targets(&self, sql: &str) -> Result> { @@ -1561,20 +1813,39 @@ fn split_modifiers(sql: &str, dialect: DialectType) -> Result> { let stream = tokens(sql, dialect)?; let mut starts = vec![0]; let mut depth = 0; + let head = |token: &Token| { + matches!( + token.token_type, + TokenType::All | TokenType::Set | TokenType::Where + ) || (token.token_type == TokenType::Var && token.text.eq_ignore_ascii_case("VISIBLE")) + }; for (index, token) in stream.iter().enumerate() { match token.token_type { TokenType::LParen => depth += 1, TokenType::RParen => depth -= 1, _ => {} } - if index > 0 - && depth == 0 - && ["ALL", "SET", "WHERE", "VISIBLE"] - .iter() - .any(|word| token.text.eq_ignore_ascii_case(word)) - { - starts.push(token.span.start); + if index == 0 || depth != 0 || !head(token) { + continue; + } + // VISIBLE is also a valid unquoted column name; it can only start a + // context modifier at the end or just before the next modifier. + if token.text.eq_ignore_ascii_case("VISIBLE") { + let preceding = &stream[index - 1]; + if [ + ".", "=", "!=", "<>", "<", ">", "<=", ">=", "+", "-", "*", "/", "%", "AND", "OR", + "NOT", "IS", "LIKE", "ILIKE", "WHERE", "SET", + ] + .iter() + .any(|word| preceding.text.eq_ignore_ascii_case(word)) + || !stream + .get(index + 1) + .is_none_or(|next| head(next) || next.token_type == TokenType::Eof) + { + continue; + } } + starts.push(token.span.start); } starts.push(sql.len()); Ok(starts @@ -1714,4 +1985,96 @@ mod tests { assert!(sql.contains(&format!("GROUPING({qualifier}.year) = 1 OR ((_inner.year) IS NOT DISTINCT FROM ({qualifier}.year))")), "{sql}"); } } + fn at_graph() -> SemanticGraph { + let mut model = Model::new("orders_v", "id") + .with_table("raw_orders") + .with_dimension(crate::core::Dimension::categorical("year")) + .with_dimension(crate::core::Dimension::categorical("region")) + .with_metric(Metric::sum("revenue", "amount")); + model.metadata = Some(serde_json::json!({"yardstick": {}})); + let mut graph = SemanticGraph::new(); + graph.add_model(model).unwrap(); + graph + } + + #[test] + fn at_clauses_apply_outer_inward_but_parts_apply_in_written_order() { + let graph = at_graph(); + let rewriter = QueryRewriter::new(&graph); + let query = |modifier| { + rewriter + .rewrite(&format!( + "SELECT AGGREGATE(revenue) {modifier} FROM orders_v WHERE year=2023" + )) + .unwrap() + }; + let compound = query("AT (WHERE region='N' VISIBLE)"); + assert!(compound.contains("_inner.region = 'N'"), "{compound}"); + assert!(compound.contains("_inner.year = 2023"), "{compound}"); + let chained = query("AT (WHERE region='N') AT (VISIBLE)"); + assert!(chained.contains("_inner.region = 'N'"), "{chained}"); + assert!(!chained.contains("_inner.year = 2023"), "{chained}"); + let reset_then_set = query("AT (ALL SET year=2024)"); + assert!( + reset_then_set.contains("IS NOT DISTINCT FROM (2024)"), + "{reset_then_set}" + ); + let set_then_reset = query("AT (SET year=2024 ALL)"); + assert!(!set_then_reset.contains("2024"), "{set_then_reset}"); + } + + #[test] + fn at_current_uses_prior_binding_and_filter_projection_is_ordered() { + let graph = at_graph(); + let rewriter = QueryRewriter::new(&graph); + let sql = rewriter.rewrite( + "SELECT AGGREGATE(revenue) AT (WHERE year=2024 AND region='N' SET year=CURRENT year-1) FROM orders_v", + ).unwrap(); + assert!(sql.contains("2024 - 1"), "{sql}"); + assert!(sql.contains("_inner.region = 'N'"), "{sql}"); + assert!(!sql.contains("_inner.year = 2024"), "{sql}"); + let mixed = rewriter.rewrite( + "SELECT AGGREGATE(revenue) AT (VISIBLE SET year=2024) FROM orders_v WHERE year=2023 OR region='N'", + ).unwrap_err(); + assert!( + mixed.to_string().contains("mixed VISIBLE predicate"), + "{mixed}" + ); + for word in ["ALL", "SET", "WHERE", "VISIBLE", "CURRENT"] { + let sql = rewriter + .rewrite(&format!( + "SELECT AGGREGATE(revenue) AT (WHERE region='{word}') FROM orders_v" + )) + .unwrap(); + assert!(sql.contains(&format!("_inner.region = '{word}'")), "{sql}"); + } + } + #[test] + fn at_projection_separates_deterministic_predicates_but_not_volatile_disjunctions() { + let graph = at_graph(); + let rewriter = QueryRewriter::new(&graph); + let query = |predicate| { + rewriter.rewrite(&format!( + "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year=year-1) FROM orders_v WHERE {predicate} GROUP BY year" + )) + }; + for predicate in [ + "NOT (year<>2024 OR region<>'N')", + "(year=2024 AND region='N') OR (year=2025 AND region='N')", + "NOT (year<>2024 OR region IS DISTINCT FROM NULL)", + ] { + let sql = query(predicate).unwrap(); + assert!(sql.contains("_inner.region"), "{sql}"); + assert!(!sql.contains("_inner.year = 2024"), "{sql}"); + } + let volatile = query( + "(year=2024 AND random() > 0.5 AND region='N') OR (year=2025 AND random() > 0.5 AND region='N')", + ).unwrap_err(); + assert!( + volatile + .to_string() + .contains("volatile or unproven predicate"), + "{volatile}" + ); + } } diff --git a/sqlctx/sql/query_rewriter.py b/sqlctx/sql/query_rewriter.py index d6f4cd43f..1be2f4bf9 100644 --- a/sqlctx/sql/query_rewriter.py +++ b/sqlctx/sql/query_rewriter.py @@ -6,7 +6,8 @@ import os import re import warnings -from dataclasses import dataclass +from collections.abc import Callable +from dataclasses import dataclass, field from typing import Any import sqlglot @@ -16,7 +17,10 @@ from sqlctx.core.semantic_graph import SemanticGraph from sqlctx.rust_bridge import rewrite_semantic_input -from sqlctx.semantic_handoff import RustBackendUnavailableError, UnsupportedSemanticFeaturesError +from sqlctx.semantic_handoff import ( + RustBackendUnavailableError, + UnsupportedSemanticFeaturesError, +) from sqlctx.sql.aggregation_detection import sql_has_aggregate from sqlctx.sql.generator import DATE_GRANULARITIES, SQLGenerator from sqlctx.sql.parsing import parse_fragment @@ -52,6 +56,15 @@ class _YardstickAggregateCall: include_visible_default: bool +@dataclass +class _YardstickContextFilter: + predicate: exp.Expression + visible: bool + position: int + bindings: dict[str, str] = field(default_factory=dict) + excluded_dimensions: set[str] = field(default_factory=set) + + @dataclass class _WrappedSemanticSource: inner_select: exp.Select @@ -3436,7 +3449,9 @@ def _expand_yardstick_table_functions(self, sql: str, *, user_attributes: dict | ): raise ValueError("yardstick() is not supported while semantic security controls are active") args = function.expressions - if len(args) != 1 or not isinstance(args[0], exp.Literal) or not args[0].is_string: + if len(args) != 1 or not ( + isinstance(args[0], exp.RawString) or (isinstance(args[0], exp.Literal) and args[0].is_string) + ): raise ValueError("yardstick() requires one literal SQL query") inner_sql = args[0].this transformed, _ = self._replace_yardstick_aggregate_calls(inner_sql) @@ -3759,7 +3774,10 @@ def _rewrite_yardstick_select_scope( if has_metric_projection and select_scope.args.get("group") is None: group_exprs = [] for projection, is_metric, is_literal in zip( - select_scope.expressions, projection_is_metric, projection_is_literal, strict=False + select_scope.expressions, + projection_is_metric, + projection_is_literal, + strict=False, ): if is_metric: continue @@ -3775,6 +3793,26 @@ def _rewrite_yardstick_select_scope( scalar_aggregate = True group_clause = select_scope.args.get("group") + if ( + group_clause + and group_clause.args.get("all") + and not any(projection.is_star for projection in select_scope.expressions) + ): + # Resolve the implicit grain before lowering measures to scalar subqueries. + # Otherwise a HAVING-only measure sees a grand total instead of its group. + group_expressions = [] + for projection, is_metric, is_literal in zip( + select_scope.expressions, + projection_is_metric, + projection_is_literal, + strict=True, + ): + expression = projection.this if isinstance(projection, exp.Alias) else projection + if not is_metric and not is_literal and not expression.find(exp.AggFunc, exp.Window): + group_expressions.append(expression.copy()) + if group_expressions: + group_clause = exp.Group(expressions=group_expressions) + select_scope.set("group", group_clause) if group_clause: self._resolve_yardstick_group_ordinals(group_clause, select_scope.expressions) if group_clause and default_alias and single_model_scope: @@ -3813,6 +3851,32 @@ def _rewrite_yardstick_select_scope( ) group_expressions = self._collect_yardstick_group_expressions(group_clause) if group_clause else [] outer_where = select_scope.args.get("where") + joined_scope = self._yardstick_joined_scope(select_scope, source_models) + joined_visibility = None + if joined_scope is not None: + source_alias, rhs_columns = joined_scope + select_aliases = { + projection.alias.casefold() for projection in select_scope.expressions if projection.alias + } + qualified_groups = [] + for group_expr in group_expressions: + group_expr = group_expr.copy() + for column in self._columns_without_nested_scopes(group_expr): + if not column.table and column.name.casefold() not in rhs_columns | select_aliases: + column.set("table", exp.to_identifier(source_alias)) + qualified_groups.append(group_expr) + group_expressions = qualified_groups + if outer_where is not None and not outer_where.find(exp.Select, exp.Subquery): + + def render_visibility(predicate: exp.Expression) -> str | None: + return self._yardstick_visible_join_sql( + select_scope, + source_alias, + exp.Where(this=predicate), + scope_placeholders, + ) + + joined_visibility = render_visibility projection_aliases: dict[str, str] = {} for projection in select_scope.expressions: if not isinstance(projection, exp.Alias): @@ -3838,6 +3902,7 @@ def _rewrite_yardstick_select_scope( outer_where=outer_where, default_alias=default_alias, single_model_scope=single_model_scope, + joined_visibility=joined_visibility, ) replacement_expr_cache = {key: parse_fragment(value, self.dialect) for key, value in replacement_sql.items()} @@ -3870,6 +3935,111 @@ def replace_placeholder(node: exp.Expression) -> exp.Expression: rewritten = self._inline_yardstick_order_by_subquery_aliases(rewritten) return self._rewrite_source_model_relations(rewritten) + def _yardstick_joined_scope( + self, + select: exp.Select, + source_models: dict[str, str], + ) -> tuple[str, set[str]] | None: + """Recognize one measure source joined to a relation with known output names.""" + if self.dialect != "duckdb" or len(source_models) != 1: + return None + from_clause = select.args.get("from_") + if from_clause is None or not isinstance(from_clause.this, exp.Table): + return None + source_alias = from_clause.this.alias_or_name + if source_alias not in source_models or from_clause.this.args.get("db") or from_clause.this.args.get("catalog"): + return None + if not self._is_yardstick_model(source_models[source_alias]): + return None + joins = select.args.get("joins") or [] + if len(joins) != 1: + return None + join = joins[0] + if join.side not in {"", "LEFT"} or join.kind not in {"", "INNER", "OUTER"}: + return None + using = {column.name.casefold() for column in join.args.get("using") or []} + if join.method or (not using and join.args.get("on") is None): + return None + + relation = join.this + alias = relation.args.get("alias") + if isinstance(relation, exp.Values): + if alias is None or not alias.args.get("columns") or relation.find(exp.Column, exp.Subquery): + return None + outputs = {column.name.casefold() for column in alias.args["columns"]} + if len(outputs) != len(alias.args["columns"]) or not using <= outputs: + return None + return source_alias, outputs - using + if alias is not None and alias.args.get("columns"): + return None + if isinstance(relation, exp.Subquery): + rhs = relation.this + elif isinstance(relation, exp.Table) and not relation.args.get("db") and not relation.args.get("catalog"): + with_clause = select.args.get("with_") + if with_clause is None or with_clause.args.get("recursive"): + return None + matching_ctes = [cte for cte in with_clause.expressions if cte.alias.casefold() == relation.name.casefold()] + if len(matching_ctes) != 1: + return None + cte = matching_ctes[0] + if cte.args["alias"].args.get("columns"): + return None + rhs = cte.this + else: + return None + # An unnamed expression, positional overwrite, or star requires a + # catalog/binder. Keep the legacy path when ownership isn't provable. + if not isinstance(rhs, exp.Select): + return None + if isinstance(relation, exp.Subquery) and any( + column.table.casefold() == source_alias.casefold() for column in rhs.find_all(exp.Column) + ): + # DuckDB implicitly treats a correlated right side as LATERAL. + # Don't move those joins through the visibility semijoin. + return None + outputs = set() + for projection in rhs.expressions: + if not isinstance(projection, (exp.Alias, exp.Column)) or projection.is_star or not projection.output_name: + return None + output = projection.output_name.casefold() + if output in outputs: + return None + outputs.add(output) + if not using <= outputs: + return None + return source_alias, outputs - using + + def _yardstick_visible_join_sql( + self, + select: exp.Select, + source_alias: str, + outer_where: exp.Where, + placeholders: set[str], + ) -> str | None: + if self._expression_contains_yardstick_placeholder(outer_where, placeholders): + return None + join = select.args["joins"][0].copy() + if self._expression_contains_yardstick_placeholder(join, placeholders): + return None + # The current SELECT retains its original join. Only the visibility + # probe uses LEFT, because JOIN alone must not shrink the measure's + # row population. A WHERE on the right still rejects unmatched rows. + join.set("side", "LEFT") + join.set("kind", None) + source = exp.to_identifier(source_alias, quoted=True).sql(dialect=self.dialect) + probe = exp.Select( + expressions=[parse_fragment(f"ROW(*COLUMNS({source}.*))", self.dialect)], + from_=select.args["from_"].copy(), + joins=[join], + where=outer_where.copy(), + ) + probe = self._rewrite_source_model_relations(probe) + # DuckDB compares ROW fields with nested NULL-safe equality. The + # composite is non-NULL and matches by position even for SELECT *; + # qualified COLUMNS avoids a column-vs-table alias name collision. + # IN is a semijoin, so RHS fanout cannot multiply measure input. + return f"ROW(*COLUMNS(_inner.*)) IN ({probe.sql(dialect=self.dialect)})" + def _inline_yardstick_order_by_subquery_aliases(self, select_scope: exp.Select) -> exp.Select: """Inline subquery-backed SELECT aliases inside compound ORDER BY expressions. @@ -4741,6 +4911,7 @@ def _build_yardstick_call_sql( outer_where: exp.Where | None, default_alias: str | None, single_model_scope: bool, + joined_visibility: Callable[[exp.Expression], str | None] | None = None, ) -> str: model_alias, model_name, measure_name = self._resolve_yardstick_measure_call(call.argument_sql, source_models) return self._build_yardstick_measure_sql( @@ -4756,6 +4927,7 @@ def _build_yardstick_call_sql( default_alias=default_alias, single_model_scope=single_model_scope, visiting=set(), + joined_visibility=joined_visibility, ) def _build_yardstick_measure_sql( @@ -4772,6 +4944,7 @@ def _build_yardstick_measure_sql( default_alias: str | None, single_model_scope: bool, visiting: set[tuple[str, str]], + joined_visibility: Callable[[exp.Expression], str | None] | None = None, ) -> str: model = self.graph.get_model(model_name) measure = model.get_metric(measure_name) @@ -4814,6 +4987,7 @@ def replace_measure_refs(node: exp.Expression) -> exp.Expression: default_alias=default_alias, single_model_scope=single_model_scope, visiting=visiting.copy(), + joined_visibility=joined_visibility, ) return parse_fragment(dep_sql, self.dialect) @@ -4849,13 +5023,8 @@ def replace_measure_refs(node: exp.Expression) -> exp.Expression: default_alias=default_alias, single_model=single_model_scope, include_visible_default=include_visible_default, - fixed_context_signatures=self._extract_fixed_context_signatures_from_where( - outer_where=outer_where, - default_alias=default_alias, - single_model=single_model_scope, - model_alias=model_alias, - model_name=model_name, - ), + outer_where=outer_where, + joined_visibility=joined_visibility, ) self._warn_yardstick_dropped_filters( @@ -4878,16 +5047,6 @@ def replace_measure_refs(node: exp.Expression) -> exp.Expression: correlation_predicates.append(equality) base_predicates = list(where_modifier_predicates) - if include_visible and outer_where is not None: - visible_expr = outer_where.this.copy() - if default_alias and single_model_scope: - visible_expr = self._qualify_unaliased_columns(visible_expr, default_alias) - visible_expr = self._rewrite_tables( - visible_expr, - table_mapping={model_alias: "_inner", model_name: "_inner"}, - default_table="_inner" if single_model_scope else None, - ) - base_predicates.append(visible_expr.sql(dialect=self.dialect)) for measure_filter in measure.filters or []: # Replace {model} placeholder (used by LookML adapter) with inner alias @@ -5205,60 +5364,77 @@ def _split_all_modifier_targets(self, modifier_sql: str) -> list[str]: return targets or [raw_targets] - def _extract_fixed_context_signatures_from_where( - self, - outer_where: exp.Where | None, - default_alias: str | None, - single_model: bool, - model_alias: str, - model_name: str, - ) -> set[str]: - """Extract dimensions fixed to a literal by conjunctive outer WHERE predicates.""" - if outer_where is None: - return set() + def _yardstick_conjuncts(self, expression: exp.Expression) -> list[exp.Expression]: + while isinstance(expression, exp.Paren): + expression = expression.this + if isinstance(expression, exp.And): + return self._yardstick_conjuncts(expression.this) + self._yardstick_conjuncts(expression.expression) + return [expression] - where_expr = outer_where.this.copy() - if default_alias and single_model: - where_expr = self._qualify_unaliased_columns(where_expr, default_alias) - where_expr = self._rewrite_tables(where_expr, table_mapping={model_name: model_alias}) - - signatures: set[str] = set() - stack: list[exp.Expression] = [where_expr] - while stack: - condition = stack.pop() - if isinstance(condition, exp.And): - stack.append(condition.this) - stack.append(condition.expression) - continue - if not isinstance(condition, exp.EQ): - continue - left = condition.this - right = condition.expression - if isinstance(right, exp.Literal): - signatures.add(self._expr_signature_without_tables(left)) - elif isinstance(left, exp.Literal): - signatures.add(self._expr_signature_without_tables(right)) + def _is_repeatable_yardstick_filter(self, expression: exp.Expression) -> bool: + # The semantic graph cannot prove stability for SQL functions or subqueries. + if isinstance(expression, (exp.Column, exp.Literal, exp.Null, exp.Boolean)): + return True + if isinstance(expression, (exp.Paren, exp.Not)): + return self._is_repeatable_yardstick_filter(expression.this) + if isinstance( + expression, + ( + exp.And, + exp.Or, + exp.EQ, + exp.NEQ, + exp.LT, + exp.LTE, + exp.GT, + exp.GTE, + exp.NullSafeEQ, + exp.NullSafeNEQ, + exp.Is, + ), + ): + return self._is_repeatable_yardstick_filter(expression.this) and self._is_repeatable_yardstick_filter( + expression.expression + ) + return False - return signatures + def _factor_yardstick_filter(self, expression: exp.Expression, negated: bool = False) -> exp.Expression: + """Push NOT through known predicates and factor shared OR conjuncts without distributing.""" + expression = expression.unnest() + if isinstance(expression, exp.Not): + return self._factor_yardstick_filter(expression.this, not negated) + if not isinstance(expression, (exp.And, exp.Or)): + return exp.not_(expression) if negated else expression + + left = self._factor_yardstick_filter(expression.this, negated) + right = self._factor_yardstick_filter(expression.expression, negated) + if isinstance(expression, exp.And) != negated: + return exp.and_(left, right) + + left_terms = self._yardstick_conjuncts(left) + right_terms = self._yardstick_conjuncts(right) + shared = set(left_terms).intersection(right_terms) + if not shared: + return exp.or_(left, right) + common = exp.and_(*(term for term in left_terms if term in shared)) + left_terms = [term for term in left_terms if term not in shared] + right_terms = [term for term in right_terms if term not in shared] + if not left_terms or not right_terms: + # C OR (C AND P) = C, including when C or P is UNKNOWN. + return common + return exp.and_(common, exp.or_(exp.and_(*left_terms), exp.and_(*right_terms))) def _rewrite_current_keyword( self, sql_expr: str, - context_dimensions: list[dict[str, str]], - fixed_context_signatures: set[str] | None = None, + context_values: dict[str, str], + source_aliases: set[str] | None = None, ) -> str: - """Rewrite CURRENT references to context-aware expressions. - - CURRENT resolves to only when that dimension is present in the - current context. Otherwise it resolves to NULL (ambiguous context). - """ + """Replace CURRENT references with their effective context values.""" tokens = sqlglot.tokenize(sql_expr, read=self.dialect) if not tokens: return sql_expr - context_signatures = {dim["signature"] for dim in context_dimensions} - if fixed_context_signatures: - context_signatures |= fixed_context_signatures parts: list[str] = [] i = 0 while i < len(tokens): @@ -5303,8 +5479,11 @@ def _rewrite_current_keyword( try: target_expr = parse_fragment(target_sql, self.dialect) signature = self._expr_signature_without_tables(target_expr) - if signature in context_signatures: - replacement = target_sql + if signature in context_values and ( + source_aliases is None + or all(not c.table or c.table.lower() in source_aliases for c in target_expr.find_all(exp.Column)) + ): + replacement = f"({context_values[signature]})" except SqlglotError: replacement = "NULL" @@ -5323,183 +5502,309 @@ def _apply_yardstick_modifiers( default_alias: str | None, single_model: bool, include_visible_default: bool, - fixed_context_signatures: set[str] | None = None, + outer_where: exp.Where | None, + joined_visibility: Callable[[exp.Expression], str | None] | None = None, ) -> tuple[list[dict[str, str]], list[str], list[str], bool]: - expanded_modifiers: list[str] = [] - for modifier in modifiers: - expanded_modifiers.extend(self._split_compound_yardstick_modifier(modifier)) + # Compound modifiers run in written order; a later AT wraps the + # preceding clause and transforms its input context first. + expanded_modifiers = [ + part for clause in reversed(modifiers) for part in self._split_compound_yardstick_modifier(clause) + ] + if not expanded_modifiers and include_visible_default: + expanded_modifiers = ["VISIBLE"] active_dimensions = list(context_dimensions) - where_predicates: list[str] = [] - set_predicates: dict[str, str] = {} - include_visible = include_visible_default and not expanded_modifiers - has_set = False - has_all_global = False - removed_signatures: set[str] = set() - single_where_modifier = False - - for modifier in expanded_modifiers: - tokens = sqlglot.tokenize(modifier, read=self.dialect) - if not tokens: - continue - if tokens[0].text.upper() == "SET": - has_set = True - if has_set: - include_visible = False - if len(expanded_modifiers) == 1: - tokens = sqlglot.tokenize(expanded_modifiers[0], read=self.dialect) - single_where_modifier = bool(tokens and tokens[0].text.upper() == "WHERE") - - for modifier in reversed(expanded_modifiers): + filters: list[_YardstickContextFilter] = [] + # (modifier position, predicate, value if it determines CURRENT). + set_predicates: dict[str, tuple[int, exp.Expression, str | None]] = {} + set_errors: dict[str, str] = {} + source_aliases = {model_alias.lower(), model_name.lower(), "_inner"} + + def signature_for_source(expression: exp.Expression) -> str | None: + columns = self._columns_without_nested_scopes(expression) + if columns and all(not c.table or c.table.lower() in source_aliases for c in columns): + return self._expr_signature_without_tables(expression) + return None + + def fixed_values( + predicate: exp.Expression, + bindings: dict[str, str] | None = None, + ) -> dict[str, str]: + def fixed(expression: exp.Expression) -> bool: + if isinstance(expression, (exp.Literal, exp.Null, exp.Boolean)): + return True + if isinstance(expression, (exp.Neg, exp.Paren)): + return fixed(expression.this) + if isinstance(expression, (exp.Add, exp.Sub, exp.Mul, exp.Div, exp.Mod)): + return fixed(expression.this) and fixed(expression.expression) + return bool(bindings and isinstance(expression, exp.Column) and expression.name in bindings) + + values: dict[str, str] = {} + for term in self._yardstick_conjuncts(predicate): + if not isinstance(term, (exp.EQ, exp.NullSafeEQ)): + continue + for target, value in ( + (term.this, term.expression), + (term.expression, term.this), + ): + signature = signature_for_source(target) + if signature and fixed(value): + value_sql = ( + restore_current(value, bindings).sql(dialect=self.dialect) + if bindings + else value.sql(dialect=self.dialect) + ) + values.setdefault(signature, value_sql) + return values + + original_values = fixed_values(outer_where.this) if outer_where is not None else {} + + def context_values() -> dict[str, str]: + values = dict(original_values) + values.update({dim["signature"]: dim["outer_sql"] for dim in active_dimensions}) + candidates = [(position, {key: value}) for key, (position, _, value) in set_predicates.items()] + for term in filters: + fixed = fixed_values(term.predicate, term.bindings) + candidates.append( + ( + term.position, + {key: value for key, value in fixed.items() if key not in term.excluded_dimensions}, + ) + ) + for _, found in sorted(candidates, key=lambda item: item[0]): + for key, value in found.items(): + if value is None: + values.pop(key, None) + else: + values[key] = value + return values + + next_current = 0 + + def parse_with_current(sql: str) -> tuple[exp.Expression, dict[str, str]]: + nonlocal next_current + if "CURRENT" not in sql.upper(): + return parse_fragment(sql, self.dialect), {} + bindings = {} + markers = {} + for signature, value in context_values().items(): + marker = f"__yardstick_at_current_{next_current}" + next_current += 1 + while marker.lower() in sql.lower(): + marker = f"__yardstick_at_current_{next_current}" + next_current += 1 + markers[signature] = marker + bindings[marker] = value + return parse_fragment( + self._rewrite_current_keyword(sql, markers, source_aliases), + self.dialect, + ), bindings + + def restore_current(expression: exp.Expression, bindings: dict[str, str]) -> exp.Expression: + def restore(node: exp.Expression) -> exp.Expression: + if isinstance(node, exp.Column) and node.name in bindings: + return exp.Paren(this=parse_fragment(bindings[node.name], self.dialect)) + return node + + return expression.transform(restore) + + def clear_context() -> None: + active_dimensions.clear() + filters.clear() + set_predicates.clear() + set_errors.clear() + original_values.clear() + + def remove_dimension(target: str) -> None: + active_dimensions[:] = [dim for dim in active_dimensions if dim["signature"] != target] + set_predicates.pop(target, None) + set_errors.pop(target, None) + original_values.pop(target, None) + for term in filters: + term.excluded_dimensions.add(target) + + def project_filter(term: _YardstickContextFilter) -> list[exp.Expression]: + if not term.excluded_dimensions: + return [term.predicate] + + def dependencies(expression: exp.Expression) -> tuple[bool, bool]: + removed, other = False, False + + def prune(node: exp.Expression) -> bool: + nonlocal removed, other + if isinstance(node, (exp.Select, exp.Subquery)): + other = True + return True + if signature_for_source(node) in term.excluded_dimensions: + removed = True + return True + if isinstance(node, exp.Column) and node.name not in term.bindings: + other = True + return False + + for _ in expression.walk(prune=prune): + pass + return removed, other + + retained = [] + for conjunct in self._yardstick_conjuncts(term.predicate): + removed, _ = dependencies(conjunct) + if not removed: + retained.append(conjunct) + continue + if conjunct.find(exp.And, exp.Or): + if not self._is_repeatable_yardstick_filter(conjunct): + raise YardstickBindingError( + "AT dimension replacement cannot safely normalize a volatile or unproven predicate; " + "use an explicit AT WHERE predicate" + ) + conjunct = self._factor_yardstick_filter(conjunct) + + for part in self._yardstick_conjuncts(conjunct): + removed, other = dependencies(part) + if removed and other: + raise YardstickBindingError( + "AT dimension replacement cannot separate a mixed " + f"{'VISIBLE' if term.visible else 'WHERE'} predicate; use an explicit AT WHERE predicate" + ) + if not removed: + retained.append(part) + return retained + + for position, modifier in enumerate(expanded_modifiers): tokens = sqlglot.tokenize(modifier, read=self.dialect) if not tokens: continue - modifier_type = tokens[0].text.upper() - if modifier_type == "ALL": if len(tokens) == 1: - active_dimensions = [] - set_predicates.clear() - where_predicates.clear() - include_visible = False - has_all_global = True - continue - - if has_all_global: - continue + clear_context() + else: + for target_sql in self._split_all_modifier_targets(modifier): + target = parse_fragment(target_sql, self.dialect) + remove_dimension(self._expr_signature_without_tables(target)) + continue - for target_sql in self._split_all_modifier_targets(modifier): - target_expr = parse_fragment(target_sql, self.dialect) - if default_alias and single_model: - target_expr = self._qualify_unaliased_columns(target_expr, default_alias) - target_signature = self._expr_signature_without_tables(target_expr) - active_dimensions = [d for d in active_dimensions if d["signature"] != target_signature] - removed_signatures.add(target_signature) + if modifier_type == "VISIBLE": + if outer_where is not None: + filters.append(_YardstickContextFilter(outer_where.this, visible=True, position=position)) continue if modifier_type == "WHERE": - if has_all_global: - continue - where_sql = modifier[tokens[0].end + 1 :].strip() - where_expr = parse_fragment(where_sql, self.dialect) - # In AT(WHERE ...), unqualified columns belong to the inner evaluation context. - # Keep explicitly-qualified outer aliases untouched so predicates can correlate - # (e.g. `prod_name = o.prod_name` from paper listing-style queries). - where_expr = self._rewrite_tables( - where_expr, - table_mapping={model_name: "_inner"}, - default_table="_inner" if single_model else None, - ) - where_predicates = [where_expr.sql(dialect=self.dialect)] - include_visible = False - # Single WHERE modifier evaluates in a non-correlated context. - if single_where_modifier: - active_dimensions = [] + condition, bindings = parse_with_current(modifier[tokens[0].end + 1 :].strip()) + clear_context() + filters.append(_YardstickContextFilter(condition, visible=False, position=position, bindings=bindings)) continue - if modifier_type == "SET": - if has_all_global: - continue - try: - left_sql, right_sql = self._split_set_modifier(modifier) - except ValueError: - # Support Yardstick predicate-style SET forms like: - # AT (SET region IN ('North', 'South')) - set_predicate_sql = modifier[tokens[0].end + 1 :].strip() - set_predicate_expr = parse_fragment(set_predicate_sql, self.dialect) - - if default_alias and single_model: - set_predicate_expr = self._qualify_unaliased_columns(set_predicate_expr, default_alias) - - target_signatures: list[str] = [] - if isinstance(set_predicate_expr, exp.In): - target_signatures.append(self._expr_signature_without_tables(set_predicate_expr.this)) - else: - raise ValueError(f"Unsupported SET modifier: {modifier}") - - if any(signature in removed_signatures for signature in target_signatures): - continue + if modifier_type != "SET": + raise ValueError(f"Unsupported AT modifier: {modifier}") - for signature in target_signatures: - active_dimensions = [d for d in active_dimensions if d["signature"] != signature] - set_predicates.pop(signature, None) + try: + left_sql, right_sql = self._split_set_modifier(modifier) + except ValueError: + # Predicate-style SET replaces the target with a set, not + # a single value from which CURRENT can be read. + predicate = parse_fragment(modifier[tokens[0].end + 1 :].strip(), self.dialect) + if not isinstance(predicate, exp.In): + raise ValueError(f"Unsupported SET modifier: {modifier}") from None + target = self._expr_signature_without_tables(predicate.this) + remove_dimension(target) + if default_alias and single_model: + predicate = self._qualify_unaliased_columns(predicate, default_alias) + predicate = self._rewrite_tables( + predicate, + table_mapping={model_alias: "_inner", model_name: "_inner"}, + default_table="_inner" if single_model else None, + ) + set_predicates[target] = (position, predicate, None) + continue - set_inner_predicate = self._rewrite_tables( - set_predicate_expr, - table_mapping={model_name: "_inner"}, - default_table="_inner" if single_model else None, + left_expr = parse_fragment(left_sql, self.dialect) + target = self._expr_signature_without_tables(left_expr) + error = None + if isinstance(left_expr, exp.Column): + # Plain SET self-references use the outer grouping, even + # after ALL removed that dimension from the measure context. + direct_value = parse_fragment(self._rewrite_current_keyword(right_sql, {}), self.dialect) + if any( + self._expr_signature_without_tables(column) == target + for column in self._columns_without_nested_scopes(direct_value) + ) and not any(dim["signature"] == target for dim in context_dimensions): + error = ( + f"AT (SET {left_sql} = {right_sql}) references {left_expr.name}, " + f"but the query does not group by {left_expr.name}. " + f"Add {left_expr.name} to SELECT/GROUP BY or use a constant SET value." ) - set_predicates[target_signatures[0]] = set_inner_predicate.sql(dialect=self.dialect) - continue - - left_expr = parse_fragment(left_sql, self.dialect) - left_signature = self._expr_signature_without_tables(left_expr) - if left_signature in removed_signatures: + right_expr, bindings = parse_with_current(right_sql) + for column in self._columns_without_nested_scopes(right_expr): + if column.name in bindings: continue - if isinstance(left_expr, exp.Column): - # CURRENT has its own missing-context semantics. Only direct - # self-references require the dimension in SELECT/GROUP BY. - direct_value = parse_fragment(self._rewrite_current_keyword(right_sql, []), self.dialect) - target_signature = self._expr_signature_without_tables(left_expr) - if any( - self._expr_signature_without_tables(column) == target_signature - for column in self._columns_without_nested_scopes(direct_value) - ) and not any(dim["signature"] == target_signature for dim in context_dimensions): - raise YardstickBindingError( - f"AT (SET {left_sql} = {right_sql}) references {left_expr.name}, " - f"but the query does not group by {left_expr.name}. " - f"Add {left_expr.name} to SELECT/GROUP BY or use a constant SET value." - ) - right_expr = parse_fragment( - self._rewrite_current_keyword( - right_sql, - context_dimensions, - fixed_context_signatures=fixed_context_signatures, - ), - self.dialect, + resolved = self._resolve_yardstick_dimension_expression( + column, source_models, default_alias, placeholder_names=set() ) + if resolved: + if column is right_expr: + right_expr = resolved[0] + else: + column.replace(resolved[0]) + + if default_alias and single_model: + left_expr = self._qualify_unaliased_columns(left_expr, default_alias) + right_expr = self._qualify_unaliased_columns(right_expr, default_alias) + elif joined_visibility is not None: + left_expr = self._qualify_unaliased_columns(left_expr, model_alias) for column in self._columns_without_nested_scopes(right_expr): - resolved = self._resolve_yardstick_dimension_expression( - column, source_models, default_alias, placeholder_names=set() - ) - if resolved: - if column is right_expr: - right_expr = resolved[0] - else: - column.replace(resolved[0]) + if not column.table and signature_for_source(column) == target: + column.set("table", exp.to_identifier(model_alias)) - if default_alias and single_model: - left_expr = self._qualify_unaliased_columns(left_expr, default_alias) - right_expr = self._qualify_unaliased_columns(right_expr, default_alias) + left_inner = self._rewrite_tables( + left_expr, + table_mapping={model_alias: "_inner", model_name: "_inner"}, + default_table="_inner" if single_model else None, + ) + right_outer = self._rewrite_tables(right_expr, table_mapping={model_name: model_alias}) + right_outer = restore_current(right_outer, bindings) + remove_dimension(target) + if error is not None: + set_errors[target] = error + set_predicates[target] = ( + position, + exp.NullSafeEQ(this=left_inner, expression=right_outer), + right_outer.sql(dialect=self.dialect), + ) - active_dimensions = [d for d in active_dimensions if d["signature"] != left_signature] + if set_errors: + raise YardstickBindingError(next(iter(set_errors.values()))) - left_inner = self._rewrite_tables( - left_expr, - table_mapping={model_alias: "_inner", model_name: "_inner"}, + where_predicates = [] + include_visible = False + for term in filters: + retained = project_filter(term) + if term.visible and (not term.excluded_dimensions or retained == self._yardstick_conjuncts(term.predicate)): + include_visible = True + if term.visible and retained and joined_visibility is not None: + projected = exp.and_(*(predicate.copy() for predicate in retained)) + if membership := joined_visibility(projected): + where_predicates.append(membership) + continue + names = {model_name: "_inner"} + if term.visible: + names[model_alias] = "_inner" + for predicate in retained: + predicate = self._rewrite_tables( + predicate, + table_mapping=names, default_table="_inner" if single_model else None, ) - right_outer = self._rewrite_tables( - right_expr, - table_mapping={model_name: model_alias}, - ) - set_predicates[left_signature] = ( - f"({left_inner.sql(dialect=self.dialect)}) IS NOT DISTINCT FROM " - f"({right_outer.sql(dialect=self.dialect)})" - ) - continue + predicate = restore_current(predicate, term.bindings) + where_predicates.append(exp.Paren(this=predicate).sql(dialect=self.dialect)) - if modifier_type == "VISIBLE": - if has_all_global or has_set: - continue - include_visible = True - where_predicates.clear() - continue - - raise ValueError(f"Unsupported AT modifier: {modifier}") - - return active_dimensions, where_predicates, list(set_predicates.values()), include_visible + return ( + active_dimensions, + where_predicates, + [predicate.sql(dialect=self.dialect) for _, predicate, _ in set_predicates.values()], + include_visible, + ) def _warn_yardstick_dropped_filters( self, @@ -5520,14 +5825,16 @@ def _warn_yardstick_dropped_filters( its input columns when that expression occurs in the outer predicate; SET MONTH(date)=2 does not preserve an arbitrary filter on date. """ - expanded = [part for modifier in modifiers for part in self._split_compound_yardstick_modifier(modifier)] - if ( - outer_where is None - or include_visible - or not any( - sqlglot.tokenize(part, read=self.dialect)[0].text.upper() == "ALL" for part in expanded if part.strip() - ) - ): + if outer_where is None or include_visible: + return + tokens = [ + sqlglot.tokenize(part, read=self.dialect) + for modifier in modifiers + for part in self._split_compound_yardstick_modifier(modifier) + ] + has_all = any(part[0].token_type == TokenType.ALL for part in tokens) + has_all_global = any(len(part) == 1 and part[0].token_type == TokenType.ALL for part in tokens) + if not has_all and not any(part[0].token_type == TokenType.SET for part in tokens): return model = self.graph.get_model(model_name) @@ -5553,14 +5860,14 @@ def source_columns(expression: exp.Expression) -> set[str]: expression = parse_fragment(dimension["inner_sql"], self.dialect) if isinstance(expression, exp.Column): encoded.update(source_columns(expression)) - for predicate in where_predicates: + for predicate in where_predicates if not has_all_global else []: encoded.update(source_columns(parse_fragment(predicate, self.dialect))) outer_expressions = { self._expr_signature_without_tables(node) for node in outer_where.this.walk(prune=lambda node: isinstance(node, (exp.Select, exp.Subquery))) } - for predicate in set_predicates: + for predicate in set_predicates if not has_all_global else []: expression = parse_fragment(predicate, self.dialect) target = expression.this while isinstance(target, exp.Paren): @@ -5570,10 +5877,20 @@ def source_columns(expression: exp.Expression) -> set[str]: dropped = sorted(outer_columns - encoded) if dropped: + modifier, advice = ( + ( + "ALL", + "Add the filter dimension(s) to SELECT/GROUP BY or use an explicit AT modifier that encodes the intended denominator.", + ) + if has_all + else ( + "SET", + "Use AT (VISIBLE SET ...) to keep them, or add the filter dimension(s) to SELECT/GROUP BY.", + ) + ) warnings.warn( - f"AT (ALL ...) on AGGREGATE({measure_name}) does not preserve outer WHERE filter(s) " - f"on ungrouped dimension(s): {', '.join(dropped)}. Add the filter dimension(s) to " - "SELECT/GROUP BY or use an explicit AT modifier that encodes the intended denominator.", + f"AT ({modifier} ...) on AGGREGATE({measure_name}) does not preserve outer WHERE filter(s) " + f"on ungrouped dimension(s): {', '.join(dropped)}. {advice}", YardstickWarning, stacklevel=4, ) diff --git a/tests/fixtures/sql/yardstick/measures.test b/tests/fixtures/sql/yardstick/measures.test index 5ba55da92..9a40eac9a 100644 --- a/tests/fixtures/sql/yardstick/measures.test +++ b/tests/fixtures/sql/yardstick/measures.test @@ -576,8 +576,8 @@ SEMANTIC SELECT AGGREGATE(revenue) AT (SET year = year - 1) AT (ALL year) as prior_grand FROM sales_yearly; ---- -2022 NULL 375.0 -2023 150.0 375.0 +2022 NULL NULL +2023 150.0 150.0 # ============================================================================= # Test: Negative and zero values diff --git a/tests/queries/test_yardstick_joined_visibility.py b/tests/queries/test_yardstick_joined_visibility.py new file mode 100644 index 000000000..3f23981f3 --- /dev/null +++ b/tests/queries/test_yardstick_joined_visibility.py @@ -0,0 +1,76 @@ +import pytest + +from sqlctx import SemanticLayer +from sqlctx.adapters.yardstick import YardstickAdapter +from tests.queries.yardstick_replay_runtime import replay_runtime + + +@pytest.mark.parametrize("source_columns", ["*", "year, region, amount, s"]) +def test_single_yardstick_source_join_does_not_multiply_or_hide_visible_rows(source_columns): + layer = SemanticLayer(connection="duckdb:///:memory:") + try: + runtime = replay_runtime(layer, YardstickAdapter()) + # The physical column s also matches the source alias. A bare s in + # DuckDB would bind to the column, not to the whole source row. + runtime.execute( + "CREATE TABLE sales(year INT, region VARCHAR, amount INT, s INT); " + "INSERT INTO sales VALUES (2023,'North',10,1), (2023,'North',10,1), " + "(2023,'South',20,1), (2024,'North',30,1), (2024,NULL,40,1), (2024,'East',5,1)" + ) + runtime.execute( + f"CREATE VIEW sales_v AS SELECT {source_columns}, COUNT(*) AS MEASURE tally, " + "SUM(amount) AS MEASURE revenue FROM sales" + ) + query = ( + "WITH thresholds AS (SELECT 'North' AS region, 8 AS cutoff UNION ALL " + "SELECT 'North', 9) " + "SELECT year, AGGREGATE(tally), AGGREGATE(revenue) FROM sales_v s " + "JOIN (SELECT region, cutoff FROM thresholds) r " + "ON r.region = s.region WHERE {predicate} GROUP BY year ORDER BY year" + ) + assert runtime.execute(query.format(predicate="amount > 7")) == [(2023, 3, 40), (2024, 2, 70)] + assert runtime.execute(query.format(predicate="s.amount > r.cutoff")) == [(2023, 2, 20), (2024, 1, 30)] + finally: + layer.adapter.close() + + +def test_joined_grouping_does_not_assign_a_right_hand_column_to_the_measure_source(): + layer = SemanticLayer(connection="duckdb:///:memory:") + try: + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + "CREATE TABLE raw_sales(region VARCHAR, amount INT); " + "INSERT INTO raw_sales VALUES ('North',10), ('North',11), ('South',20); " + "CREATE VIEW raw_sales_v AS SELECT *, COUNT(*) AS MEASURE tally FROM raw_sales" + ) + assert runtime.execute( + "SELECT report_year, AGGREGATE(tally) FROM raw_sales_v s " + "JOIN (SELECT 2026 AS report_year, 'North' AS region) r ON r.region = s.region " + "WHERE s.amount > 0 GROUP BY report_year" + ) == [(2026, 3)] + finally: + layer.adapter.close() + + +@pytest.mark.parametrize( + ("year", "join", "where", "expected"), + [ + ("y", "JOIN (VALUES (2024,'N')) allowed(y,r) USING(y,r)", "y=2024", 30), + ("s.y", "JOIN (VALUES (2024,'N')) allowed(y,r) ON s.y=allowed.y AND s.r=allowed.r", "s.y=2024", 30), + ("y", "JOIN (VALUES ('N',1),('N',1),('S',0)) allowed(r,keep) USING(r)", "y=2024 AND keep=1", 10), + ], +) +def test_joined_visible_set_replaces_year_without_filtering_against_join(year, join, where, expected): + layer = SemanticLayer(connection="duckdb:///:memory:") + try: + runtime = replay_runtime(layer, YardstickAdapter()) + runtime.execute( + "CREATE TABLE sales(y INT, r VARCHAR, amount INT); " + "INSERT INTO sales VALUES (2023,'N',10), (2023,'S',20), (2024,'N',40), (2024,'S',80); " + "CREATE VIEW sales_v AS SELECT y, r, SUM(amount) AS MEASURE revenue FROM sales" + ) + assert runtime.execute( + f"SELECT {year}, AGGREGATE(revenue) AT (VISIBLE SET y=y-1) FROM sales_v s {join} WHERE {where}" + ) == [(2024, expected)] + finally: + layer.adapter.close() diff --git a/tests/queries/test_yardstick_measures_replay.py b/tests/queries/test_yardstick_measures_replay.py index a1010d980..66cd921c8 100644 --- a/tests/queries/test_yardstick_measures_replay.py +++ b/tests/queries/test_yardstick_measures_replay.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import os import re import subprocess @@ -800,11 +801,35 @@ def _apply_statement(layer: SemanticLayer, adapter: YardstickAdapter, statement: ) -def _replay_yardstick_sql_test(path: Path) -> None: +# Yardstick #72 added a mixed fixture to the legacy (non-PEG) corpus. Its +# attached-store metadata, session/transaction behavior, and implicit measures +# are native extension integration checks, not sqlctx query capabilities. +# Require review of any changed fixture so no new assertions disappear silently. +_DEFINITION_STORE_FIXTURE_SHA256 = "8301ba931eee4043223d37efb30e819a2b957a4d1e9e93f92cf984fd33da6e82" +_DEFINITION_STORE_PORTABLE_STATEMENTS = {13, 16, 28, 72} +_DEFINITION_STORE_PORTABLE_QUERIES = {23, 42, 54, 75} + + +def _portable_definition_store_records(path: Path) -> tuple[list[_StatementBlock], list[_QueryBlock]]: + digest = hashlib.sha256(path.read_text().rstrip("\n").encode()).hexdigest() + assert digest == _DEFINITION_STORE_FIXTURE_SHA256, ( + f"{path}: upstream definition-store fixture changed; review the native/portable replay boundary" + ) + statements, queries = _parse_measures_test(path) + portable_statements = [record for record in statements if record.line in _DEFINITION_STORE_PORTABLE_STATEMENTS] + portable_queries = [record for record in queries if record.line in _DEFINITION_STORE_PORTABLE_QUERIES] + assert {record.line for record in portable_statements} == _DEFINITION_STORE_PORTABLE_STATEMENTS + assert {record.line for record in portable_queries} == _DEFINITION_STORE_PORTABLE_QUERIES + return portable_statements, portable_queries + + +def _replay_yardstick_sql_test( + path: Path, records: tuple[list[_StatementBlock], list[_QueryBlock]] | None = None +) -> None: if not path.exists(): pytest.skip(f"Yardstick SQL test file not found: {path}") - statements, queries = _parse_measures_test(path) + statements, queries = _parse_measures_test(path) if records is None else records assert queries, f"No query blocks parsed from Yardstick SQL test: {path}" layer = SemanticLayer(connection="duckdb:///:memory:") @@ -856,7 +881,18 @@ def test_yardstick_upstream_create_view_definitions(): @pytest.mark.yardstick_upstream def test_yardstick_upstream_sql_replay(): for path in _yardstick_upstream_sql_test_paths(): - _replay_yardstick_sql_test(path) + if path.name == "definition_store.test": + _replay_yardstick_sql_test(path, _portable_definition_store_records(path)) + else: + _replay_yardstick_sql_test(path) + + +def test_changed_definition_store_fixture_requires_review(tmp_path): + path = tmp_path / "definition_store.test" + path.write_text("query I\nSELECT 123;\n----\n456\n") + + with pytest.raises(AssertionError, match="review the native/portable replay boundary"): + _portable_definition_store_records(path) def test_replay_binds_measure_and_grouping_projection_aliases(tmp_path): diff --git a/tests/queries/test_yardstick_query_rewriter.py b/tests/queries/test_yardstick_query_rewriter.py index 505fb7af3..fa7b9964a 100644 --- a/tests/queries/test_yardstick_query_rewriter.py +++ b/tests/queries/test_yardstick_query_rewriter.py @@ -6,7 +6,7 @@ from sqlctx import SemanticLayer from sqlctx.loaders import load_from_directory -from sqlctx.sql.query_rewriter import QueryRewriter +from sqlctx.sql.query_rewriter import QueryRewriter, YardstickBindingError, YardstickWarning from tests.duckdb_compat import date_bucket from tests.utils import fetch_dicts @@ -668,7 +668,7 @@ def test_yardstick_set_in_predicate_form(yardstick_layer): } -def test_yardstick_set_then_all_overrides_set(yardstick_layer): +def test_yardstick_outer_all_runs_before_inner_set(yardstick_layer): result = yardstick_layer.sql( """ SEMANTIC SELECT @@ -678,11 +678,10 @@ def test_yardstick_set_then_all_overrides_set(yardstick_layer): """ ) rows = fetch_dicts(result) - values = {row["year"]: float(row["prior_grand"]) for row in rows} - assert values == {2022: 375.0, 2023: 375.0} + assert {row["year"]: row["prior_grand"] for row in rows} == {2022: None, 2023: 150.0} -def test_yardstick_where_then_all_keeps_remaining_correlation(yardstick_layer): +def test_yardstick_where_resets_remaining_correlation(yardstick_layer): result = yardstick_layer.sql( """ SEMANTIC SELECT @@ -695,10 +694,10 @@ def test_yardstick_where_then_all_keeps_remaining_correlation(yardstick_layer): rows = fetch_dicts(result) values = {(row["year"], row["region"]): float(row["us_year_total"]) for row in rows} assert values == { - (2022, "EU"): 100.0, - (2022, "US"): 100.0, - (2023, "EU"): 150.0, - (2023, "US"): 150.0, + (2022, "EU"): 250.0, + (2022, "US"): 250.0, + (2023, "EU"): 250.0, + (2023, "US"): 250.0, } @@ -713,7 +712,101 @@ def test_yardstick_compound_at_modifiers_set_visible(yardstick_layer): """ ) rows = fetch_dicts(result) - assert rows == [{"year": 2023, "prior_year": 150.0}] + assert rows == [{"year": 2023, "prior_year": None}] + + +def test_yardstick_compound_and_chained_modifiers_have_distinct_order(yardstick_layer): + rows = yardstick_layer.sql( + """ +SELECT + AGGREGATE(revenue) AT (WHERE region = 'US' VISIBLE), + AGGREGATE(revenue) AT (VISIBLE WHERE region = 'US'), + AGGREGATE(revenue) AT (WHERE region = 'US') AT (VISIBLE), + AGGREGATE(revenue) AT (VISIBLE) AT (WHERE region = 'US') +FROM sales_v WHERE year = 2023 +""" + ).fetchall() + assert rows == [(150.0, 250.0, 250.0, 150.0)] + + +def test_yardstick_all_visible_restores_outer_conjunction(yardstick_layer): + query = "SELECT AGGREGATE(revenue) AT ({}) FROM sales_v WHERE year = 2023 AND region = 'US'" + assert yardstick_layer.sql(query.format("ALL VISIBLE")).fetchall() == [(150.0,)] + with pytest.warns(YardstickWarning, match="does not preserve outer WHERE"): + assert yardstick_layer.sql(query.format("VISIBLE ALL")).fetchall() == [(375.0,)] + + +def test_yardstick_current_reads_the_context_at_its_position(yardstick_layer): + rows = yardstick_layer.sql( + """ +SELECT + AGGREGATE(revenue) AT (SET year = 2023 SET year = CURRENT year - 1), + AGGREGATE(revenue) AT (WHERE year = 2023 SET year = CURRENT year - 1), + AGGREGATE(revenue) AT (SET year = CURRENT year - 1) AT (SET year = 2023), + AGGREGATE(revenue) AT (SET year = 2023 WHERE year = CURRENT year - 1), + AGGREGATE(revenue) AT (SET year = 2023 ALL SET year = COALESCE(CURRENT year, 2022)), + AGGREGATE(revenue) AT (SET year = 2023 WHERE year = CURRENT year - 1 SET year = CURRENT year + 1) +FROM sales_yearly +""" + ).fetchall() + assert rows == [(150.0, 150.0, 150.0, 150.0, 150.0, 225.0)] + assert yardstick_layer.sql( + "SELECT AGGREGATE(revenue) AT (SET year = 2022 VISIBLE SET year = CURRENT year) " + "FROM sales_yearly WHERE year = 2023" + ).fetchall() == [(225.0,)] + + +def test_yardstick_visible_set_projects_conjuncts_and_rejects_mixed_predicates(yardstick_layer): + query = "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year = year - 1) FROM sales_v WHERE {}" + assert yardstick_layer.sql(query.format("year = 2023 AND region = 'US'")).fetchall() == [(2023, 100.0)] + with pytest.raises(YardstickBindingError, match="mixed VISIBLE predicate"): + yardstick_layer.sql(query.format("year = 2023 OR region = 'US'")) + # A subsequent reset discards the predicate before any projection is needed. + with pytest.warns(YardstickWarning, match="does not preserve outer WHERE"): + assert yardstick_layer.sql( + "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year = year - 1 ALL) " + "FROM sales_v WHERE year = 2023 OR region = 'US' ORDER BY year" + ).fetchall() == [(2022, 375.0), (2023, 375.0)] + + +@pytest.mark.parametrize( + "predicate,expected", + [ + ("NOT (year <> 2023 OR region <> 'US')", 100.0), + ("(year=2023 AND region='US') OR (year=2024 AND region='US')", 100.0), + ("NOT (year <> 2023 OR region IS DISTINCT FROM NULL)", 7.0), + ], +) +def test_yardstick_visible_set_factors_predicates_without_losing_null_semantics(yardstick_layer, predicate, expected): + yardstick_layer.adapter.execute("INSERT INTO sales VALUES (2022, NULL, 7), (2023, NULL, 11)") + assert yardstick_layer.sql( + f"SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year=year-1) FROM sales_v WHERE {predicate}" + ).fetchall() == [(2023, expected)] + + +def test_yardstick_visible_set_retains_independent_volatile_predicates(yardstick_layer): + query = "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year=year-1) FROM sales_v WHERE " + assert yardstick_layer.sql(query + "year=2023 AND (random() < 2 OR random() < 2)").fetchall() == [(2023, 150.0)] + for function in ("random() < 2", "unknown_predicate(region)"): + with pytest.raises(YardstickBindingError, match="volatile or unproven predicate"): + yardstick_layer.sql(query + f"(year=2023 AND {function}) OR (year=2024 AND {function})") + + +def test_yardstick_dollar_quoted_wrapper_reaches_modifier_binding(yardstick_layer): + inner = "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year=year-1) FROM sales_v WHERE " + wrapped = "SELECT * FROM yardstick($context$" + "{}" + "$context$)" + assert yardstick_layer.sql(wrapped.format(inner + "NOT (year<>2023 OR region<>'US')")).fetchall() == [(2023, 100.0)] + with pytest.raises(YardstickBindingError, match="mixed VISIBLE predicate"): + yardstick_layer.sql(wrapped.format(inner + "year=2023 OR region='US'")) + + +@pytest.mark.parametrize("word", ["ALL", "SET", "WHERE", "VISIBLE"]) +def test_yardstick_modifier_keywords_inside_string_literals(yardstick_layer, word): + yardstick_layer.adapter.execute(f"INSERT INTO sales VALUES (2023, '{word}', 1)") + rows = yardstick_layer.sql( + f"SELECT AGGREGATE(revenue) AT (WHERE region = '{word}' VISIBLE) FROM sales_v WHERE year = 2023" + ).fetchall() + assert rows == [(1.0,)] def test_yardstick_at_visible_without_where_is_identity(yardstick_layer): @@ -876,7 +969,7 @@ def test_yardstick_correlated_scalar_context_collapses_to_maximum(tmp_path, reve def test_yardstick_overridden_set_self_reference_is_ignored(yardstick_layer, expression, override): rows = yardstick_layer.sql( "SEMANTIC SELECT region, AGGREGATE(revenue) " - f"AT (SET year = {expression}) AT ({override}) FROM sales_v v ORDER BY region" + f"AT ({override}) AT (SET year = {expression}) FROM sales_v v ORDER BY region" ).fetchall() assert rows == ([("EU", 375.0), ("US", 375.0)] if override == "ALL" else [("EU", 125.0), ("US", 250.0)]) @@ -1585,6 +1678,21 @@ def test_yardstick_group_by_extra_spaces(yardstick_layer): } +def test_yardstick_group_by_all_uses_projection_grain_for_having(yardstick_layer): + result = fetch_dicts( + yardstick_layer.sql( + """ +SELECT year, UPPER(region) AS area, COUNT(*) AS n +FROM sales_v +GROUP BY ALL +HAVING AGGREGATE(revenue) > 110 +ORDER BY year, area +""" + ) + ) + assert result == [{"year": 2023, "area": "US", "n": 1}] + + def test_yardstick_group_by_positional_ordinal(yardstick_layer): result = fetch_dicts( yardstick_layer.sql( @@ -2534,4 +2642,3 @@ def test_yardstick_subquery_placeholder_rewrite_stays_in_inner_scope(yardstick_l assert len(rows) == 1 assert rows[0]["total_revenue"] == pytest.approx(375.0) - diff --git a/tests/queries/test_yardstick_warnings.py b/tests/queries/test_yardstick_warnings.py index 72a44aa47..c24022f1f 100644 --- a/tests/queries/test_yardstick_warnings.py +++ b/tests/queries/test_yardstick_warnings.py @@ -42,9 +42,8 @@ def query_with(modifiers, predicate="year = 2023"): "at (where year=2023) at (all)", "at (all) at (where year=2023)", "at (all) at (set year=2023)", - "at (set year=2023) at (all year)", + "at (all year) at (set year=2023)", "at (all region) at (where region='US') at (visible)", - "at (all region visible set region=current(region))", "at (all region) at (where region='US') at (where year=2023)", ], ) @@ -64,7 +63,8 @@ def test_lost_filter_warns_and_can_be_an_error(warning_layer, modifiers): [ ("at (all region where year=2023)", [("EU", 225.0), ("US", 225.0)]), ("at (all region set year=2023)", [("EU", 225.0), ("US", 225.0)]), - ("at (all year) at (set year=2023)", [("EU", 75.0), ("US", 150.0)]), + ("at (set year=2023) at (all year)", [("EU", 75.0), ("US", 150.0)]), + ("at (all region visible set region=current(region))", [("EU", None), ("US", None)]), ("at (all region visible)", [("EU", 225.0), ("US", 225.0)]), ("at (all region) at (where year=2023) at (where region='US')", [("EU", 225.0), ("US", 225.0)]), ], @@ -124,7 +124,10 @@ def test_literal_yardstick_table_function_preserves_results_and_warnings(warning assert result == [("EU", 375.0), ("US", 375.0)] -@pytest.mark.parametrize("argument", ["'select 1; select 2'", "'delete from sales'", "'select 1 into sink'", "region"]) +@pytest.mark.parametrize( + "argument", + ["'select 1; select 2'", "$$select 1; select 2$$", "'delete from sales'", "'select 1 into sink'", "region"], +) def test_yardstick_table_function_requires_single_literal_read(warning_layer, argument): with pytest.raises(ValueError): QueryRewriter(warning_layer.graph).rewrite(f"select * from yardstick({argument})") @@ -162,10 +165,11 @@ def test_wrapper_explanation_matches_rewrite_and_emits_warning(warning_layer): def test_parenthesized_current_preserves_context_and_string_literals(warning_layer): - assert warning_layer.sql(query_with("at (set region=coalesce(current(region), 'US'))")).fetchall() == [ - ("EU", 125.0), - ("US", 250.0), - ] + with pytest.warns(YardstickWarning, match="year"): + assert warning_layer.sql(query_with("at (set region=coalesce(current(region), 'US'))")).fetchall() == [ + ("EU", 125.0), + ("US", 250.0), + ] @pytest.mark.parametrize( From db8f2b3d289b3dd408b2e80db91e328415cc5f3e Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Tue, 24 Nov 2026 18:28:22 -0800 Subject: [PATCH 5/7] Align native Yardstick modifier contexts with query contracts --- sqlctx-rs/src/sql/rewriter/yardstick.rs | 122 +++++++++++++++++------- 1 file changed, 89 insertions(+), 33 deletions(-) diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index 81a663eec..fa3c1f068 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -797,10 +797,12 @@ impl Lowerer<'_, '_> { "yardstick() is not supported while semantic security controls are active".into(), )); } - let [Expression::Literal(polyglot_sql::expressions::Literal::String(sql))] = - function.args.as_slice() - else { - return Err(invalid("yardstick() requires one literal SQL query")); + let sql = match function.args.as_slice() { + [Expression::Literal(polyglot_sql::expressions::Literal::String(sql))] => sql.clone(), + [Expression::Literal(polyglot_sql::expressions::Literal::DollarString(sql))] => { + polyglot_sql::tokens::parse_dollar_string_token(sql).1 + } + _ => return Err(invalid("yardstick() requires one literal SQL query")), }; let mut validator = Lowerer { rewriter: self.rewriter, @@ -809,7 +811,7 @@ impl Lowerer<'_, '_> { reserved: HashSet::new(), changed: false, }; - let (normalized, _) = validator.normalize(sql)?; + let (normalized, _) = validator.normalize(&sql)?; let normalized = dialects::query(&normalized, self.source_dialect)?; let statements = parse_sql_with_dialect(&normalized, DialectType::DuckDB)?; if statements.len() != 1 @@ -842,7 +844,7 @@ impl Lowerer<'_, '_> { )); } let rewritten = self.rewriter.rewrite_with_output_dialect( - sql, + &sql, self.source_dialect, DialectType::DuckDB, )?; @@ -1002,9 +1004,10 @@ impl Lowerer<'_, '_> { if let Some(predicate) = outer_where { self.fixed_context(&predicate.this, &mut ambient)?; } - let mut filters: Vec<(Expression, HashSet)> = Vec::new(); + let mut filters: Vec<(Expression, HashSet, usize)> = Vec::new(); let mut set_predicates = std::collections::BTreeMap::new(); - let mut set_bindings = HashMap::new(); + let mut set_bindings: HashMap = HashMap::new(); + let mut set_errors = std::collections::BTreeMap::new(); let mut visible = implicit_visible; let mut has_all = false; let mut has_global_all = false; @@ -1019,29 +1022,39 @@ impl Lowerer<'_, '_> { single, )?, HashSet::new(), + 0, )); } } - for modifier in &call.modifiers { + for (position, modifier) in call.modifiers.iter().enumerate() { let stream = tokens(modifier, self.source_dialect)?; let Some(head) = stream.first() else { continue }; let body = modifier[head.span.end..].trim(); let current = || -> Result> { let mut effective = ambient.clone(); - for (filter, removed) in &filters { + for (key, _, outer, _) in &active { + effective.insert(key.clone(), self.expression(outer)?); + } + // CURRENT reads the most recently applied binding, whether it + // came from SET, WHERE, or a later VISIBLE predicate. + let mut candidates = Vec::new(); + for (filter, removed, position) in &filters { let mut fixed = HashMap::new(); self.fixed_context(filter, &mut fixed)?; for (key, expr) in fixed { if !removed.contains(&key) { - effective.insert(key, expr); + candidates.push((*position, key, expr)); } } } - for (key, _, outer, _) in &active { - effective.insert(key.clone(), self.expression(outer)?); + for (key, (position, expression)) in &set_bindings { + candidates.push((*position, key.clone(), expression.clone())); + } + candidates.sort_by_key(|(position, _, _)| *position); + for (_, key, expression) in candidates { + effective.insert(key, expression); } - effective.extend(set_bindings.clone()); Ok(effective) }; @@ -1052,6 +1065,7 @@ impl Lowerer<'_, '_> { active.clear(); set_predicates.clear(); set_bindings.clear(); + set_errors.clear(); filters.clear(); ambient.clear(); visible = false; @@ -1063,8 +1077,9 @@ impl Lowerer<'_, '_> { active.retain(|(signature, _, _, _)| signature != &key); set_predicates.remove(&key); set_bindings.remove(&key); + set_errors.remove(&key); ambient.remove(&key); - for (_, removed) in &mut filters { + for (_, removed, _) in &mut filters { removed.insert(key.clone()); } } @@ -1080,6 +1095,7 @@ impl Lowerer<'_, '_> { single, )?, HashSet::new(), + position, )); } } @@ -1088,19 +1104,25 @@ impl Lowerer<'_, '_> { active.clear(); set_predicates.clear(); set_bindings.clear(); + set_errors.clear(); filters.clear(); ambient.clear(); visible = false; - // Apply outer bindings only after mapping the authored filter - // columns to the measure's source. - let predicate = - self.remap(expression, &[model_name, alias], "_inner", single)?; - filters.push((self.replace_current(predicate, &bindings)?, HashSet::new())); + // An explicit query alias in authored WHERE is an outer + // correlation. Only the model name and unqualified columns + // bind to the inner measure source; VISIBLE maps both aliases. + let predicate = self.remap(expression, &[model_name], "_inner", single)?; + filters.push(( + self.replace_current(predicate, &bindings)?, + HashSet::new(), + position, + )); } "SET" => { has_set = true; let (direct, empty) = self.current(body, &HashMap::new())?; let direct = self.replace_current(direct, &empty)?; + let mut binding_error = None; if let Expression::Eq(eq) = direct { let key = self.signature(eq.left.clone())?; if let Some((_, dimension)) = reference(&eq.left) { @@ -1112,9 +1134,9 @@ impl Lowerer<'_, '_> { if self_reference && !context.iter().any(|(signature, _, _, _)| signature == &key) { - return Err(SqlctxError::YardstickBinding(format!( + binding_error = Some(format!( "AT ({modifier}) references {dimension}, but the query does not group by {dimension}. Add {dimension} to SELECT/GROUP BY or use a constant SET value." - ))); + )); } } } @@ -1127,10 +1149,14 @@ impl Lowerer<'_, '_> { }; active.retain(|(signature, _, _, _)| signature != &key); set_bindings.remove(&key); + set_errors.remove(&key); ambient.remove(&key); - for (_, removed) in &mut filters { + for (_, removed, _) in &mut filters { removed.insert(key.clone()); } + if let Some(error) = binding_error { + set_errors.insert(key.clone(), error); + } match expression { Expression::Eq(eq) => { let left = @@ -1158,7 +1184,7 @@ impl Lowerer<'_, '_> { })?; let right = self.remap(decode(right)?, &[model_name], alias, single)?; let right = self.replace_current(right, &bindings)?; - set_bindings.insert(key.clone(), right.clone()); + set_bindings.insert(key.clone(), (position, right.clone())); set_predicates.insert( key, format!( @@ -1184,8 +1210,13 @@ impl Lowerer<'_, '_> { _ => return Err(invalid(format!("Unsupported AT modifier: {modifier}"))), } } + // A later ALL, WHERE, or SET can discard an invalid self-reference. + // Only bindings that survive the complete modifier chain must validate. + if let Some(error) = set_errors.into_values().next() { + return Err(SqlctxError::YardstickBinding(error)); + } let mut base = Vec::new(); - for (filter, removed) in filters { + for (filter, removed, _) in filters { if let Some(predicate) = self.project_at_filter(filter, &removed)? { base.push(self.sql(&predicate)?); } @@ -1384,6 +1415,22 @@ impl Lowerer<'_, '_> { Ok(()) } + fn fixed_value(expression: &Expression) -> bool { + match expression { + Expression::Literal(_) | Expression::Null(_) | Expression::Boolean(_) => true, + Expression::Paren(paren) => Self::fixed_value(&paren.this), + Expression::Neg(neg) => Self::fixed_value(&neg.this), + Expression::Add(binary) + | Expression::Sub(binary) + | Expression::Mul(binary) + | Expression::Div(binary) + | Expression::Mod(binary) => { + Self::fixed_value(&binary.left) && Self::fixed_value(&binary.right) + } + _ => false, + } + } + fn fixed_context( &self, expression: &Expression, @@ -1396,10 +1443,10 @@ impl Lowerer<'_, '_> { self.fixed_context(&and.right, fixed)?; } Expression::Eq(eq) => { - if matches!(eq.right, Expression::Literal(_)) { + if Self::fixed_value(&eq.right) { fixed.insert(self.signature(eq.left.clone())?, eq.right.clone()); } - if matches!(eq.left, Expression::Literal(_)) { + if Self::fixed_value(&eq.left) { fixed.insert(self.signature(eq.right.clone())?, eq.left.clone()); } } @@ -1643,8 +1690,8 @@ impl Lowerer<'_, '_> { let value = encode(&expression)?; let boolean_complex = contains_kind(&value, "and") || contains_kind(&value, "or"); if boolean_complex && !Self::repeatable_at_filter(&expression) { - return Err(invalid( - "AT dimension replacement cannot safely normalize a volatile or unproven predicate; use an explicit AT WHERE predicate", + return Err(SqlctxError::YardstickBinding( + "AT dimension replacement cannot safely normalize a volatile or unproven predicate; use an explicit AT WHERE predicate".into(), )); } let normalized = Self::normalize_at_filter(expression)?; @@ -1652,8 +1699,8 @@ impl Lowerer<'_, '_> { return self.project_at_filter(normalized, removed); } match dependencies(&normalized)? { - (true, true) => Err(invalid( - "mixed VISIBLE predicate: use an explicit AT context", + (true, true) => Err(SqlctxError::YardstickBinding( + "mixed VISIBLE predicate: use an explicit AT context".into(), )), (true, false) => Ok(None), _ => Ok(Some(normalized)), @@ -1832,12 +1879,21 @@ fn split_modifiers(sql: &str, dialect: DialectType) -> Result> { // context modifier at the end or just before the next modifier. if token.text.eq_ignore_ascii_case("VISIBLE") { let preceding = &stream[index - 1]; - if [ + if (!matches!( + preceding.token_type, + TokenType::String + | TokenType::DollarString + | TokenType::RawString + | TokenType::NationalString + | TokenType::EscapeString + | TokenType::TripleDoubleQuotedString + | TokenType::TripleSingleQuotedString + ) && [ ".", "=", "!=", "<>", "<", ">", "<=", ">=", "+", "-", "*", "/", "%", "AND", "OR", "NOT", "IS", "LIKE", "ILIKE", "WHERE", "SET", ] .iter() - .any(|word| preceding.text.eq_ignore_ascii_case(word)) + .any(|word| preceding.text.eq_ignore_ascii_case(word))) || !stream .get(index + 1) .is_none_or(|next| head(next) || next.token_type == TokenType::Eof) From 72bc67433e771c68a0c2f10531b1d739236db50c Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Thu, 26 Nov 2026 08:22:39 -0800 Subject: [PATCH 6/7] Match expression targets when replacing Yardstick measure filters --- sqlctx-rs/src/sql/rewriter/yardstick.rs | 68 ++++++++++++++++--- .../queries/test_yardstick_query_rewriter.py | 29 ++++++++ 2 files changed, 86 insertions(+), 11 deletions(-) diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index fa3c1f068..b6509eb57 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -1651,19 +1651,65 @@ impl Lowerer<'_, '_> { return Ok(Some(expression)); } let dependencies = |expression: &Expression| -> Result<(bool, bool)> { - let mut retained = false; - let mut dropped = false; - map_columns(&mut encode(expression)?, &mut |node| { - if let Some((table, _)) = reference(&node) { - let own = table.as_deref().is_none_or(|table| table == "_inner"); - if own && removed.contains(&self.signature(node.clone())?) { - dropped = true; - } else { - retained = true; + fn visit( + lowerer: &Lowerer<'_, '_>, + value: &Value, + removed: &HashSet, + dropped: &mut bool, + retained: &mut bool, + ) -> Result<()> { + match value { + Value::Object(fields) => { + if fields.contains_key("select") || fields.contains_key("subquery") { + *retained = true; + return Ok(()); + } + if let Ok(expression) = decode::(value.clone()) { + // Match the complete target before descending into its + // inputs: replacing YEAR(date) does not replace date. + if removed.contains(&lowerer.signature(expression.clone())?) { + let mut has_columns = false; + let mut own = true; + map_columns(&mut value.clone(), &mut |column| { + if let Some((table, _)) = reference(&column) { + has_columns = true; + own &= + table.as_deref().is_none_or(|table| table == "_inner"); + } + Ok(column) + })?; + if has_columns && own { + *dropped = true; + return Ok(()); + } + } + if reference(&expression).is_some() { + *retained = true; + return Ok(()); + } + } + for child in fields.values() { + visit(lowerer, child, removed, dropped, retained)?; + } + } + Value::Array(children) => { + for child in children { + visit(lowerer, child, removed, dropped, retained)?; + } } + _ => {} } - Ok(node) - })?; + Ok(()) + } + let mut retained = false; + let mut dropped = false; + visit( + self, + &encode(expression)?, + removed, + &mut dropped, + &mut retained, + )?; Ok((dropped, retained)) }; let (dropped, _) = dependencies(&expression)?; diff --git a/tests/queries/test_yardstick_query_rewriter.py b/tests/queries/test_yardstick_query_rewriter.py index fa7b9964a..1361c4d74 100644 --- a/tests/queries/test_yardstick_query_rewriter.py +++ b/tests/queries/test_yardstick_query_rewriter.py @@ -792,6 +792,35 @@ def test_yardstick_visible_set_retains_independent_volatile_predicates(yardstick yardstick_layer.sql(query + f"(year=2023 AND {function}) OR (year=2024 AND {function})") +@pytest.mark.parametrize("modifier", ["SET MONTH(order_date)=2", "ALL MONTH(order_date)"]) +@pytest.mark.parametrize("context", ["VISIBLE", "WHERE MONTH(order_date)=1 AND amount>110"]) +def test_yardstick_expression_target_replaces_only_its_filter(yardstick_layer, modifier, context): + rows = yardstick_layer.sql( + f"SELECT AGGREGATE(revenue) AT ({context} {modifier}) FROM daily_orders_v " + "WHERE MONTH(order_date)=1 AND amount>110" + ).fetchall() + assert rows == [(320.0 if modifier.startswith("SET") else 650.0,)] + + +def test_yardstick_expression_target_keeps_filters_on_its_input(yardstick_layer): + rows = yardstick_layer.sql( + "SELECT AGGREGATE(revenue) AT (VISIBLE SET MONTH(order_date)=2) FROM daily_orders_v " + "WHERE MONTH(order_date)=1 AND order_date < DATE '2023-01-25'" + ).fetchall() + assert rows == [(None,)] + assert yardstick_layer.sql( + "SELECT AGGREGATE(revenue) AT (VISIBLE SET year+1=2024) FROM sales_yearly WHERE year+1=2023" + ).fetchall() == [(225.0,)] + + +def test_yardstick_visible_set_replaces_year_expression(yardstick_layer): + yardstick_layer.adapter.execute("INSERT INTO daily_orders VALUES ('2024-01-01', 40)") + assert yardstick_layer.sql( + "SELECT AGGREGATE(revenue) AT (VISIBLE SET YEAR(order_date)=2023) " + "FROM daily_orders_v WHERE YEAR(order_date)=2024" + ).fetchall() == [(840.0,)] + + def test_yardstick_dollar_quoted_wrapper_reaches_modifier_binding(yardstick_layer): inner = "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year=year-1) FROM sales_v WHERE " wrapped = "SELECT * FROM yardstick($context$" + "{}" + "$context$)" From adf3461081ef84ee196a7f7536526a3e5a945eec Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Thu, 26 Nov 2026 09:42:13 -0800 Subject: [PATCH 7/7] Preserve wildcard column precedence and captured Yardstick contexts --- sqlctx-rs/src/sql/rewriter/yardstick.rs | 182 +++++++++++++----- sqlctx/core/semantic_layer.py | 1 + sqlctx/core/transport_security.py | 1 + sqlctx/sql/query_rewriter.py | 46 ++++- .../queries/test_yardstick_measures_replay.py | 43 +++++ .../queries/test_yardstick_query_rewriter.py | 37 ++++ 6 files changed, 255 insertions(+), 55 deletions(-) diff --git a/sqlctx-rs/src/sql/rewriter/yardstick.rs b/sqlctx-rs/src/sql/rewriter/yardstick.rs index b6509eb57..48b700eec 100644 --- a/sqlctx-rs/src/sql/rewriter/yardstick.rs +++ b/sqlctx-rs/src/sql/rewriter/yardstick.rs @@ -23,6 +23,13 @@ struct Call { visible: bool, } +struct ContextFilter { + predicate: Expression, + removed: HashSet, + position: usize, + current_bindings: HashMap, +} + struct Lowerer<'a, 'g> { rewriter: &'a QueryRewriter<'g>, source_dialect: DialectType, @@ -159,6 +166,26 @@ impl Lowerer<'_, '_> { )?) } + fn has_wildcard_source(&self, model_name: &str) -> Result { + let view_sql = self + .rewriter + .graph + .get_model(model_name) + .and_then(|model| model.metadata.as_ref()) + .and_then(|metadata| metadata.get("yardstick")) + .and_then(|metadata| metadata.get("view_sql")) + .and_then(Value::as_str); + let Some(view_sql) = view_sql else { + return Ok(false); + }; + let statements = parse_sql_with_dialect(view_sql, self.source_dialect)?; + Ok( + matches!(statements.as_slice(), [Expression::Select(select)] if select.expressions.iter().any(|projection| { + matches!(projection, Expression::Star(_)) || reference(projection).is_some_and(|(_, name)| name == "*") + })), + ) + } + fn register(&mut self, call: Call) -> String { let mut index = self.calls.len(); loop { @@ -481,6 +508,28 @@ impl Lowerer<'_, '_> { .iter() .map(|projection| reference(projection).map(|(_, name)| name)) .collect::>(); + let wildcard_source = single + && self.source_dialect == DialectType::DuckDB + && self.has_wildcard_source(&sources[0].0)?; + if wildcard_source { + // Wildcard imports leave physical columns undeclared. In projection + // expressions they take precedence over same-named output aliases. + // Keep ORDER BY/HAVING aliases outside this qualification pass. + for projection in &mut select.expressions { + let mut expression = encode(&*projection)?; + map_columns(&mut expression, &mut |node| { + if reference(&node).is_some_and(|(table, name)| { + table.is_none() && !scope_calls.contains(&name) + }) { + self.remap(node, &[], &sources[0].1, true) + } else { + Ok(node) + } + })?; + *projection = decode(expression)?; + } + value = encode(&select)?; + } // Expand declared dimension expressions before computing context keys. map_columns(&mut value, &mut |node| { let Some((table, name)) = reference(&node) else { @@ -610,7 +659,13 @@ impl Lowerer<'_, '_> { } } else if let Some((None, name)) = reference(expression) { if let Some(Expression::Alias(alias)) = select.expressions.iter().find(|projection| matches!(projection, Expression::Alias(alias) if alias.alias.name == name)) { - *expression = alias.this.clone(); + *expression = if wildcard_source && contains_call(&alias.this)? { + // A wildcard input column wins over a measure alias + // with the same name, just as it does in SELECT. + self.remap(expression.clone(), &[], &sources[0].1, true)? + } else { + alias.this.clone() + }; } } } @@ -928,6 +983,9 @@ impl Lowerer<'_, '_> { } Some(aggregation) => format!("{}({expression_sql})", aggregation.as_sql()), }; + let wildcard_source = single + && self.source_dialect == DialectType::DuckDB + && self.has_wildcard_source(model_name)?; let mut context = Vec::new(); for group in groups { let mut expanded = Vec::new(); @@ -973,7 +1031,15 @@ impl Lowerer<'_, '_> { }) { continue; } - if let Some(output_alias) = context_aliases.get(&signature).filter(|_| !optional) { + if wildcard_source { + // Correlate on the qualified group key itself: an output + // alias may shadow a physical column or follow the measure. + if reference(&outer).is_none() { + outer = self.expression(&format!("ANY_VALUE({})", self.sql(&outer)?))?; + } + } else if let Some(output_alias) = + context_aliases.get(&signature).filter(|_| !optional) + { // SELECT * imports can expose physical grouping columns // without declaring dimensions. An unqualified output // alias with that same name would bind to the inner source @@ -1002,9 +1068,9 @@ impl Lowerer<'_, '_> { let implicit_visible = call.visible && call.modifiers.is_empty(); let mut ambient = HashMap::new(); if let Some(predicate) = outer_where { - self.fixed_context(&predicate.this, &mut ambient)?; + self.fixed_context(&predicate.this, &HashMap::new(), &mut ambient)?; } - let mut filters: Vec<(Expression, HashSet, usize)> = Vec::new(); + let mut filters: Vec = Vec::new(); let mut set_predicates = std::collections::BTreeMap::new(); let mut set_bindings: HashMap = HashMap::new(); let mut set_errors = std::collections::BTreeMap::new(); @@ -1014,16 +1080,17 @@ impl Lowerer<'_, '_> { let mut has_set = false; if implicit_visible { if let Some(predicate) = outer_where { - filters.push(( - self.remap( + filters.push(ContextFilter { + predicate: self.remap( predicate.this.clone(), &[model_name, alias], "_inner", single, )?, - HashSet::new(), - 0, - )); + removed: HashSet::new(), + position: 0, + current_bindings: HashMap::new(), + }); } } for (position, modifier) in call.modifiers.iter().enumerate() { @@ -1039,12 +1106,12 @@ impl Lowerer<'_, '_> { // CURRENT reads the most recently applied binding, whether it // came from SET, WHERE, or a later VISIBLE predicate. let mut candidates = Vec::new(); - for (filter, removed, position) in &filters { + for filter in &filters { let mut fixed = HashMap::new(); - self.fixed_context(filter, &mut fixed)?; + self.fixed_context(&filter.predicate, &filter.current_bindings, &mut fixed)?; for (key, expr) in fixed { - if !removed.contains(&key) { - candidates.push((*position, key, expr)); + if !filter.removed.contains(&key) { + candidates.push((filter.position, key, expr)); } } } @@ -1079,24 +1146,25 @@ impl Lowerer<'_, '_> { set_bindings.remove(&key); set_errors.remove(&key); ambient.remove(&key); - for (_, removed, _) in &mut filters { - removed.insert(key.clone()); + for filter in &mut filters { + filter.removed.insert(key.clone()); } } } "VISIBLE" => { visible = true; if let Some(predicate) = outer_where { - filters.push(( - self.remap( + filters.push(ContextFilter { + predicate: self.remap( predicate.this.clone(), &[model_name, alias], "_inner", single, )?, - HashSet::new(), + removed: HashSet::new(), position, - )); + current_bindings: HashMap::new(), + }); } } "WHERE" => { @@ -1112,11 +1180,14 @@ impl Lowerer<'_, '_> { // correlation. Only the model name and unqualified columns // bind to the inner measure source; VISIBLE maps both aliases. let predicate = self.remap(expression, &[model_name], "_inner", single)?; - filters.push(( - self.replace_current(predicate, &bindings)?, - HashSet::new(), + // CURRENT is a captured context value, not another input + // dimension. Keep it opaque until filter projection finishes. + filters.push(ContextFilter { + predicate, + removed: HashSet::new(), position, - )); + current_bindings: bindings, + }); } "SET" => { has_set = true; @@ -1151,8 +1222,8 @@ impl Lowerer<'_, '_> { set_bindings.remove(&key); set_errors.remove(&key); ambient.remove(&key); - for (_, removed, _) in &mut filters { - removed.insert(key.clone()); + for filter in &mut filters { + filter.removed.insert(key.clone()); } if let Some(error) = binding_error { set_errors.insert(key.clone(), error); @@ -1216,8 +1287,11 @@ impl Lowerer<'_, '_> { return Err(SqlctxError::YardstickBinding(error)); } let mut base = Vec::new(); - for (filter, removed, _) in filters { - if let Some(predicate) = self.project_at_filter(filter, &removed)? { + for filter in filters { + if let Some(predicate) = + self.project_at_filter(filter.predicate, &filter.removed, &filter.current_bindings)? + { + let predicate = self.replace_current(predicate, &filter.current_bindings)?; base.push(self.sql(&predicate)?); } } @@ -1415,39 +1489,47 @@ impl Lowerer<'_, '_> { Ok(()) } - fn fixed_value(expression: &Expression) -> bool { + fn fixed_value(expression: &Expression, bindings: &HashMap) -> bool { match expression { Expression::Literal(_) | Expression::Null(_) | Expression::Boolean(_) => true, - Expression::Paren(paren) => Self::fixed_value(&paren.this), - Expression::Neg(neg) => Self::fixed_value(&neg.this), + Expression::Paren(paren) => Self::fixed_value(&paren.this, bindings), + Expression::Neg(neg) => Self::fixed_value(&neg.this, bindings), Expression::Add(binary) | Expression::Sub(binary) | Expression::Mul(binary) | Expression::Div(binary) | Expression::Mod(binary) => { - Self::fixed_value(&binary.left) && Self::fixed_value(&binary.right) + Self::fixed_value(&binary.left, bindings) + && Self::fixed_value(&binary.right, bindings) } - _ => false, + _ => reference(expression).is_some_and(|(_, name)| bindings.contains_key(&name)), } } fn fixed_context( &self, expression: &Expression, + bindings: &HashMap, fixed: &mut HashMap, ) -> Result<()> { match expression { - Expression::Paren(paren) => self.fixed_context(&paren.this, fixed)?, + Expression::Paren(paren) => self.fixed_context(&paren.this, bindings, fixed)?, Expression::And(and) => { - self.fixed_context(&and.left, fixed)?; - self.fixed_context(&and.right, fixed)?; + self.fixed_context(&and.left, bindings, fixed)?; + self.fixed_context(&and.right, bindings, fixed)?; } Expression::Eq(eq) => { - if Self::fixed_value(&eq.right) { - fixed.insert(self.signature(eq.left.clone())?, eq.right.clone()); + if Self::fixed_value(&eq.right, bindings) { + fixed.insert( + self.signature(eq.left.clone())?, + self.replace_current(eq.right.clone(), bindings)?, + ); } - if Self::fixed_value(&eq.left) { - fixed.insert(self.signature(eq.right.clone())?, eq.left.clone()); + if Self::fixed_value(&eq.left, bindings) { + fixed.insert( + self.signature(eq.right.clone())?, + self.replace_current(eq.left.clone(), bindings)?, + ); } } _ => {} @@ -1646,6 +1728,7 @@ impl Lowerer<'_, '_> { &self, expression: Expression, removed: &HashSet, + bindings: &HashMap, ) -> Result> { if removed.is_empty() { return Ok(Some(expression)); @@ -1655,6 +1738,7 @@ impl Lowerer<'_, '_> { lowerer: &Lowerer<'_, '_>, value: &Value, removed: &HashSet, + bindings: &HashMap, dropped: &mut bool, retained: &mut bool, ) -> Result<()> { @@ -1665,6 +1749,11 @@ impl Lowerer<'_, '_> { return Ok(()); } if let Ok(expression) = decode::(value.clone()) { + if reference(&expression) + .is_some_and(|(_, name)| bindings.contains_key(&name)) + { + return Ok(()); + } // Match the complete target before descending into its // inputs: replacing YEAR(date) does not replace date. if removed.contains(&lowerer.signature(expression.clone())?) { @@ -1689,12 +1778,12 @@ impl Lowerer<'_, '_> { } } for child in fields.values() { - visit(lowerer, child, removed, dropped, retained)?; + visit(lowerer, child, removed, bindings, dropped, retained)?; } } Value::Array(children) => { for child in children { - visit(lowerer, child, removed, dropped, retained)?; + visit(lowerer, child, removed, bindings, dropped, retained)?; } } _ => {} @@ -1707,6 +1796,7 @@ impl Lowerer<'_, '_> { self, &encode(expression)?, removed, + bindings, &mut dropped, &mut retained, )?; @@ -1717,11 +1807,13 @@ impl Lowerer<'_, '_> { return Ok(Some(expression)); // Preserve unrelated predicate shape and evaluation. } let expression = match expression { - Expression::Paren(paren) => return self.project_at_filter(paren.this, removed), + Expression::Paren(paren) => { + return self.project_at_filter(paren.this, removed, bindings) + } Expression::And(mut and) => { return match ( - self.project_at_filter(and.left.clone(), removed)?, - self.project_at_filter(and.right.clone(), removed)?, + self.project_at_filter(and.left.clone(), removed, bindings)?, + self.project_at_filter(and.right.clone(), removed, bindings)?, ) { (Some(left), Some(right)) => { and.left = left; @@ -1742,7 +1834,7 @@ impl Lowerer<'_, '_> { } let normalized = Self::normalize_at_filter(expression)?; if matches!(normalized, Expression::And(_)) { - return self.project_at_filter(normalized, removed); + return self.project_at_filter(normalized, removed, bindings); } match dependencies(&normalized)? { (true, true) => Err(SqlctxError::YardstickBinding( diff --git a/sqlctx/core/semantic_layer.py b/sqlctx/core/semantic_layer.py index 44e8964e0..be160d4e4 100644 --- a/sqlctx/core/semantic_layer.py +++ b/sqlctx/core/semantic_layer.py @@ -2429,6 +2429,7 @@ def explain_sql(self, query: str, strict: bool = True): use_rust_rewriter=self._use_rust_sql_generator if self._explicit_engine else None, rust_no_fallback=self._rust_no_fallback, allow_non_additive_unsafe=self.allow_non_additive_unsafe, + model_columns=self._get_model_columns, ) explanation = rewriter.explain(query, strict=strict) self.last_engine_selection = rewriter.last_engine_selection diff --git a/sqlctx/core/transport_security.py b/sqlctx/core/transport_security.py index 6fbeee385..822b32ee2 100644 --- a/sqlctx/core/transport_security.py +++ b/sqlctx/core/transport_security.py @@ -192,6 +192,7 @@ def rewrite_transport_sql( ), rust_no_fallback=getattr(layer, "_rust_no_fallback", None), allow_non_additive_unsafe=getattr(layer, "allow_non_additive_unsafe", False), + model_columns=getattr(layer, "_get_model_columns", None), ) # Yardstick's explicit and implicit measure paths expand directly against # physical model tables. They do not currently route those reads through diff --git a/sqlctx/sql/query_rewriter.py b/sqlctx/sql/query_rewriter.py index 1be2f4bf9..42dd69b48 100644 --- a/sqlctx/sql/query_rewriter.py +++ b/sqlctx/sql/query_rewriter.py @@ -8,6 +8,7 @@ import warnings from collections.abc import Callable from dataclasses import dataclass, field +from functools import cache from typing import Any import sqlglot @@ -15,6 +16,7 @@ from sqlglot.errors import SqlglotError from sqlglot.tokens import TokenType +from sqlctx.core.model import Model from sqlctx.core.semantic_graph import SemanticGraph from sqlctx.rust_bridge import rewrite_semantic_input from sqlctx.semantic_handoff import ( @@ -158,6 +160,7 @@ def __init__( use_rust_rewriter: bool | None = None, rust_no_fallback: bool | None = None, allow_non_additive_unsafe: bool = False, + model_columns: Callable[[Model], list[dict]] | None = None, ): """Initialize query rewriter. @@ -169,8 +172,10 @@ def __init__( use_rust_rewriter: Override the environment-controlled Rust rewrite path rust_no_fallback: Reject unsupported Rust requirements instead of falling back allow_non_additive_unsafe: Aggregate all snapshots without semi-additive protection + model_columns: Optional catalog lookup for binding aliases on wildcard Yardstick views """ self.graph = graph + self._model_columns = model_columns self.dialect = dialect self.use_preaggregations = use_preaggregations self.allow_non_additive_unsafe = allow_non_additive_unsafe @@ -3700,18 +3705,31 @@ def _rewrite_yardstick_select_scope( if not scope_placeholders: return select_scope + # Physical columns take precedence over aliases. A wildcard import needs + # catalog metadata to prove a name is absent; resolve it only on collision. + @cache + def source_columns(model_name: str) -> set[str] | None: + model = self.graph.get_model(model_name) + names = {dimension.name.lower() for dimension in model.dimensions} + if self.dialect == "duckdb" and self._yardstick_view_has_wildcard(model): + columns = self._model_columns(model) if self._model_columns else [] + if not columns: + return None + names.update(column["column_name"].lower() for column in columns) + return names + + def can_bind_alias(name: str) -> bool: + names = source_columns(source_models[default_alias]) + return names is not None and name.lower() not in names + if single_model_scope and self.dialect == "duckdb": - model = self.graph.get_model(source_models[default_alias]) - known_columns = {dimension.name.lower() for dimension in model.dimensions} measure_aliases: dict[str, exp.Expression] = {} for projection in select_scope.expressions: expression = projection.this if isinstance(projection, exp.Alias) else projection replacements = { id(column): measure_aliases[column.name.lower()] for column in self._columns_without_nested_scopes(expression) - if not column.table - and column.name.lower() in measure_aliases - and column.name.lower() not in known_columns + if not column.table and column.name.lower() in measure_aliases and can_bind_alias(column.name) } if replacements: expanded = expression.transform( @@ -3816,7 +3834,6 @@ def _rewrite_yardstick_select_scope( if group_clause: self._resolve_yardstick_group_ordinals(group_clause, select_scope.expressions) if group_clause and default_alias and single_model_scope: - model = self.graph.get_model(source_models[default_alias]) group_aliases = { item.alias.lower(): item.this for item in select_scope.expressions if isinstance(item, exp.Alias) } @@ -3827,7 +3844,7 @@ def _rewrite_yardstick_select_scope( if isinstance(expr, exp.Column) and not expr.table and expr.name.lower() in group_aliases - and not model.get_dimension(expr.name) + and can_bind_alias(expr.name) else expr for expr in group_clause.expressions ], @@ -4733,6 +4750,10 @@ def _resolve_yardstick_dimension_expression( ) return expr, column.name + def _yardstick_view_has_wildcard(self, model: Model) -> bool: + view_sql = (model.metadata or {}).get("yardstick", {}).get("view_sql") + return bool(view_sql and any(item.is_star for item in parse_fragment(view_sql, self.dialect).expressions)) + def _expand_yardstick_measure_exclusions( self, select: exp.Select, source_models: dict[str, str], default_alias: str | None ) -> exp.Select: @@ -4767,8 +4788,7 @@ def _expand_yardstick_measure_exclusions( continue if explicit_view is None: - view = sqlglot.parse_one(view_sql, read=self.dialect) - explicit_view = not any(item.is_star for item in view.expressions) + explicit_view = not self._yardstick_view_has_wildcard(model) if not explicit_view: projections.append(projection) continue @@ -5157,6 +5177,7 @@ def _build_yardstick_context_dimensions( context_dimensions: list[dict[str, str]] = [] model = self.graph.get_model(model_name) seen_signatures: set[tuple[str, str]] = set() + wildcard_source = single_model_scope and self.dialect == "duckdb" and self._yardstick_view_has_wildcard(model) for raw_group_expr in group_expressions: expanded_group_expressions = self._expand_group_expression_for_yardstick_context(raw_group_expr) @@ -5209,7 +5230,12 @@ def _build_yardstick_context_dimensions( if dim_expr.strip().lower() == dimension.name.lower(): unsafe_aliases.add(dimension.name.lower()) - if projection_alias and projection_alias.lower() not in unsafe_aliases: + if wildcard_source: + # An output alias can shadow a physical column, or appear after + # the measure. Correlate on the qualified grouping key itself. + if not isinstance(outer_expr, exp.Column): + outer_sql = f"ANY_VALUE({outer_sql})" + elif projection_alias and projection_alias.lower() not in unsafe_aliases: outer_sql = exp.to_identifier(projection_alias).sql(dialect=self.dialect) context_dimensions.append( diff --git a/tests/queries/test_yardstick_measures_replay.py b/tests/queries/test_yardstick_measures_replay.py index 66cd921c8..b5a7e7bae 100644 --- a/tests/queries/test_yardstick_measures_replay.py +++ b/tests/queries/test_yardstick_measures_replay.py @@ -919,6 +919,49 @@ def test_replay_binds_measure_and_grouping_projection_aliases(tmp_path): _replay_yardstick_sql_test(path) +def test_wildcard_source_column_precedes_measure_projection_alias(tmp_path): + path = tmp_path / "wildcard-alias.test" + path.write_text( + """statement ok +CREATE TABLE sales(year INTEGER); + +statement ok +INSERT INTO sales VALUES (2022), (2022), (2023); + +statement ok +CREATE VIEW sales_v AS SELECT *, COUNT(*) AS MEASURE tally FROM sales; + +query II rowsort +SELECT AGGREGATE(tally) AS year, year + 1 AS next_year FROM sales_v; +---- +2\t2023 +1\t2024 +""" + ) + _replay_yardstick_sql_test(path) + + +def test_connected_wildcard_alias_checks_current_physical_columns(): + layer = SemanticLayer(connection="duckdb:///:memory:", engine="python") + try: + layer.adapter.execute("CREATE TABLE sales(amount INTEGER)") + layer.adapter.execute("INSERT INTO sales VALUES (10), (20), (30)") + _execute_statement_sql( + layer, YardstickAdapter(), "CREATE VIEW sales_v AS SELECT *, COUNT(*) AS MEASURE tally FROM sales" + ) + query = "SELECT AGGREGATE(tally) AS year, year + 1 AS next_year FROM sales_v ORDER BY next_year" + assert layer.sql(query).fetchall() == [(3, 4)] + + layer.adapter.execute("ALTER TABLE sales ADD COLUMN year INTEGER DEFAULT 2022") + layer.adapter.execute("UPDATE sales SET year = 2023 WHERE amount = 30") + assert layer.sql(query).fetchall() == [(2, 2023), (1, 2024)] + assert layer.sql( + "SELECT AGGREGATE(tally) AS year, year + 1 AS next_year FROM sales_v GROUP BY year ORDER BY next_year" + ).fetchall() == [(2, 2023), (1, 2024)] + finally: + layer.adapter.close() + + def test_parse_statement_record_preserves_batch_and_unterminated_error(tmp_path): path = tmp_path / "batch.test" path.write_text( diff --git a/tests/queries/test_yardstick_query_rewriter.py b/tests/queries/test_yardstick_query_rewriter.py index 1361c4d74..bd6facb7a 100644 --- a/tests/queries/test_yardstick_query_rewriter.py +++ b/tests/queries/test_yardstick_query_rewriter.py @@ -756,6 +756,43 @@ def test_yardstick_current_reads_the_context_at_its_position(yardstick_layer): ).fetchall() == [(225.0,)] +@pytest.mark.parametrize("replacement,expected", [("SET year=2022", 150.0), ("ALL year", 375.0)]) +def test_yardstick_current_filter_can_be_replaced(yardstick_layer, replacement, expected): + assert yardstick_layer.sql( + f"SELECT o.year, AGGREGATE(revenue) AT (WHERE year=CURRENT year {replacement}) " + "FROM sales_v o GROUP BY o.year ORDER BY o.year" + ).fetchall() == [(2022, expected), (2023, expected)] + + +def test_yardstick_current_filter_retains_independent_bindings(yardstick_layer): + assert yardstick_layer.sql( + "SELECT o.year, o.region, AGGREGATE(revenue) " + "AT (WHERE year=CURRENT year AND region=CURRENT region SET year=2022) " + "FROM sales_v o GROUP BY o.year, o.region ORDER BY o.year, o.region" + ).fetchall() == [(2022, "EU", 50.0), (2022, "US", 100.0), (2023, "EU", 50.0), (2023, "US", 100.0)] + # A later CURRENT reads the WHERE binding captured from the original group. + assert yardstick_layer.sql( + "SELECT o.year, AGGREGATE(revenue) " + "AT (WHERE year=CURRENT year SET year=CURRENT year-1) " + "FROM sales_v o GROUP BY o.year ORDER BY o.year" + ).fetchall() == [(2022, None), (2023, 150.0)] + + +@pytest.mark.parametrize("year", ["year", "s.year"]) +@pytest.mark.parametrize("grouping", ["", "GROUP BY year", "GROUP BY s.year", "GROUP BY next_year"]) +def test_yardstick_wildcard_grouping_precedes_measure_output_alias(tmp_path, year, grouping): + (tmp_path / "wildcard.sql").write_text("CREATE VIEW sales_v AS SELECT *, COUNT(*) AS MEASURE tally FROM sales;") + layer = SemanticLayer(connection="duckdb:///:memory:") + try: + layer.adapter.execute("CREATE TABLE sales(year INTEGER); INSERT INTO sales VALUES (2022), (2022), (2023)") + load_from_directory(layer, tmp_path) + assert layer.sql( + f"SELECT AGGREGATE(tally) AS year, {year}+1 AS next_year FROM sales_v s {grouping} ORDER BY next_year" + ).fetchall() == [(2, 2023), (1, 2024)] + finally: + layer.adapter.close() + + def test_yardstick_visible_set_projects_conjuncts_and_rejects_mixed_predicates(yardstick_layer): query = "SELECT year, AGGREGATE(revenue) AT (VISIBLE SET year = year - 1) FROM sales_v WHERE {}" assert yardstick_layer.sql(query.format("year = 2023 AND region = 'US'")).fetchall() == [(2023, 100.0)]