From 8655cbe95bc3cf9e6495695ba3a6784674937489 Mon Sep 17 00:00:00 2001 From: Alex Kosachev Date: Wed, 4 Nov 2026 16:54:28 +0800 Subject: [PATCH 1/2] fix(validation): read the unit of a date function as a unit in validate_metric_scoping validate_metric_scoping walked tree.find_all(exp.Column), so under sqlglot's default dialect the unit of DATEDIFF was reported as an undeclared field and the spec's own DATEDIFF(day, start_date, end_date) form was rejected. The check now walks iter_columns, the iterator validate_metric_references and validate_field_shadowing already use: the unit is skipped and an identifier the parser left in the unit slot is read as a column. iter_columns skips every `*`, so a qualified star is read on its own and is still a qualified reference. Co-Authored-By: Claude Fable 5.1 --- validation/tests/test_validate.py | 61 +++++++++++++++++++++++++++++++ validation/validate.py | 13 +++++-- 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 26d8962a..9decdc72 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1926,6 +1926,67 @@ def test_dataset_scoped_metric_count_star_references_no_field() -> None: assert _VALIDATE.validate_metric_scoping(doc) == [] +def test_dataset_scoped_metric_reads_a_date_part_as_a_unit_not_a_field() -> None: + # sqlglot's default parser reads the unit of DATEDIFF as a column, so the + # check walks iter_columns like the reference checks do. + doc = _orders_with( + fields=[ + {"name": "opened_at", "expression": _ds_expr("opened_at")}, + {"name": "closed_at", "expression": _ds_expr("closed_at")}, + ], + metrics=[ + {"name": "days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))")}, + {"name": "source_days_open", "expression": _ds_expr("MAX(DATEDIFF(day, source.opened_at, source.closed_at))")}, + {"name": "minutes_since_open", "expression": _ds_expr("DATEDIFF(MINUTE, MAX(opened_at), CURRENT_TIMESTAMP)")}, + {"name": "ansi_days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))", "ANSI_SQL")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [] + + +def test_dataset_scoped_metric_reads_a_column_in_the_unit_slot_as_a_field() -> None: + # Under the default parser the last DATEDIFF argument lands in `unit`, so an + # undeclared field there must still be reported. + doc = _orders_with( + fields=[{"name": "opened_at", "expression": _ds_expr("opened_at")}], + metrics=[{"name": "days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))")}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert len(errors) == 1 + assert errors[0].startswith("[Scope]") and "'CLOSED_AT'" in errors[0] and "'day'" not in errors[0] + + +def test_dataset_scoped_metric_still_reports_a_bare_field_named_like_a_unit() -> None: + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount")}], + metrics=[{"name": "total_minutes", "expression": _ds_expr("SUM(minute)")}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert len(errors) == 1 + assert errors[0].startswith("[Scope]") and "'minute'" in errors[0] + + +def test_dataset_scoped_metric_still_rejects_a_qualified_star() -> None: + # iter_columns skips every `*`; a qualified one names a dataset, or the + # source, and keeps the scoping rule. + doc = _orders_with( + metrics=[ + {"name": "n_customers", "expression": _ds_expr("COUNT(customers.*)")}, + {"name": "n_source", "expression": _ds_expr("COUNT(source.*)")}, + ], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert len(errors) == 1 + assert errors[0].startswith("[Scope]") and "'customers'" in errors[0] + + def test_dataset_scoped_metric_scoping_skips_dialects_sqlglot_cannot_parse() -> None: doc = _orders_with( metrics=[{"name": "total", "expression": _ds_expr("SUM(orders.amount)", "MDX")}], diff --git a/validation/validate.py b/validation/validate.py index 877b8c07..bb9e5133 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1008,8 +1008,8 @@ 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(*)` and literals reference no field - and are fine. + is compared 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 `source`, since the field takes precedence over the qualifier. @@ -1032,7 +1032,14 @@ def scope_errors(expression: Expression) -> list[str]: qualifiers = set() undeclared = set() uses_source = False - for col in tree.find_all(exp.Column): + # iter_columns skips every `*`; a qualified one, `customers.*`, still + # names a dataset or the source and is checked like any other + # qualified reference. + qualified_stars = ( + col for col in tree.find_all(exp.Column) + if isinstance(col.this, exp.Star) and col.table + ) + for col in (*iter_columns(tree), *qualified_stars): parts = [part.name for part in col.parts] if len(parts) == 2 and parts[0].casefold() == SOURCE_QUALIFIER: uses_source = True From bbbe42db5e1ac734d8ed0dc9cd4063cd7821e84f Mon Sep 17 00:00:00 2001 From: Alex Kosachev Date: Thu, 5 Nov 2026 07:45:11 +0800 Subject: [PATCH 2/2] fix(validation): read the unit slot back only under the default parser iter_columns guessed whether a column in the unit slot of DATEDIFF, DATE_ADD or TIMESTAMPDIFF was the unit or a column by whether the Var in unit names a date part. Under a parser that knows the function that guess fails both ways: a field named like a date part next to a unit the alias table lacks (ISOWEEK, nanoseconds) was dropped and the unit reported, and a non-Var unit hid an undeclared field. The iterator now takes the expression's dialect and reads the unit slot back only under sqlglot's default parser, where the shift happens; is_date_part treats a column in this as the unit only there too. The SNOWFLAKE case of the DATE_ADD reference test now uses DATEADD: Snowflake has no DATE_ADD, and sqlglot reads it there like the default parser does. Co-Authored-By: Claude Fable 5.1 --- validation/tests/test_validate.py | 53 ++++++++++++++++++++++++++----- validation/validate.py | 46 ++++++++++++++++----------- 2 files changed, 73 insertions(+), 26 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 9decdc72..edb0eb48 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1987,6 +1987,38 @@ def test_dataset_scoped_metric_still_rejects_a_qualified_star() -> None: assert errors[0].startswith("[Scope]") and "'customers'" in errors[0] +def test_dataset_scoped_metric_under_a_parser_that_knows_the_unit_reads_every_column_as_a_field() -> None: + # Snowflake and BigQuery put the unit in `unit` themselves, so a field named + # like a date part next to a unit the alias table lacks is still a field. + doc = _orders_with( + fields=[ + {"name": "opened_at", "expression": _ds_expr("opened_at", "SNOWFLAKE")}, + {"name": "d", "expression": _ds_expr("delivered_at", "SNOWFLAKE")}, + {"name": "day", "expression": _ds_expr("delivered_day", "BIGQUERY")}, + ], + metrics=[ + {"name": "ns_open", "expression": _ds_expr("MAX(DATEDIFF(nanoseconds, opened_at, d))", "SNOWFLAKE")}, + {"name": "weeks_open", "expression": _ds_expr("MAX(DATE_DIFF(day, opened_at, ISOWEEK))", "BIGQUERY")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [] + + +def test_dataset_scoped_metric_under_a_parser_that_knows_the_unit_reports_the_date_argument() -> None: + # BigQuery puts `WEEK(MONDAY)` in `unit`, so `day` in `this` is the date + # argument and is reported when undeclared. + doc = _orders_with( + fields=[{"name": "opened_at", "expression": _ds_expr("opened_at", "BIGQUERY")}], + metrics=[{"name": "open", "expression": _ds_expr("MAX(DATE_DIFF(day, opened_at, WEEK(MONDAY)))", "BIGQUERY")}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert len(errors) == 1 + assert errors[0].startswith("[Scope]") and "undeclared field(s) 'day'." in errors[0] + + def test_dataset_scoped_metric_scoping_skips_dialects_sqlglot_cannot_parse() -> None: doc = _orders_with( metrics=[{"name": "total", "expression": _ds_expr("SUM(orders.amount)", "MDX")}], @@ -2677,12 +2709,13 @@ def test_a_parser_that_knows_the_unit_leaves_the_date_arguments_as_columns() -> document = _renamed_model(metrics=[ _metric("ok", "SUM(DATEDIFF(day, orders.total_usd, orders.total_usd))", dialect="SNOWFLAKE"), _metric("bad", "SUM(DATEDIFF(day, orders.total_usd, d))", dialect="SNOWFLAKE"), + _metric("unlisted", "SUM(DATEDIFF(nanoseconds, orders.total_usd, d))", dialect="SNOWFLAKE"), ]) errors = _VALIDATE.validate_metric_references(document) - assert len(errors) == 1 - assert "'d' is not qualified" in errors[0] + assert len(errors) == 2 + assert all("'d' is not qualified" in e for e in errors) def test_metric_check_still_reports_a_bare_column_named_like_a_unit() -> None: @@ -2856,18 +2889,22 @@ def test_a_repeated_reference_is_reported_once_per_expression() -> None: ] -@pytest.mark.parametrize("dialect", ["ANSI_SQL", "SNOWFLAKE"]) -def test_date_add_reads_its_unit_as_a_unit_and_its_date_as_a_column(dialect) -> None: - # The default parser keeps DATE_ADD's unit in `this` and its date in `unit`. +@pytest.mark.parametrize( + ("function", "dialect", "reported"), + [("DATE_ADD", "ANSI_SQL", "'SHIPPED'"), ("DATEADD", "SNOWFLAKE", "'shipped'")], +) +def test_date_add_reads_its_unit_as_a_unit_and_its_date_as_a_column(function, dialect, reported) -> None: + # The default parser keeps DATE_ADD's unit in `this` and its date in `unit`; + # Snowflake's reads DATEADD's date into `this` and keeps its spelling. document = _renamed_model(metrics=[ - _metric("ok", "MAX(DATE_ADD(day, 1, orders.total_usd))", dialect=dialect), - _metric("bad", "MAX(DATE_ADD(day, 1, shipped))", dialect=dialect), + _metric("ok", f"MAX({function}(day, 1, orders.total_usd))", dialect=dialect), + _metric("bad", f"MAX({function}(day, 1, shipped))", dialect=dialect), ]) errors = _VALIDATE.validate_metric_references(document) assert [e.split(": ", 2)[2] for e in errors] == [ - "'SHIPPED' is not qualified; metric expressions refer to fields as dataset.field", + f"{reported} is not qualified; metric expressions refer to fields as dataset.field", ] diff --git a/validation/validate.py b/validation/validate.py index bb9e5133..c4626531 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -535,7 +535,14 @@ def is_date_part_name(name: str) -> bool: return name.upper() in parts or name.upper() in parts.values() -def is_date_part(column) -> bool: +def uses_default_parser(dialect: str) -> bool: + """Whether sqlglot reads this dialect with its default parser, which does + not know the unit of DATEDIFF, DATE_ADD or TIMESTAMPDIFF. `dialect` is one + of SQLGLOT_DIALECTS: the checks parse no other.""" + return SQLGLOT_DIALECTS[dialect] is None + + +def is_date_part(column, dialect: str) -> bool: """Whether a bare name is the unit argument of a date function. Only the unit position counts, since the alias table also holds short @@ -548,12 +555,13 @@ def is_date_part(column) -> bool: argument is itself named like one, the two readings cannot be told apart and the column in ``this`` is reported. Functions the parser leaves anonymous carry the unit as their first argument. DATE_TRUNC and its kin - never parse the unit as a column. + never parse the unit as a column. Under a dialect sqlglot parses with its + own parser, a column in ``this`` is a column. """ parent = column.parent if column.table or not is_date_part_name(column.name): return False - if isinstance(parent, UNIT_SLOT_FUNCTIONS): + if isinstance(parent, UNIT_SLOT_FUNCTIONS) and uses_default_parser(dialect): unit = parent.args.get("unit") unit_consumed = isinstance(unit, exp.Var) and is_date_part_name(unit.name) return column.arg_key == "this" and unit is not None and not unit_consumed @@ -562,22 +570,24 @@ def is_date_part(column) -> bool: return False -def iter_columns(tree) -> Iterator["exp.Column"]: - """The column references of a parsed expression, read the same way by both - reference checks: `*` references no column, the unit of a date function - is not one, and a unit slot the parser filled with a column is read as that - column. The default parser does not know DATEDIFF's unit, so in - `DATEDIFF(day, opened_at, closed_at)` it leaves `day` in `this` as a column - and reads `closed_at` into `unit` as a Var. When `this` is a bare column - named like a date part and `unit` is a Var that is not one, the Var is the - column, in the upper-cased spelling the parser keeps; a literal there, or a - unit the alias table lacks under a parser that knows the function, is left - alone. +def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]: + """The column references of a parsed expression, read the same way by the + reference checks and the scoping check: `*` references no column, the unit + of a date function is not one, and a unit slot the parser filled with a + column is read as that column. The default parser does not know DATEDIFF's + unit, so in `DATEDIFF(day, opened_at, closed_at)` it leaves `day` in `this` + as a column and reads `closed_at` into `unit` as a Var. When `this` is a + bare column named like a date part and `unit` is a Var that is not one, the + Var is the column, in the upper-cased spelling the parser keeps; a literal + there is left alone. Under a dialect sqlglot parses with its own parser, + nothing is read back from `unit`. """ for column in tree.find_all(exp.Column): - if isinstance(column.this, exp.Star) or is_date_part(column): + if isinstance(column.this, exp.Star) or is_date_part(column, dialect): continue yield column + if not uses_default_parser(dialect): + return for node in tree.find_all(*UNIT_SLOT_FUNCTIONS): first, unit = node.this, node.args.get("unit") if ( @@ -621,7 +631,7 @@ def validate_metric_references(data: dict) -> list[str]: if tree is None: continue seen = set() - for column in iter_columns(tree): + for column in iter_columns(tree, expression.dialect): key = tuple(part.name.casefold() for part in column.parts) if key in seen: continue @@ -698,7 +708,7 @@ def passes_through(tree, name: str) -> bool: tree = parse_tree(expression.text, expression.dialect, context) if tree is None: continue - names = [c.name for c in iter_columns(tree) if not c.table] + 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(): @@ -1039,7 +1049,7 @@ def scope_errors(expression: Expression) -> list[str]: col for col in tree.find_all(exp.Column) if isinstance(col.this, exp.Star) and col.table ) - for col in (*iter_columns(tree), *qualified_stars): + for col in (*iter_columns(tree, expression.dialect), *qualified_stars): parts = [part.name for part in col.parts] if len(parts) == 2 and parts[0].casefold() == SOURCE_QUALIFIER: uses_source = True