From ce47cf7f004af54455e91acde4c797688f3f20d0 Mon Sep 17 00:00:00 2001 From: vignesh_A Date: Sat, 21 Nov 2026 16:59:19 +0530 Subject: [PATCH 1/4] fix(validation): compare quoted identifiers as written in metrics Metric references, dataset-scoped scoping, AGG, and field shadowing compared SQL names with casefold, so SUM("Amount") matched field amount and AGG(orders."total") matched metric total. The mapping checker already follows expression_language.md: a regular identifier upper-cases, a quoted one matches as written. Reuse normalized_identifier and declared_name for those SQL lookups. YAML keys and relationship lists stay on dataset_field_names (casefold). The source qualifier is the regular identifier SOURCE; quoted "source" is not. --- validation/tests/test_validate.py | 125 +++++++++++++++- validation/validate.py | 234 +++++++++++++++++++++--------- 2 files changed, 290 insertions(+), 69 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 7c68d5b3..72d75d05 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -2861,6 +2861,31 @@ def test_dataset_scoped_metric_rejects_an_undeclared_field() -> None: assert any(error.startswith("[Scope]") and "'quantity'" in error for error in errors) +def test_dataset_scoped_metric_rejects_a_quoted_identifier_that_does_not_match() -> None: + # Quotes cause an exact match (expression_language.md). Field amount is AMOUNT. + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount")}], + metrics=[{"name": "total_amount", "expression": _ds_expr('SUM("Amount")')}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert any(error.startswith("[Scope]") and '"Amount"' in error for error in errors) + + +def test_dataset_scoped_metric_accepts_a_quoted_identifier_in_normalized_form() -> None: + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount")}], + metrics=[ + {"name": "quoted", "expression": _ds_expr('SUM("AMOUNT")')}, + {"name": "mixed", "expression": _ds_expr("SUM(Amount)")}, + {"name": "lower", "expression": _ds_expr("SUM(amount)")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [] + + def test_dataset_scoped_metric_accepts_source_columns() -> None: # The source qualifier is case insensitive, and reaches a column that a field # of the same name shadows. @@ -2876,6 +2901,18 @@ def test_dataset_scoped_metric_accepts_source_columns() -> None: assert _VALIDATE.validate_metric_scoping(doc) == [] +def test_dataset_scoped_metric_quoted_source_is_not_the_qualifier() -> None: + # Quoted "source" is the lowercase identifier, not the SOURCE qualifier. + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount")}], + metrics=[{"name": "total", "expression": _ds_expr('SUM("source".amount)')}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert any(error.startswith("[Scope]") and "qualified" in error for error in errors) + + def test_dataset_scoped_metric_rejects_a_three_part_source_reference() -> None: doc = _orders_with( metrics=[{"name": "total", "expression": _ds_expr("SUM(source.orders.amount)")}], @@ -3158,7 +3195,7 @@ def test_iter_expressions_yields_top_level_sql_as_ossie_sql_2026() -> None: assert (expr.kind, expr.dataset_name, expr.name) == ("field", "orders", "amount") assert (expr.dialect, expr.text, expr.superseded_by) == ("OSSIE_SQL_2026", "amount", None) - assert expr.field_names == frozenset({"amount"}) + assert expr.field_names == frozenset({"AMOUNT"}) def test_iter_expressions_yields_each_dialect_entry() -> None: @@ -3220,8 +3257,8 @@ def test_iter_expressions_covers_dataset_and_model_metrics_in_order() -> None: ("dataset_metric", "orders", "total"), ("model_metric", "", "avg_total"), ] - # Dataset members see the casefolded field names; model metrics see none. - assert exprs[1].field_names == frozenset({"amount"}) + # Dataset members see declared field names; model metrics see none. + assert exprs[1].field_names == frozenset({"AMOUNT"}) assert exprs[2].field_names == frozenset() @@ -3710,6 +3747,40 @@ def test_rejects_an_invalid_agg_call(expression: str, expected: str) -> None: assert not isinstance(errors[0], _VALIDATE.ValidationWarning) +def test_rejects_agg_of_a_quoted_metric_that_does_not_match() -> None: + errors = _field_reference_findings( + _model_metric_over_order_revenue('AGG(orders."order_revenue")') + ) + assert len(errors) == 1, errors + assert "'order_revenue' is not a dataset-scoped metric of dataset 'orders'" in errors[0] + assert not isinstance(errors[0], _VALIDATE.ValidationWarning) + + +def test_accepts_agg_of_a_quoted_metric_in_normalized_form() -> None: + assert _field_reference_findings( + _model_metric_over_order_revenue('AGG(orders."ORDER_REVENUE")') + ) == [] + assert _field_reference_findings( + _model_metric_over_order_revenue("AGG(ORDERS.order_revenue)") + ) == [] + + +def test_rejects_agg_of_quoted_lowercase_total() -> None: + document = _renamed_model() + document["datasets"][0]["metrics"] = [_metric("total", "SUM(total_usd)")] + document["metrics"] = [_metric("grand", 'AGG(orders."total")', "OSSIE_SQL_2026")] + errors = _field_reference_findings(document) + assert len(errors) == 1, errors + assert "'total' is not a dataset-scoped metric of dataset 'orders'" in errors[0] + + +def test_accepts_agg_of_quoted_uppercase_total() -> None: + document = _renamed_model() + document["datasets"][0]["metrics"] = [_metric("total", "SUM(total_usd)")] + document["metrics"] = [_metric("grand", 'AGG(orders."TOTAL")', "OSSIE_SQL_2026")] + assert _field_reference_findings(document) == [] + + def test_rejects_agg_in_a_field_expression() -> None: document = _renamed_model() document["datasets"][0]["fields"] = [{"name": "revenue", "expression": {"sql": "AGG(source.revenue)"}}] @@ -3752,6 +3823,16 @@ def test_accepts_agg_of_a_source_measure(expression: str) -> None: assert _source_measure_findings(_orders_metrics(revenue_total=expression)) == [] +def test_accepts_agg_of_quoted_source_in_normalized_form() -> None: + assert _source_measure_findings(_orders_metrics(revenue_total='AGG("SOURCE".revenue)')) == [] + + +def test_rejects_agg_of_quoted_lowercase_source() -> None: + errors = _source_measure_findings(_orders_metrics(revenue_total='AGG("source".revenue)')) + assert len(errors) == 1, errors + assert "AGG in a dataset-scoped metric takes" in errors[0] + + def test_accepts_a_model_that_evaluates_source_measures(core_schema: dict) -> None: # A model-scoped metric can evaluate a dataset-scoped metric that evaluates # a source measure. @@ -4155,7 +4236,9 @@ def test_field_shadowing_check_skips_dialects_that_are_not_sql_and_unparseable_s assert _field_reference_findings(document) == [] -@pytest.mark.parametrize("definition", ["(amount)", '"amount"', "amount -- the amount", "((amount))"]) +@pytest.mark.parametrize( + "definition", ["(amount)", "amount -- the amount", "((amount))"] +) def test_pass_through_is_read_from_the_parsed_definition(definition: str) -> None: document = _renamed_model() document["datasets"][0]["fields"] += [ @@ -4174,6 +4257,18 @@ def test_pass_through_compares_names_without_regard_to_case() -> None: assert _field_reference_findings(document) == [] +def test_quoted_pass_through_does_not_match_an_unquoted_field() -> None: + # "amount" is the lowercase identifier; field amount is the regular name AMOUNT. + document = _renamed_model() + document["datasets"][0]["fields"] += [ + _field("amount", '"amount"'), + _field("amount_cents", "amount * 100"), + ] + errors = _field_reference_findings(document) + assert len(errors) == 1 + assert "'amount' is the source column, not the field 'amount' defined as '\"amount\"'" in errors[0] + + def test_field_shadowing_check_compares_names_without_regard_to_case() -> None: document = _renamed_model() document["datasets"][0]["fields"].append(_field("total_eur", "Total_USD * 0.9")) @@ -4184,6 +4279,12 @@ def test_field_shadowing_check_compares_names_without_regard_to_case() -> None: assert "'Total_USD' is the source column, not the field 'total_usd'" in errors[0] +def test_quoted_identifier_does_not_shadow_a_regular_field() -> None: + document = _renamed_model() + document["datasets"][0]["fields"].append(_field("total_eur", '"total_usd" * 0.9')) + assert _field_reference_findings(document) == [] + + def test_field_shadowing_check_reads_a_date_part_as_a_unit_not_a_column() -> None: document = _renamed_model() document["datasets"][0]["fields"] += [ @@ -4405,6 +4506,22 @@ def test_metric_check_compares_names_without_regard_to_case() -> None: assert "'revenue' names the metric 'Revenue'" in errors[1] +def test_metric_quoted_identifier_matches_as_written() -> None: + document = _renamed_model(metrics=[ + _metric("ok_quoted", 'SUM(orders."TOTAL_USD")'), + _metric("ok_unquoted", "SUM(Orders.Total_Usd)"), + _metric("bad_quoted", 'SUM(orders."total_usd")'), + _metric("bad_amount", 'SUM(orders."amount")'), + ]) + + errors = _VALIDATE.validate_metric_references(document) + + assert len(errors) == 2 + assert all(isinstance(e, _VALIDATE.ValidationWarning) for e in errors) + assert any("'orders.\"total_usd\"' is not a declared field" in e for e in errors) + assert any("'orders.\"amount\"' is not a declared field" in e for e in errors) + + def test_datasets_that_differ_only_in_case_pool_their_fields() -> None: # Whether two such names may coexist is validate_unique_names' question; # the Name Resolution checks must not warn about either one's own fields. diff --git a/validation/validate.py b/validation/validate.py index 01c26e17..bd8dfe2a 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -623,7 +623,8 @@ def dataset_field_names(dataset: dict) -> frozenset[str]: Name Resolution (spec.md) treats primary_key, unique_keys, and relationship from_columns/to_columns as field names of that dataset. Comparison is - case-insensitive, matching dataset-scoped metric scoping. + case-insensitive. SQL identifiers in expressions use declared_name instead + (expression_language.md). """ names: list[str] = [] for field in dataset.get("fields") or []: @@ -957,20 +958,66 @@ def validate_relationship_column_arity(data: dict) -> list[str]: return errors +def _sql_ident(part) -> str: + """The normalized form of one parsed identifier (expression_language.md).""" + if SQLGLOT_AVAILABLE and isinstance(part, exp.Identifier): + return normalized_identifier(part) + name = getattr(part, "name", None) + return name.upper() if isinstance(name, str) else "" + + +def _column_idents(column) -> list: + """The Identifier parts of a column reference.""" + if not SQLGLOT_AVAILABLE: + return [] + return [part for part in column.parts if isinstance(part, exp.Identifier)] + + +def _column_written(column) -> str: + """The column as written, quotes included.""" + idents = _column_idents(column) + return ".".join(part.sql() for part in idents) if idents else str(column) + + +def _declared_member_names(members: object) -> set[str]: + """YAML names of fields or metrics, as declared_name compares them.""" + names: set[str] = set() + for member in as_list(members): + if not isinstance(member, dict): + continue + name = member.get("name") + if isinstance(name, str) and name: + names.add(declared_name(name)) + return names + + +def _expression_field_names(dataset: dict) -> frozenset[str]: + """The enclosing dataset's field names as SQL identifiers compare them. + + YAML key and relationship lists still use dataset_field_names (casefold). + """ + if SQLGLOT_AVAILABLE: + return frozenset(_declared_member_names(dataset.get("fields"))) + return dataset_field_names(dataset) + + def declared_fields(model: dict) -> dict[str, set[str]]: - """Return the case-folded field names each dataset declares. + """The declared names of the fields each dataset declares, keyed by + declared dataset name (expression_language.md). - Names are read as dataset_field_names does, keyed by case-folded dataset - name. A dataset without a fields list declares none: model-level constructs - do not reach through a dataset to its source (spec.md, Name Resolution). + A dataset without a fields list declares none: model-level constructs do + not reach through a dataset to its source (spec.md, Name Resolution). + YAML key and relationship lists still use dataset_field_names (casefold). """ fields: dict[str, set[str]] = {} for d in as_list(model.get("datasets")): if not isinstance(d, dict) or not isinstance(d.get("name"), str): continue # Datasets whose names differ only by case pool their fields rather - # than hide each other's. - fields.setdefault(d["name"].casefold(), set()).update(dataset_field_names(d)) + # than hide each other's: regular identifiers upper-case to one key. + fields.setdefault(declared_name(d["name"]), set()).update( + _declared_member_names(d.get("fields")) + ) return fields @@ -1067,16 +1114,14 @@ def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]: def declared_dataset_metrics(model: dict) -> dict[str, set[str]]: - """Return the case-folded dataset-scoped metric names each dataset declares. - - Names are keyed by case-folded dataset name. - """ + """The declared names of the dataset-scoped metrics each dataset + declares, keyed by declared dataset name (expression_language.md).""" metrics: dict[str, set[str]] = {} for d in as_list(model.get("datasets")): if not isinstance(d, dict) or not isinstance(d.get("name"), str): continue - metrics.setdefault(d["name"].casefold(), set()).update( - m["name"].casefold() for m in as_list(d.get("metrics")) if isinstance(m, dict) and isinstance(m.get("name"), str) + metrics.setdefault(declared_name(d["name"]), set()).update( + _declared_member_names(d.get("metrics")) ) return metrics @@ -1102,16 +1147,20 @@ def validate_metric_references(data: dict) -> list[str]: dataset_metrics = declared_dataset_metrics(data) field_names = set().union(*fields.values()) if fields else set() metrics = [m for m in as_list(data.get("metrics")) if isinstance(m, dict)] - declared_metrics = {m["name"].casefold(): m["name"] for m in metrics if isinstance(m.get("name"), str)} + declared_metrics = { + declared_name(m["name"]): m["name"] + for m in metrics if isinstance(m.get("name"), str) + } findings = [] for metric in metrics: metric_name = metric.get("name", "") - own_name = metric_name.casefold() if isinstance(metric.get("name"), str) else None + own_name = declared_name(metric_name) if isinstance(metric.get("name"), str) else None # A bare name that is another metric, and not also a field or this # metric itself, was most likely meant as that metric. other_metrics = { - folded: name for folded, name in declared_metrics.items() if folded not in field_names and folded != own_name + key: name for key, name in declared_metrics.items() + if key not in field_names and key != own_name } for expression in read_expressions(metric, "model_metric"): context = expression.context(model_name) @@ -1136,30 +1185,49 @@ def validate_metric_references(data: dict) -> list[str]: for column in iter_columns(tree, expression.dialect): if id(column) in agg_arguments: continue - key = tuple(part.name.casefold() for part in column.parts) + idents = _column_idents(column) + key = tuple(_sql_ident(part) for part in idents) if key in seen: continue seen.add(key) - name, table = column.name.casefold(), column.table.casefold() - if column.db: - written = ".".join(part.name for part in column.parts) - message = f"'{written}' has more than two parts; metric expressions refer to fields as dataset.field" - elif not column.table and name in other_metrics: + written = _column_written(column) + name = key[-1] if key else "" + table = key[-2] if len(key) >= 2 else "" + if column.db or len(key) > 2: + message = ( + f"'{written}' has more than two parts; metric expressions refer to " + f"fields as dataset.field" + ) + elif not table and name in other_metrics: message = ( - f"'{column.name}' names the metric '{other_metrics[name]}'; " + f"'{written}' names the metric '{other_metrics[name]}'; " f"metric expressions cannot refer to other metrics" ) - elif not column.table: - message = f"'{column.name}' is not qualified; metric expressions refer to fields as dataset.field" + elif not table: + message = ( + f"'{written}' is not qualified; metric expressions refer to fields " + f"as dataset.field" + ) elif table not in fields: - message = f"'{column.table}.{column.name}' references unknown dataset '{column.table}'" - elif portable and name not in fields[table] and name in dataset_metrics.get(table, set()): message = ( - f"'{column.table}.{column.name}' names a dataset-scoped metric; " - f"write AGG({column.table}.{column.name}) to evaluate it" + f"'{written}' references unknown dataset " + f"'{idents[0].name if idents else column.table}'" + ) + elif ( + portable + and name not in fields[table] + and name in dataset_metrics.get(table, set()) + ): + message = ( + f"'{written}' names a dataset-scoped metric; " + f"write AGG({written}) to evaluate it" ) elif name not in fields[table]: - message = f"'{column.table}.{column.name}' is not a declared field of dataset '{column.table}'" + dataset_label = idents[0].name if idents else column.table + message = ( + f"'{written}' is not a declared field of dataset " + f"'{dataset_label}'" + ) else: continue findings.append(ValidationWarning(f"[Reference] Warning: {context}: {message}")) @@ -1179,18 +1247,33 @@ def agg_argument_problem( expected = "AGG takes a single dataset.metric reference to a dataset-scoped metric" if not isinstance(arg, exp.Column) or isinstance(arg.this, exp.Star) or arg.db: return f"AGG({arg.sql() if arg else ''}): {expected}" - name, table = arg.name.casefold(), arg.table.casefold() - if not arg.table: + idents = _column_idents(arg) + key = tuple(_sql_ident(part) for part in idents) + name = key[-1] if key else "" + table = key[-2] if len(key) >= 2 else "" + written = _column_written(arg) + if not table: if name in model_metrics: - return f"AGG({arg.name}) names the model-scoped metric '{model_metrics[name]}'; {expected}" - return f"AGG({arg.name}) is not qualified; {expected}" + return ( + f"AGG({written}) names the model-scoped metric '{model_metrics[name]}'; " + f"{expected}" + ) + return f"AGG({written}) is not qualified; {expected}" if table not in fields: - return f"AGG({arg.table}.{arg.name}) references unknown dataset '{arg.table}'" + dataset_label = idents[0].name if idents else arg.table + return f"AGG({written}) references unknown dataset '{dataset_label}'" if name in dataset_metrics.get(table, set()): return None if name in fields[table]: - return f"AGG({arg.table}.{arg.name}) names a field, and fields are never measures; {expected}" - return f"AGG({arg.table}.{arg.name}): '{arg.name}' is not a dataset-scoped metric of dataset '{arg.table}'" + return ( + f"AGG({written}) names a field, and fields are never measures; " + f"{expected}" + ) + dataset_label = idents[0].name if idents else arg.table + return ( + f"AGG({written}): '{idents[-1].name if idents else arg.name}' is not a " + f"dataset-scoped metric of dataset '{dataset_label}'" + ) def validate_field_shadowing(data: dict) -> list[str]: @@ -1208,10 +1291,13 @@ def validate_field_shadowing(data: dict) -> list[str]: model_name = data.get("name", "") warnings = [] - def passes_through(tree, name: str) -> bool: + def passes_through(tree, ident: str) -> bool: while isinstance(tree, (exp.Paren, exp.Alias)): tree = tree.this - return isinstance(tree, exp.Column) and not tree.table and tree.name.casefold() == name.casefold() + if not isinstance(tree, exp.Column) or tree.table: + return False + idents = _column_idents(tree) + return len(idents) == 1 and _sql_ident(idents[0]) == ident for dataset in as_list(data.get("datasets")): if not isinstance(dataset, dict): @@ -1222,17 +1308,27 @@ def passes_through(tree, name: str) -> bool: # the one other expressions are compared against. by_name: dict[str, dict] = {} for f in declared: - by_name.setdefault(f["name"].casefold(), f) + by_name.setdefault(declared_name(f["name"]), f) for field in declared: + field_key = declared_name(field["name"]) for expression in read_expressions(field, "field", dataset_name): context = expression.context(model_name) tree = parse_tree(expression.text, expression.dialect, context) if tree is None: continue - names = [c.name for c in iter_columns(tree, expression.dialect) if not c.table] - for name in dict.fromkeys(names): - other = by_name.get(name.casefold()) - if other is None or other["name"].casefold() == field["name"].casefold(): + seen = set() + for column in iter_columns(tree, expression.dialect): + if column.table: + continue + idents = _column_idents(column) + if not idents: + continue + key = _sql_ident(idents[0]) + if key in seen: + continue + seen.add(key) + other = by_name.get(key) + if other is None or declared_name(other["name"]) == field_key: continue definitions = read_expressions(other, "field", dataset_name, expression.dialect) or read_expressions( other, "field", dataset_name @@ -1243,14 +1339,13 @@ def passes_through(tree, name: str) -> bool: for d in definitions if (tree := parse_tree(d.text, d.dialect, d.context(model_name))) is not None ] - if not parsed or any(passes_through(t, name) for _, t in parsed): + if not parsed or any(passes_through(t, key) for _, t in parsed): continue - warnings.append( - ValidationWarning( - f"[Reference] Warning: {context}: '{name}' is the source column, not the " - f"field '{other['name']}' defined as '{parsed[0][0]}'" - ) - ) + written = _column_written(column) + warnings.append(ValidationWarning( + f"[Reference] Warning: {context}: '{written}' is the source column, not the " + f"field '{other['name']}' defined as '{parsed[0][0]}'" + )) return warnings @@ -1527,7 +1622,8 @@ class Expression: `kind` identifies the declaring element, and `name` identifies the field or metric. `dialect` is OSSIE_SQL_2026 for portable `sql` expressions, or the dialect's label otherwise. `field_names` contains the enclosing - dataset's field names, or is empty for model-scoped metrics. + dataset's field names as declared_name compares them + (expression_language.md), or is empty for model-scoped metrics. `superseded_by` is the authoritative top-level `sql` text when this is an OSSIE_SQL_2026 dialect entry that `sql` outranks, else None: such an entry is non-authoritative, since a client reads the `sql` instead. @@ -1597,7 +1693,7 @@ def iter_expressions(data: dict) -> Iterator[Expression]: """ for dataset in data.get("datasets", []): dataset_name = dataset.get("name", "") - field_names = dataset_field_names(dataset) + field_names = _expression_field_names(dataset) for field in dataset.get("fields", []): yield from _expressions_in(field, "field", dataset_name, field_names) for metric in dataset.get("metrics", []): @@ -1958,7 +2054,8 @@ def validate_metric_agreement(data: dict) -> list[str]: # The qualifier for a dataset's source columns in its dataset-scoped metrics. -SOURCE_QUALIFIER = "source" +# Regular identifier `source` / `SOURCE` / `"SOURCE"`; quoted `"source"` is not. +SOURCE_QUALIFIER = "SOURCE" def validate_metric_scoping(data: dict) -> list[str]: @@ -1971,8 +2068,9 @@ def validate_metric_scoping(data: dict) -> list[str]: * No other qualified reference (`dataset.field`): that is model-scoped and belongs in the model-root metrics. * Every unqualified name must be a declared field of the dataset. A bare name - is compared case-insensitively; `COUNT(*)`, literals and the unit of a - date function reference no field and are fine. + is compared as a normalized identifier (expression_language.md); + `COUNT(*)`, literals and the unit of a date function reference no field + and are fine. * `source.column` is not allowed when the dataset declares a field named `source`, since the field takes precedence over the qualifier. @@ -2007,13 +2105,16 @@ def scope_errors(expression: Expression) -> list[str]: for col in (*iter_columns(tree, expression.dialect), *qualified_stars): if id(col) in inside_agg: continue - parts = [part.name for part in col.parts] - if len(parts) == 2 and parts[0].casefold() == SOURCE_QUALIFIER: - uses_source = True - elif len(parts) > 1 and parts[0]: - qualifiers.add(parts[0]) - elif parts and parts[0].casefold() not in expression.field_names: - undeclared.add(parts[0]) + idents = _column_idents(col) + first = _sql_ident(idents[0]) if idents else "" + written_first = idents[0].sql() if idents else (col.table or col.name or "") + if col.table: + if first == SOURCE_QUALIFIER and not col.db: + uses_source = True + elif written_first: + qualifiers.add(idents[0].name if idents else col.table) + elif first and first not in expression.field_names: + undeclared.add(written_first) prefix = ( f"[Scope] Dataset-scoped metric '{expression.dataset_name}.{expression.name}' " @@ -2064,12 +2165,15 @@ def source_agg_problem(call, field_names: frozenset[str]) -> str | None: """ expected = "AGG in a dataset-scoped metric takes a single source.measure reference" arg = call.this + idents = _column_idents(arg) if isinstance(arg, exp.Column) else [] + table = _sql_ident(idents[0]) if len(idents) >= 2 else "" + name = _sql_ident(idents[-1]) if idents else "" if ( not isinstance(arg, exp.Column) or isinstance(arg.this, exp.Star) or arg.db - or arg.table.casefold() != SOURCE_QUALIFIER - or not arg.name + or table != SOURCE_QUALIFIER + or not name ): return f"AGG({arg.sql() if arg else ''}): {expected}" if SOURCE_QUALIFIER in field_names: From 6320ebb3e3a29eaa17d3f50f09e12ededb527865 Mon Sep 17 00:00:00 2001 From: vignesh_A Date: Mon, 23 Nov 2026 14:18:16 +0530 Subject: [PATCH 2/4] fix(validation): apply Ossie quoting only to OSSIE_SQL_2026 Quoted versus unquoted identifier matching is DB specific (expression_language.md). Vendor dialects keep the case-insensitive lookup they had; POSTGRES SUM("amount") and BIGQUERY SUM(`amount`) against field amount stay valid. Quiet declared_name the same way as other probes, so it is not the first unquieted parse on the validate_sql path. Print identifiers as written in AGG and scope labels. --- validation/tests/test_validate.py | 55 ++++++-- validation/validate.py | 205 ++++++++++++++++++++---------- 2 files changed, 182 insertions(+), 78 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 72d75d05..c45fa673 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -2886,6 +2886,20 @@ def test_dataset_scoped_metric_accepts_a_quoted_identifier_in_normalized_form() assert _VALIDATE.validate_metric_scoping(doc) == [] +def test_dataset_scoped_metric_vendor_dialect_compares_quoted_names_without_regard_to_case() -> None: + # Quoted versus unquoted matching is DB specific; vendor dialects keep the + # case-insensitive comparison they had before the OSSIE_SQL_2026 quoting rule. + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount")}], + metrics=[ + {"name": "pg", "expression": _ds_expr('SUM("amount")', "POSTGRES")}, + {"name": "bq", "expression": _ds_expr("SUM(`amount`)", "BIGQUERY")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [] + + def test_dataset_scoped_metric_accepts_source_columns() -> None: # The source qualifier is case insensitive, and reaches a column that a field # of the same name shadows. @@ -3752,7 +3766,7 @@ def test_rejects_agg_of_a_quoted_metric_that_does_not_match() -> None: _model_metric_over_order_revenue('AGG(orders."order_revenue")') ) assert len(errors) == 1, errors - assert "'order_revenue' is not a dataset-scoped metric of dataset 'orders'" in errors[0] + assert "'\"order_revenue\"' is not a dataset-scoped metric of dataset 'orders'" in errors[0] assert not isinstance(errors[0], _VALIDATE.ValidationWarning) @@ -3771,7 +3785,7 @@ def test_rejects_agg_of_quoted_lowercase_total() -> None: document["metrics"] = [_metric("grand", 'AGG(orders."total")', "OSSIE_SQL_2026")] errors = _field_reference_findings(document) assert len(errors) == 1, errors - assert "'total' is not a dataset-scoped metric of dataset 'orders'" in errors[0] + assert "'\"total\"' is not a dataset-scoped metric of dataset 'orders'" in errors[0] def test_accepts_agg_of_quoted_uppercase_total() -> None: @@ -4261,8 +4275,8 @@ def test_quoted_pass_through_does_not_match_an_unquoted_field() -> None: # "amount" is the lowercase identifier; field amount is the regular name AMOUNT. document = _renamed_model() document["datasets"][0]["fields"] += [ - _field("amount", '"amount"'), - _field("amount_cents", "amount * 100"), + _field("amount", '"amount"', "OSSIE_SQL_2026"), + _field("amount_cents", "amount * 100", "OSSIE_SQL_2026"), ] errors = _field_reference_findings(document) assert len(errors) == 1 @@ -4281,10 +4295,22 @@ def test_field_shadowing_check_compares_names_without_regard_to_case() -> None: def test_quoted_identifier_does_not_shadow_a_regular_field() -> None: document = _renamed_model() - document["datasets"][0]["fields"].append(_field("total_eur", '"total_usd" * 0.9')) + document["datasets"][0]["fields"].append( + _field("total_eur", '"total_usd" * 0.9', "OSSIE_SQL_2026") + ) assert _field_reference_findings(document) == [] +def test_quoted_identifier_in_vendor_dialect_shadows_without_regard_to_case() -> None: + document = _renamed_model() + document["datasets"][0]["fields"].append( + _field("total_eur", '"total_usd" * 0.9', "POSTGRES") + ) + errors = _field_reference_findings(document) + assert len(errors) == 1 + assert "'\"total_usd\"' is the source column, not the field 'total_usd'" in errors[0] + + def test_field_shadowing_check_reads_a_date_part_as_a_unit_not_a_column() -> None: document = _renamed_model() document["datasets"][0]["fields"] += [ @@ -4508,10 +4534,10 @@ def test_metric_check_compares_names_without_regard_to_case() -> None: def test_metric_quoted_identifier_matches_as_written() -> None: document = _renamed_model(metrics=[ - _metric("ok_quoted", 'SUM(orders."TOTAL_USD")'), - _metric("ok_unquoted", "SUM(Orders.Total_Usd)"), - _metric("bad_quoted", 'SUM(orders."total_usd")'), - _metric("bad_amount", 'SUM(orders."amount")'), + _metric("ok_quoted", 'SUM(orders."TOTAL_USD")', "OSSIE_SQL_2026"), + _metric("ok_unquoted", "SUM(Orders.Total_Usd)", "OSSIE_SQL_2026"), + _metric("bad_quoted", 'SUM(orders."total_usd")', "OSSIE_SQL_2026"), + _metric("bad_amount", 'SUM(orders."amount")', "OSSIE_SQL_2026"), ]) errors = _VALIDATE.validate_metric_references(document) @@ -4522,6 +4548,17 @@ def test_metric_quoted_identifier_matches_as_written() -> None: assert any("'orders.\"amount\"' is not a declared field" in e for e in errors) +def test_metric_vendor_dialect_compares_quoted_names_without_regard_to_case() -> None: + # Quoted versus unquoted matching is DB specific; vendor dialects keep the + # case-insensitive comparison they had before the OSSIE_SQL_2026 quoting rule. + document = _renamed_model(metrics=[ + _metric("pg", 'SUM(orders."total_usd")', "POSTGRES"), + _metric("bq", "SUM(orders.`total_usd`)", "BIGQUERY"), + ]) + + assert _VALIDATE.validate_metric_references(document) == [] + + def test_datasets_that_differ_only_in_case_pool_their_fields() -> None: # Whether two such names may coexist is validate_unique_names' question; # the Name Resolution checks must not warn about either one's own fields. diff --git a/validation/validate.py b/validation/validate.py index bd8dfe2a..eadda5ae 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -958,12 +958,33 @@ def validate_relationship_column_arity(data: dict) -> list[str]: return errors -def _sql_ident(part) -> str: - """The normalized form of one parsed identifier (expression_language.md).""" - if SQLGLOT_AVAILABLE and isinstance(part, exp.Identifier): - return normalized_identifier(part) +def _uses_ossie_quoting(dialect: str) -> bool: + """The quoting table in expression_language.md is for OSSIE_SQL_2026. + + Quoted versus unquoted comparison is DB specific in other dialects. + """ + return dialect == PORTABLE_DIALECT + + +def _sql_ident(part, dialect: str = PORTABLE_DIALECT) -> str: + """The comparison key of one parsed identifier. + + OSSIE_SQL_2026 follows expression_language.md: a quoted identifier as + written, a regular one upper-cased. Other dialects compare case-insensitively. + """ name = getattr(part, "name", None) - return name.upper() if isinstance(name, str) else "" + if not isinstance(name, str): + return "" + if _uses_ossie_quoting(dialect): + if SQLGLOT_AVAILABLE and isinstance(part, exp.Identifier): + return normalized_identifier(part) + return name.upper() + return name.casefold() + + +def _declared_key(name: str, dialect: str = PORTABLE_DIALECT) -> str: + """YAML name as SQL identifiers in this dialect compare it.""" + return declared_name(name) if _uses_ossie_quoting(dialect) else name.casefold() def _column_idents(column) -> list: @@ -973,37 +994,42 @@ def _column_idents(column) -> list: return [part for part in column.parts if isinstance(part, exp.Identifier)] +def _ident_written(part) -> str: + """One identifier as written, quotes included.""" + return part.sql() if hasattr(part, "sql") else getattr(part, "name", "") or "" + + def _column_written(column) -> str: """The column as written, quotes included.""" idents = _column_idents(column) - return ".".join(part.sql() for part in idents) if idents else str(column) + return ".".join(_ident_written(part) for part in idents) if idents else str(column) -def _declared_member_names(members: object) -> set[str]: - """YAML names of fields or metrics, as declared_name compares them.""" +def _declared_member_names(members: object, dialect: str = PORTABLE_DIALECT) -> set[str]: + """YAML names of fields or metrics, as this dialect compares them.""" names: set[str] = set() for member in as_list(members): if not isinstance(member, dict): continue name = member.get("name") if isinstance(name, str) and name: - names.add(declared_name(name)) + names.add(_declared_key(name, dialect)) return names -def _expression_field_names(dataset: dict) -> frozenset[str]: +def _expression_field_names(dataset: dict, dialect: str = PORTABLE_DIALECT) -> frozenset[str]: """The enclosing dataset's field names as SQL identifiers compare them. YAML key and relationship lists still use dataset_field_names (casefold). """ if SQLGLOT_AVAILABLE: - return frozenset(_declared_member_names(dataset.get("fields"))) + return frozenset(_declared_member_names(dataset.get("fields"), dialect)) return dataset_field_names(dataset) -def declared_fields(model: dict) -> dict[str, set[str]]: +def declared_fields(model: dict, dialect: str = PORTABLE_DIALECT) -> dict[str, set[str]]: """The declared names of the fields each dataset declares, keyed by - declared dataset name (expression_language.md). + dataset name as this dialect compares them (expression_language.md). A dataset without a fields list declares none: model-level constructs do not reach through a dataset to its source (spec.md, Name Resolution). @@ -1015,8 +1041,8 @@ def declared_fields(model: dict) -> dict[str, set[str]]: continue # Datasets whose names differ only by case pool their fields rather # than hide each other's: regular identifiers upper-case to one key. - fields.setdefault(declared_name(d["name"]), set()).update( - _declared_member_names(d.get("fields")) + fields.setdefault(_declared_key(d["name"], dialect), set()).update( + _declared_member_names(d.get("fields"), dialect) ) return fields @@ -1113,15 +1139,15 @@ def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]: yield exp.column(unit.name) -def declared_dataset_metrics(model: dict) -> dict[str, set[str]]: +def declared_dataset_metrics(model: dict, dialect: str = PORTABLE_DIALECT) -> dict[str, set[str]]: """The declared names of the dataset-scoped metrics each dataset - declares, keyed by declared dataset name (expression_language.md).""" + declares, keyed by dataset name as this dialect compares them.""" metrics: dict[str, set[str]] = {} for d in as_list(model.get("datasets")): if not isinstance(d, dict) or not isinstance(d.get("name"), str): continue - metrics.setdefault(declared_name(d["name"]), set()).update( - _declared_member_names(d.get("metrics")) + metrics.setdefault(_declared_key(d["name"], dialect), set()).update( + _declared_member_names(d.get("metrics"), dialect) ) return metrics @@ -1143,34 +1169,46 @@ def validate_metric_references(data: dict) -> list[str]: if not SQLGLOT_AVAILABLE or not isinstance(data, dict) or "datasets" not in data: return [] model_name = data.get("name", "") - fields = declared_fields(data) - dataset_metrics = declared_dataset_metrics(data) - field_names = set().union(*fields.values()) if fields else set() metrics = [m for m in as_list(data.get("metrics")) if isinstance(m, dict)] - declared_metrics = { - declared_name(m["name"]): m["name"] - for m in metrics if isinstance(m.get("name"), str) - } + maps: dict[str, tuple] = {} + + def maps_for(dialect: str): + if dialect not in maps: + fields = declared_fields(data, dialect) + dataset_metrics = declared_dataset_metrics(data, dialect) + field_names = set().union(*fields.values()) if fields else set() + declared_metrics = { + _declared_key(m["name"], dialect): m["name"] + for m in metrics if isinstance(m.get("name"), str) + } + maps[dialect] = (fields, dataset_metrics, field_names, declared_metrics) + return maps[dialect] + findings = [] for metric in metrics: metric_name = metric.get("name", "") - own_name = declared_name(metric_name) if isinstance(metric.get("name"), str) else None - # A bare name that is another metric, and not also a field or this - # metric itself, was most likely meant as that metric. - other_metrics = { - key: name for key, name in declared_metrics.items() - if key not in field_names and key != own_name - } for expression in read_expressions(metric, "model_metric"): context = expression.context(model_name) tree = parse_tree(expression.text, expression.dialect, context) if tree is None: continue + dialect = expression.dialect + fields, dataset_metrics, field_names, declared_metrics = maps_for(dialect) + own_name = ( + _declared_key(metric_name, dialect) + if isinstance(metric.get("name"), str) else None + ) + # A bare name that is another metric, and not also a field or this + # metric itself, was most likely meant as that metric. + other_metrics = { + key: name for key, name in declared_metrics.items() + if key not in field_names and key != own_name + } # AGG is defined only for OSSIE_SQL_2026; other dialects are read as # before. In OSSIE_SQL_2026, the argument of each AGG call is checked # here, so the column loop below skips every column inside it. - portable = expression.dialect == PORTABLE_DIALECT + portable = _uses_ossie_quoting(dialect) agg_arguments = set() for call in tree.find_all(exp.Agg) if portable else (): arg = call.this @@ -1182,17 +1220,20 @@ def validate_metric_references(data: dict) -> list[str]: if message: findings.append(f"[Reference] {context}: {message}") seen = set() - for column in iter_columns(tree, expression.dialect): + for column in iter_columns(tree, dialect): if id(column) in agg_arguments: continue idents = _column_idents(column) - key = tuple(_sql_ident(part) for part in idents) + key = tuple(_sql_ident(part, dialect) for part in idents) if key in seen: continue seen.add(key) written = _column_written(column) name = key[-1] if key else "" table = key[-2] if len(key) >= 2 else "" + dataset_label = ( + _ident_written(idents[0]) if idents else column.table + ) if column.db or len(key) > 2: message = ( f"'{written}' has more than two parts; metric expressions refer to " @@ -1211,7 +1252,7 @@ def validate_metric_references(data: dict) -> list[str]: elif table not in fields: message = ( f"'{written}' references unknown dataset " - f"'{idents[0].name if idents else column.table}'" + f"'{dataset_label}'" ) elif ( portable @@ -1223,7 +1264,6 @@ def validate_metric_references(data: dict) -> list[str]: f"write AGG({written}) to evaluate it" ) elif name not in fields[table]: - dataset_label = idents[0].name if idents else column.table message = ( f"'{written}' is not a declared field of dataset " f"'{dataset_label}'" @@ -1252,6 +1292,8 @@ def agg_argument_problem( name = key[-1] if key else "" table = key[-2] if len(key) >= 2 else "" written = _column_written(arg) + metric_label = _ident_written(idents[-1]) if idents else arg.name + dataset_label = _ident_written(idents[0]) if idents else arg.table if not table: if name in model_metrics: return ( @@ -1260,7 +1302,6 @@ def agg_argument_problem( ) return f"AGG({written}) is not qualified; {expected}" if table not in fields: - dataset_label = idents[0].name if idents else arg.table return f"AGG({written}) references unknown dataset '{dataset_label}'" if name in dataset_metrics.get(table, set()): return None @@ -1269,9 +1310,8 @@ def agg_argument_problem( f"AGG({written}) names a field, and fields are never measures; " f"{expected}" ) - dataset_label = idents[0].name if idents else arg.table return ( - f"AGG({written}): '{idents[-1].name if idents else arg.name}' is not a " + f"AGG({written}): '{metric_label}' is not a " f"dataset-scoped metric of dataset '{dataset_label}'" ) @@ -1291,13 +1331,13 @@ def validate_field_shadowing(data: dict) -> list[str]: model_name = data.get("name", "") warnings = [] - def passes_through(tree, ident: str) -> bool: + def passes_through(tree, ident: str, dialect: str) -> bool: while isinstance(tree, (exp.Paren, exp.Alias)): tree = tree.this if not isinstance(tree, exp.Column) or tree.table: return False idents = _column_idents(tree) - return len(idents) == 1 and _sql_ident(idents[0]) == ident + return len(idents) == 1 and _sql_ident(idents[0], dialect) == ident for dataset in as_list(data.get("datasets")): if not isinstance(dataset, dict): @@ -1305,30 +1345,40 @@ def passes_through(tree, ident: str) -> bool: dataset_name = dataset.get("name", "") declared = [f for f in as_list(dataset.get("fields")) if isinstance(f, dict) and isinstance(f.get("name"), str)] # Of two fields whose names differ only by case, the first declared is - # the one other expressions are compared against. - by_name: dict[str, dict] = {} - for f in declared: - by_name.setdefault(declared_name(f["name"]), f) + # the one other expressions are compared against. The key is dialect + # specific: OSSIE_SQL_2026 uses declared_name, other dialects casefold. + by_name_for: dict[str, dict[str, dict]] = {} + + def by_name(dialect: str) -> dict[str, dict]: + if dialect not in by_name_for: + keyed: dict[str, dict] = {} + for f in declared: + keyed.setdefault(_declared_key(f["name"], dialect), f) + by_name_for[dialect] = keyed + return by_name_for[dialect] + for field in declared: - field_key = declared_name(field["name"]) for expression in read_expressions(field, "field", dataset_name): context = expression.context(model_name) tree = parse_tree(expression.text, expression.dialect, context) if tree is None: continue + dialect = expression.dialect + keyed = by_name(dialect) + field_key = _declared_key(field["name"], dialect) seen = set() - for column in iter_columns(tree, expression.dialect): + for column in iter_columns(tree, dialect): if column.table: continue idents = _column_idents(column) if not idents: continue - key = _sql_ident(idents[0]) + key = _sql_ident(idents[0], dialect) if key in seen: continue seen.add(key) - other = by_name.get(key) - if other is None or declared_name(other["name"]) == field_key: + other = keyed.get(key) + if other is None or _declared_key(other["name"], dialect) == field_key: continue definitions = read_expressions(other, "field", dataset_name, expression.dialect) or read_expressions( other, "field", dataset_name @@ -1339,7 +1389,7 @@ def passes_through(tree, ident: str) -> bool: for d in definitions if (tree := parse_tree(d.text, d.dialect, d.context(model_name))) is not None ] - if not parsed or any(passes_through(t, key) for _, t in parsed): + if not parsed or any(passes_through(t, key, dialect) for _, t in parsed): continue written = _column_written(column) warnings.append(ValidationWarning( @@ -1622,7 +1672,7 @@ class Expression: `kind` identifies the declaring element, and `name` identifies the field or metric. `dialect` is OSSIE_SQL_2026 for portable `sql` expressions, or the dialect's label otherwise. `field_names` contains the enclosing - dataset's field names as declared_name compares them + dataset's field names as this expression's dialect compares them (expression_language.md), or is empty for model-scoped metrics. `superseded_by` is the authoritative top-level `sql` text when this is an OSSIE_SQL_2026 dialect entry that `sql` outranks, else None: such an entry @@ -1648,13 +1698,25 @@ def context(self, model_name: str) -> str: return f"{self.label()} in model '{model_name}' ({self.dialect})" -def _expressions_in(member: dict, kind: ExpressionKind, dataset_name: str, field_names: frozenset[str]) -> Iterator[Expression]: +def _expressions_in( + member: dict, kind: ExpressionKind, dataset_name: str, dataset: dict | None = None, +) -> Iterator[Expression]: + # Shapes the schema rejects are skipped, not read, so a check called directly # on an unvetted document reports nothing rather than failing. expression = member.get("expression") if not isinstance(expression, dict): return name = member.get("name", "") + names_cache: dict[str, frozenset[str]] = {} + + def names_for(dialect: str) -> frozenset[str]: + if dataset is None: + return frozenset() + if dialect not in names_cache: + names_cache[dialect] = _expression_field_names(dataset, dialect) + return names_cache[dialect] + sql = expression.get("sql") if sql is not None: yield Expression( @@ -1663,7 +1725,7 @@ def _expressions_in(member: dict, kind: ExpressionKind, dataset_name: str, field name=name, dialect=PORTABLE_DIALECT, text=sql, - field_names=field_names, + field_names=names_for(PORTABLE_DIALECT), ) for dialect_expr in as_list(expression.get("dialects")): if not isinstance(dialect_expr, dict): @@ -1678,7 +1740,7 @@ def _expressions_in(member: dict, kind: ExpressionKind, dataset_name: str, field name=name, dialect=dialect, text=text, - field_names=field_names, + field_names=names_for(dialect), # A top-level `sql` is the authoritative OSSIE_SQL_2026 form, so an # OSSIE_SQL_2026 dialect entry alongside it is non-authoritative. superseded_by=sql if dialect == PORTABLE_DIALECT and sql is not None else None, @@ -1693,13 +1755,12 @@ def iter_expressions(data: dict) -> Iterator[Expression]: """ for dataset in data.get("datasets", []): dataset_name = dataset.get("name", "") - field_names = _expression_field_names(dataset) for field in dataset.get("fields", []): - yield from _expressions_in(field, "field", dataset_name, field_names) + yield from _expressions_in(field, "field", dataset_name, dataset) for metric in dataset.get("metrics", []): - yield from _expressions_in(metric, "dataset_metric", dataset_name, field_names) + yield from _expressions_in(metric, "dataset_metric", dataset_name, dataset) for metric in data.get("metrics", []): - yield from _expressions_in(metric, "model_metric", "", frozenset()) + yield from _expressions_in(metric, "model_metric", "") def read_expressions(member: dict, kind: ExpressionKind, dataset_name: str = "", dialect: str | None = None) -> list[Expression]: @@ -1712,7 +1773,7 @@ def read_expressions(member: dict, kind: ExpressionKind, dataset_name: str = "", """ return [ expression - for expression in _expressions_in(member, kind, dataset_name, frozenset()) + for expression in _expressions_in(member, kind, dataset_name) if isinstance(expression.text, str) and expression.text and expression.superseded_by is None @@ -2067,8 +2128,9 @@ def validate_metric_scoping(data: dict) -> list[str]: * No other qualified reference (`dataset.field`): that is model-scoped and belongs in the model-root metrics. - * Every unqualified name must be a declared field of the dataset. A bare name - is compared as a normalized identifier (expression_language.md); + * Every unqualified name must be a declared field of the dataset. In + OSSIE_SQL_2026 a bare name is compared as a normalized identifier + (expression_language.md); other dialects compare case-insensitively. `COUNT(*)`, literals and the unit of a date function reference no field and are fine. * `source.column` is not allowed when the dataset declares a field named @@ -2098,6 +2160,10 @@ def scope_errors(expression: Expression) -> list[str]: qualifiers = set() undeclared = set() uses_source = False + source_key = ( + SOURCE_QUALIFIER if _uses_ossie_quoting(expression.dialect) + else SOURCE_QUALIFIER.casefold() + ) # iter_columns skips every `*`; a qualified one, `customers.*`, still # names a dataset or the source and is checked like any other # qualified reference. @@ -2106,13 +2172,13 @@ def scope_errors(expression: Expression) -> list[str]: if id(col) in inside_agg: continue idents = _column_idents(col) - first = _sql_ident(idents[0]) if idents else "" - written_first = idents[0].sql() if idents else (col.table or col.name or "") + first = _sql_ident(idents[0], expression.dialect) if idents else "" + written_first = _ident_written(idents[0]) if idents else (col.table or col.name or "") if col.table: - if first == SOURCE_QUALIFIER and not col.db: + if first == source_key and not col.db: uses_source = True elif written_first: - qualifiers.add(idents[0].name if idents else col.table) + qualifiers.add(written_first) elif first and first not in expression.field_names: undeclared.add(written_first) @@ -2136,7 +2202,7 @@ def scope_errors(expression: Expression) -> list[str]: f"metric may reference only the dataset's declared fields, and its " f"source columns as source.column." ) - if uses_source and SOURCE_QUALIFIER in expression.field_names: + if uses_source and source_key in expression.field_names: out.append( f"{prefix} uses source.column, but dataset '{expression.dataset_name}' " f"declares a field named 'source', which takes precedence over the source " @@ -2529,6 +2595,7 @@ def normalized_identifier(identifier) -> str: return identifier.name if identifier.quoted else identifier.name.upper() +@_quiet_sqlglot() def declared_name(name: str) -> str: """Return the normalized form of a name declared in a document. From 5150a675e52fb093e7db8bb9340d5f824980caa2 Mon Sep 17 00:00:00 2001 From: vignesh_A Date: Wed, 25 Nov 2026 17:05:05 +0530 Subject: [PATCH 3/4] fix(validation): cache declared_name across a document names_cache in _expressions_in is per member, so every YAML name was parsed once per field. Cache the parse. Vendor dialects still casefold without it. Quoted "amount" stays an ANSI pass-through, as on main. --- validation/tests/test_validate.py | 4 +--- validation/validate.py | 3 ++- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index c45fa673..6ce07028 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -4250,9 +4250,7 @@ def test_field_shadowing_check_skips_dialects_that_are_not_sql_and_unparseable_s assert _field_reference_findings(document) == [] -@pytest.mark.parametrize( - "definition", ["(amount)", "amount -- the amount", "((amount))"] -) +@pytest.mark.parametrize("definition", ["(amount)", '"amount"', "amount -- the amount", "((amount))"]) def test_pass_through_is_read_from_the_parsed_definition(definition: str) -> None: document = _renamed_model() document["datasets"][0]["fields"] += [ diff --git a/validation/validate.py b/validation/validate.py index eadda5ae..fd828d9d 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -112,7 +112,7 @@ from dataclasses import dataclass from datetime import date, datetime, time from decimal import MAX_EMAX, MIN_EMIN, Context, Decimal, InvalidOperation -from functools import cache +from functools import cache, lru_cache from importlib.metadata import EntryPoint, entry_points from pathlib import Path from typing import Literal, NamedTuple @@ -2595,6 +2595,7 @@ def normalized_identifier(identifier) -> str: return identifier.name if identifier.quoted else identifier.name.upper() +@lru_cache(maxsize=None) @_quiet_sqlglot() def declared_name(name: str) -> str: """Return the normalized form of a name declared in a document. From 26ed5690a62c3fe7bfc1851308aa6d56cb463ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JB=20Onofr=C3=A9?= Date: Thu, 26 Nov 2026 15:52:23 +0100 Subject: [PATCH 4/4] style(validation): fix Ruff lint and formatting issues --- validation/tests/test_validate.py | 44 ++++----- validation/validate.py | 158 +++++++++++------------------- 2 files changed, 78 insertions(+), 124 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 6ce07028..8c685c01 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -3762,21 +3762,15 @@ def test_rejects_an_invalid_agg_call(expression: str, expected: str) -> None: def test_rejects_agg_of_a_quoted_metric_that_does_not_match() -> None: - errors = _field_reference_findings( - _model_metric_over_order_revenue('AGG(orders."order_revenue")') - ) + errors = _field_reference_findings(_model_metric_over_order_revenue('AGG(orders."order_revenue")')) assert len(errors) == 1, errors assert "'\"order_revenue\"' is not a dataset-scoped metric of dataset 'orders'" in errors[0] assert not isinstance(errors[0], _VALIDATE.ValidationWarning) def test_accepts_agg_of_a_quoted_metric_in_normalized_form() -> None: - assert _field_reference_findings( - _model_metric_over_order_revenue('AGG(orders."ORDER_REVENUE")') - ) == [] - assert _field_reference_findings( - _model_metric_over_order_revenue("AGG(ORDERS.order_revenue)") - ) == [] + assert _field_reference_findings(_model_metric_over_order_revenue('AGG(orders."ORDER_REVENUE")')) == [] + assert _field_reference_findings(_model_metric_over_order_revenue("AGG(ORDERS.order_revenue)")) == [] def test_rejects_agg_of_quoted_lowercase_total() -> None: @@ -4293,17 +4287,13 @@ def test_field_shadowing_check_compares_names_without_regard_to_case() -> None: def test_quoted_identifier_does_not_shadow_a_regular_field() -> None: document = _renamed_model() - document["datasets"][0]["fields"].append( - _field("total_eur", '"total_usd" * 0.9', "OSSIE_SQL_2026") - ) + document["datasets"][0]["fields"].append(_field("total_eur", '"total_usd" * 0.9', "OSSIE_SQL_2026")) assert _field_reference_findings(document) == [] def test_quoted_identifier_in_vendor_dialect_shadows_without_regard_to_case() -> None: document = _renamed_model() - document["datasets"][0]["fields"].append( - _field("total_eur", '"total_usd" * 0.9', "POSTGRES") - ) + document["datasets"][0]["fields"].append(_field("total_eur", '"total_usd" * 0.9', "POSTGRES")) errors = _field_reference_findings(document) assert len(errors) == 1 assert "'\"total_usd\"' is the source column, not the field 'total_usd'" in errors[0] @@ -4531,12 +4521,14 @@ def test_metric_check_compares_names_without_regard_to_case() -> None: def test_metric_quoted_identifier_matches_as_written() -> None: - document = _renamed_model(metrics=[ - _metric("ok_quoted", 'SUM(orders."TOTAL_USD")', "OSSIE_SQL_2026"), - _metric("ok_unquoted", "SUM(Orders.Total_Usd)", "OSSIE_SQL_2026"), - _metric("bad_quoted", 'SUM(orders."total_usd")', "OSSIE_SQL_2026"), - _metric("bad_amount", 'SUM(orders."amount")', "OSSIE_SQL_2026"), - ]) + document = _renamed_model( + metrics=[ + _metric("ok_quoted", 'SUM(orders."TOTAL_USD")', "OSSIE_SQL_2026"), + _metric("ok_unquoted", "SUM(Orders.Total_Usd)", "OSSIE_SQL_2026"), + _metric("bad_quoted", 'SUM(orders."total_usd")', "OSSIE_SQL_2026"), + _metric("bad_amount", 'SUM(orders."amount")', "OSSIE_SQL_2026"), + ] + ) errors = _VALIDATE.validate_metric_references(document) @@ -4549,10 +4541,12 @@ def test_metric_quoted_identifier_matches_as_written() -> None: def test_metric_vendor_dialect_compares_quoted_names_without_regard_to_case() -> None: # Quoted versus unquoted matching is DB specific; vendor dialects keep the # case-insensitive comparison they had before the OSSIE_SQL_2026 quoting rule. - document = _renamed_model(metrics=[ - _metric("pg", 'SUM(orders."total_usd")', "POSTGRES"), - _metric("bq", "SUM(orders.`total_usd`)", "BIGQUERY"), - ]) + document = _renamed_model( + metrics=[ + _metric("pg", 'SUM(orders."total_usd")', "POSTGRES"), + _metric("bq", "SUM(orders.`total_usd`)", "BIGQUERY"), + ] + ) assert _VALIDATE.validate_metric_references(document) == [] diff --git a/validation/validate.py b/validation/validate.py index fd828d9d..2e2eb717 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -112,7 +112,7 @@ from dataclasses import dataclass from datetime import date, datetime, time from decimal import MAX_EMAX, MIN_EMIN, Context, Decimal, InvalidOperation -from functools import cache, lru_cache +from functools import cache from importlib.metadata import EntryPoint, entry_points from pathlib import Path from typing import Literal, NamedTuple @@ -959,15 +959,16 @@ def validate_relationship_column_arity(data: dict) -> list[str]: def _uses_ossie_quoting(dialect: str) -> bool: - """The quoting table in expression_language.md is for OSSIE_SQL_2026. + """Return whether a dialect uses the OSSIE_SQL_2026 quoting table. - Quoted versus unquoted comparison is DB specific in other dialects. + The quoting table in expression_language.md is for OSSIE_SQL_2026; + quoted versus unquoted comparison is DB specific in other dialects. """ return dialect == PORTABLE_DIALECT def _sql_ident(part, dialect: str = PORTABLE_DIALECT) -> str: - """The comparison key of one parsed identifier. + """Return the comparison key of one parsed identifier. OSSIE_SQL_2026 follows expression_language.md: a quoted identifier as written, a regular one upper-cased. Other dialects compare case-insensitively. @@ -983,30 +984,30 @@ def _sql_ident(part, dialect: str = PORTABLE_DIALECT) -> str: def _declared_key(name: str, dialect: str = PORTABLE_DIALECT) -> str: - """YAML name as SQL identifiers in this dialect compare it.""" + """Return a YAML name as SQL identifiers in this dialect compare it.""" return declared_name(name) if _uses_ossie_quoting(dialect) else name.casefold() def _column_idents(column) -> list: - """The Identifier parts of a column reference.""" + """Return the Identifier parts of a column reference.""" if not SQLGLOT_AVAILABLE: return [] return [part for part in column.parts if isinstance(part, exp.Identifier)] def _ident_written(part) -> str: - """One identifier as written, quotes included.""" + """Return one identifier as written, quotes included.""" return part.sql() if hasattr(part, "sql") else getattr(part, "name", "") or "" def _column_written(column) -> str: - """The column as written, quotes included.""" + """Return the column as written, quotes included.""" idents = _column_idents(column) return ".".join(_ident_written(part) for part in idents) if idents else str(column) def _declared_member_names(members: object, dialect: str = PORTABLE_DIALECT) -> set[str]: - """YAML names of fields or metrics, as this dialect compares them.""" + """Return YAML names of fields or metrics, as this dialect compares them.""" names: set[str] = set() for member in as_list(members): if not isinstance(member, dict): @@ -1018,7 +1019,7 @@ def _declared_member_names(members: object, dialect: str = PORTABLE_DIALECT) -> def _expression_field_names(dataset: dict, dialect: str = PORTABLE_DIALECT) -> frozenset[str]: - """The enclosing dataset's field names as SQL identifiers compare them. + """Return the enclosing dataset's field names as SQL identifiers compare them. YAML key and relationship lists still use dataset_field_names (casefold). """ @@ -1028,12 +1029,13 @@ def _expression_field_names(dataset: dict, dialect: str = PORTABLE_DIALECT) -> f def declared_fields(model: dict, dialect: str = PORTABLE_DIALECT) -> dict[str, set[str]]: - """The declared names of the fields each dataset declares, keyed by - dataset name as this dialect compares them (expression_language.md). + """Return the declared names of the fields each dataset declares. - A dataset without a fields list declares none: model-level constructs do - not reach through a dataset to its source (spec.md, Name Resolution). - YAML key and relationship lists still use dataset_field_names (casefold). + Names are keyed by dataset name as this dialect compares them + (expression_language.md). A dataset without a fields list declares none: + model-level constructs do not reach through a dataset to its source + (spec.md, Name Resolution). YAML key and relationship lists still use + dataset_field_names (casefold). """ fields: dict[str, set[str]] = {} for d in as_list(model.get("datasets")): @@ -1041,9 +1043,7 @@ def declared_fields(model: dict, dialect: str = PORTABLE_DIALECT) -> dict[str, s continue # Datasets whose names differ only by case pool their fields rather # than hide each other's: regular identifiers upper-case to one key. - fields.setdefault(_declared_key(d["name"], dialect), set()).update( - _declared_member_names(d.get("fields"), dialect) - ) + fields.setdefault(_declared_key(d["name"], dialect), set()).update(_declared_member_names(d.get("fields"), dialect)) return fields @@ -1140,15 +1140,15 @@ def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]: def declared_dataset_metrics(model: dict, dialect: str = PORTABLE_DIALECT) -> dict[str, set[str]]: - """The declared names of the dataset-scoped metrics each dataset - declares, keyed by dataset name as this dialect compares them.""" + """Return the declared names of the dataset-scoped metrics each dataset declares. + + Names are keyed by dataset name as this dialect compares them. + """ metrics: dict[str, set[str]] = {} for d in as_list(model.get("datasets")): if not isinstance(d, dict) or not isinstance(d.get("name"), str): continue - metrics.setdefault(_declared_key(d["name"], dialect), set()).update( - _declared_member_names(d.get("metrics"), dialect) - ) + metrics.setdefault(_declared_key(d["name"], dialect), set()).update(_declared_member_names(d.get("metrics"), dialect)) return metrics @@ -1177,10 +1177,7 @@ def maps_for(dialect: str): fields = declared_fields(data, dialect) dataset_metrics = declared_dataset_metrics(data, dialect) field_names = set().union(*fields.values()) if fields else set() - declared_metrics = { - _declared_key(m["name"], dialect): m["name"] - for m in metrics if isinstance(m.get("name"), str) - } + declared_metrics = {_declared_key(m["name"], dialect): m["name"] for m in metrics if isinstance(m.get("name"), str)} maps[dialect] = (fields, dataset_metrics, field_names, declared_metrics) return maps[dialect] @@ -1195,16 +1192,10 @@ def maps_for(dialect: str): continue dialect = expression.dialect fields, dataset_metrics, field_names, declared_metrics = maps_for(dialect) - own_name = ( - _declared_key(metric_name, dialect) - if isinstance(metric.get("name"), str) else None - ) + own_name = _declared_key(metric_name, dialect) if isinstance(metric.get("name"), str) else None # A bare name that is another metric, and not also a field or this # metric itself, was most likely meant as that metric. - other_metrics = { - key: name for key, name in declared_metrics.items() - if key not in field_names and key != own_name - } + other_metrics = {key: name for key, name in declared_metrics.items() if key not in field_names and key != own_name} # AGG is defined only for OSSIE_SQL_2026; other dialects are read as # before. In OSSIE_SQL_2026, the argument of each AGG call is checked # here, so the column loop below skips every column inside it. @@ -1231,43 +1222,21 @@ def maps_for(dialect: str): written = _column_written(column) name = key[-1] if key else "" table = key[-2] if len(key) >= 2 else "" - dataset_label = ( - _ident_written(idents[0]) if idents else column.table - ) + dataset_label = _ident_written(idents[0]) if idents else column.table if column.db or len(key) > 2: - message = ( - f"'{written}' has more than two parts; metric expressions refer to " - f"fields as dataset.field" - ) + message = f"'{written}' has more than two parts; metric expressions refer to fields as dataset.field" elif not table and name in other_metrics: message = ( - f"'{written}' names the metric '{other_metrics[name]}'; " - f"metric expressions cannot refer to other metrics" + f"'{written}' names the metric '{other_metrics[name]}'; metric expressions cannot refer to other metrics" ) elif not table: - message = ( - f"'{written}' is not qualified; metric expressions refer to fields " - f"as dataset.field" - ) + message = f"'{written}' is not qualified; metric expressions refer to fields as dataset.field" elif table not in fields: - message = ( - f"'{written}' references unknown dataset " - f"'{dataset_label}'" - ) - elif ( - portable - and name not in fields[table] - and name in dataset_metrics.get(table, set()) - ): - message = ( - f"'{written}' names a dataset-scoped metric; " - f"write AGG({written}) to evaluate it" - ) + message = f"'{written}' references unknown dataset '{dataset_label}'" + elif portable and name not in fields[table] and name in dataset_metrics.get(table, set()): + message = f"'{written}' names a dataset-scoped metric; write AGG({written}) to evaluate it" elif name not in fields[table]: - message = ( - f"'{written}' is not a declared field of dataset " - f"'{dataset_label}'" - ) + message = f"'{written}' is not a declared field of dataset '{dataset_label}'" else: continue findings.append(ValidationWarning(f"[Reference] Warning: {context}: {message}")) @@ -1296,24 +1265,15 @@ def agg_argument_problem( dataset_label = _ident_written(idents[0]) if idents else arg.table if not table: if name in model_metrics: - return ( - f"AGG({written}) names the model-scoped metric '{model_metrics[name]}'; " - f"{expected}" - ) + return f"AGG({written}) names the model-scoped metric '{model_metrics[name]}'; {expected}" return f"AGG({written}) is not qualified; {expected}" if table not in fields: return f"AGG({written}) references unknown dataset '{dataset_label}'" if name in dataset_metrics.get(table, set()): return None if name in fields[table]: - return ( - f"AGG({written}) names a field, and fields are never measures; " - f"{expected}" - ) - return ( - f"AGG({written}): '{metric_label}' is not a " - f"dataset-scoped metric of dataset '{dataset_label}'" - ) + return f"AGG({written}) names a field, and fields are never measures; {expected}" + return f"AGG({written}): '{metric_label}' is not a dataset-scoped metric of dataset '{dataset_label}'" def validate_field_shadowing(data: dict) -> list[str]: @@ -1349,13 +1309,17 @@ def passes_through(tree, ident: str, dialect: str) -> bool: # specific: OSSIE_SQL_2026 uses declared_name, other dialects casefold. by_name_for: dict[str, dict[str, dict]] = {} - def by_name(dialect: str) -> dict[str, dict]: - if dialect not in by_name_for: + def by_name( + dialect: str, + cache: dict[str, dict[str, dict]] = by_name_for, + fields: list[dict] = declared, + ) -> dict[str, dict]: + if dialect not in cache: keyed: dict[str, dict] = {} - for f in declared: + for f in fields: keyed.setdefault(_declared_key(f["name"], dialect), f) - by_name_for[dialect] = keyed - return by_name_for[dialect] + cache[dialect] = keyed + return cache[dialect] for field in declared: for expression in read_expressions(field, "field", dataset_name): @@ -1392,10 +1356,12 @@ def by_name(dialect: str) -> dict[str, dict]: if not parsed or any(passes_through(t, key, dialect) for _, t in parsed): continue written = _column_written(column) - warnings.append(ValidationWarning( - f"[Reference] Warning: {context}: '{written}' is the source column, not the " - f"field '{other['name']}' defined as '{parsed[0][0]}'" - )) + warnings.append( + ValidationWarning( + f"[Reference] Warning: {context}: '{written}' is the source column, not the " + f"field '{other['name']}' defined as '{parsed[0][0]}'" + ) + ) return warnings @@ -1699,7 +1665,10 @@ def context(self, model_name: str) -> str: def _expressions_in( - member: dict, kind: ExpressionKind, dataset_name: str, dataset: dict | None = None, + member: dict, + kind: ExpressionKind, + dataset_name: str, + dataset: dict | None = None, ) -> Iterator[Expression]: # Shapes the schema rejects are skipped, not read, so a check called directly @@ -2160,10 +2129,7 @@ def scope_errors(expression: Expression) -> list[str]: qualifiers = set() undeclared = set() uses_source = False - source_key = ( - SOURCE_QUALIFIER if _uses_ossie_quoting(expression.dialect) - else SOURCE_QUALIFIER.casefold() - ) + source_key = SOURCE_QUALIFIER if _uses_ossie_quoting(expression.dialect) else SOURCE_QUALIFIER.casefold() # iter_columns skips every `*`; a qualified one, `customers.*`, still # names a dataset or the source and is checked like any other # qualified reference. @@ -2234,13 +2200,7 @@ def source_agg_problem(call, field_names: frozenset[str]) -> str | None: idents = _column_idents(arg) if isinstance(arg, exp.Column) else [] table = _sql_ident(idents[0]) if len(idents) >= 2 else "" name = _sql_ident(idents[-1]) if idents else "" - if ( - not isinstance(arg, exp.Column) - or isinstance(arg.this, exp.Star) - or arg.db - or table != SOURCE_QUALIFIER - or not name - ): + if not isinstance(arg, exp.Column) or isinstance(arg.this, exp.Star) or arg.db or table != SOURCE_QUALIFIER or not name: return f"AGG({arg.sql() if arg else ''}): {expected}" if SOURCE_QUALIFIER in field_names: return ( @@ -2595,7 +2555,7 @@ def normalized_identifier(identifier) -> str: return identifier.name if identifier.quoted else identifier.name.upper() -@lru_cache(maxsize=None) +@cache @_quiet_sqlglot() def declared_name(name: str) -> str: """Return the normalized form of a name declared in a document.