diff --git a/core-spec/expression_language.md b/core-spec/expression_language.md index adbfb3db..de65ecf0 100644 --- a/core-spec/expression_language.md +++ b/core-spec/expression_language.md @@ -113,9 +113,8 @@ will be able to be multi-part and the parts will be separated by the '.' charact What an identifier refers to depends on where the expression appears: * In a **field expression**, identifiers refer to columns of the dataset's `source`. A field expression cannot refer to other fields. -* In a **dataset-scoped metric expression**, unqualified identifiers refer to fields declared in that dataset. Identifiers qualified with `source`, as in `source.column`, refer to columns of the dataset's `source`. The `source` qualifier is case insensitive. If the dataset declares a field named `source`, the name refers to that field, and the dataset's metrics cannot refer to source columns. -* In a **model-scoped metric expression**, identifiers must be qualified as `dataset.field` and refer to a field declared in that dataset. -* Model-scoped metric expressions cannot refer to source columns, and no metric expression can refer to another metric. If a field and a source column share a name, an unqualified name in a metric expression refers to the field. +* In a **dataset-scoped metric expression**, unqualified identifiers refer to fields declared in that dataset, even when a source column has the same name. Identifiers qualified with `source`, as in `source.column`, refer to columns of the dataset's `source`. The `source` qualifier is case insensitive. If the dataset declares a field named `source`, the name refers to that field, and the dataset's metrics cannot refer to source columns. +* In a **model-scoped metric expression**, identifiers must be qualified. An identifier written `dataset.field` refers to a field declared in that dataset, not to a source column. Inside `AGG`, an identifier written `dataset.metric` refers to a dataset-scoped metric of that dataset; this `AGG(dataset.metric)` form is the only way to reference a metric. See [Name Resolution](spec.md#name-resolution) in the core specification. @@ -153,7 +152,7 @@ Ossie expressions support the following SQL constructs within any expression: | `UNION` / `INTERSECT` / `EXCEPT` | Not applicable to expressions | | DDL statements | Out of scope | | DML statements | Out of scope | -| `AGG(...)` | Reserved for a future version. See [Measure Evaluation: `AGG`](#measure-evaluation-agg-reserved). | +| `AGG(...)` outside a model-scoped metric | Reserved for a future version. See [Measure Evaluation: `AGG`](#measure-evaluation-agg). | ### Operator Precedence @@ -239,7 +238,7 @@ APPROX_PERCENTILE(response_time, 0.95) ### Conditional Aggregations (REQUIRED) SUM / COUNT aggregation functions support `DISTINCT.` -All aggregations must support filtered aggregation: +All aggregations except `AGG` must support filtered aggregation: ```sql -- DISTINCT modifier @@ -257,12 +256,14 @@ COUNT(*) FILTER (WHERE status = 'completed') #### `FILTER (WHERE ...)` (REQUIRED) -Every aggregate function must support a postfix `FILTER (WHERE )` modifier: +Every aggregate function except `AGG` must support a postfix `FILTER (WHERE )` modifier: ``` () FILTER (WHERE ) ``` +In this version, `AGG` takes no `FILTER` clause (see [Measure Evaluation: `AGG`](#measure-evaluation-agg)). + The clause has the semantics of the SQL:2003 `` (optional feature T612): the aggregate considers only the rows for which `` succeeds. `FILTER` is applied to the aggregate's input, not as a query `WHERE`, so it never removes output groups. A converter or engine MUST NOT rewrite an intrinsic `FILTER` predicate into a query-level `WHERE` clause when doing so would change group membership. `FILTER (WHERE ...)` is a modifier on an aggregate expression. It is not the standalone `WHERE` clause listed under [Not Supported in Expressions](#not-supported-in-expressions). The `` must reference only fields of the same dataset as the aggregate's arguments. @@ -279,11 +280,11 @@ COUNT(DISTINCT customer_id) FILTER (WHERE status = 'completed') --> COUNT(DISTI A non-matching row contributes `NULL`, which these functions ignore. An `ELSE 0` would count as a real row and would corrupt `AVG`, `MIN`, `MAX`, and `COUNT`. The identity does not hold for an aggregate function that does not ignore `NULL` inputs, such as `ARRAY_AGG`. -### Measure Evaluation: `AGG` (RESERVED) +### Measure Evaluation: `AGG` Ossie SQL reserves the function name `AGG` for evaluating a measure: a column that holds an aggregate calculation instead of a value for each row. The [Relational Query Interface](relational_semantics.md) defines measures (Section 4) and `AGG` (Section 6), including its valid arguments. In `OSSIE_SQL_2026` expressions, an implementation MUST NOT give `AGG` any other meaning. Expressions in other dialects are not affected. Because function names should be case insensitive, the reservation covers every capitalization, such as `agg` and `Agg`. -This version reserves the name only. `OSSIE_SQL_2026` expressions MUST NOT call `AGG` until a future version defines where model declarations may use it. +A model-scoped metric may use `AGG` to evaluate a dataset-scoped metric, as in `AGG(orders.total_revenue)`. The argument is a single `dataset.metric` reference, and the call takes no `FILTER (WHERE ...)` clause (see [Metric Scoping](spec.md#metric-scoping)). `OSSIE_SQL_2026` expressions MUST NOT call `AGG` anywhere else until a future version defines it. **Compatibility.** Earlier versions of this specification did not reserve `AGG`, so an older `OSSIE_SQL_2026` expression might call a different function by that name. To update it, rename that function or write the expression in a vendor dialect. Reserving `AGG` as a function name does not prevent a field, metric, or column from being named `agg`. @@ -929,6 +930,7 @@ tooling aid; where it and this document differ, this document is authoritative. |:----------|:-----------| :---- | | 0.2.0.dev | 2026-07-15 | Initial draft | | 0.2.0.dev | 2026-10-29 | State that function names are case insensitive. Reserve `AGG` for measure evaluation; expressions that call another function named `AGG` must rename it or move to a vendor dialect | +| 0.2.0.dev | 2026-11-06 | Allow model-scoped metrics to evaluate a dataset-scoped metric with `AGG(dataset.metric)` | --- diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index ac157411..1f60cfad 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -380,7 +380,7 @@ "items": { "$ref": "#/$defs/Metric" }, - "description": "Model-scoped metrics: aggregations that span datasets or need to be aware of cross-dataset concepts. Expressions reference fields by multi-part name (dataset.field) and may combine fields from more than one dataset. Names must be unique across the model. See core-spec/spec.md#metric-scoping." + "description": "Model-scoped metrics: aggregations that span datasets or need to be aware of cross-dataset concepts. Expressions reference fields by multi-part name (dataset.field) and may combine fields from more than one dataset. They may evaluate a dataset-scoped metric with AGG(dataset.metric). Names must be unique across the model. See core-spec/spec.md#metric-scoping." }, "nonportable_extensions": { "type": "array", diff --git a/core-spec/spec.md b/core-spec/spec.md index 87b31e2f..129729f4 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -415,7 +415,7 @@ There are two types of metrics: - **Dataset-scoped** (`datasets[].metrics`): aggregations that belong to a single dataset. The expression references that dataset's declared fields by single-part name and its source columns as `source.column`, and resolves entirely within it. - **Model-scoped** (the model-root `metrics`): aggregations that span datasets across the model. The expression references fields by multi-part `dataset.field` name and may combine fields across datasets. -Model-scoped metric expressions refer to dataset fields. Dataset-scoped metric expressions refer to the dataset's fields and may also refer to columns of its `source`, written as `source.column`. No metric expression can refer to another metric. See [Metric Scoping](#metric-scoping) for the rules governing each and [Name Resolution](#name-resolution) for how names resolve. +Model-scoped metric expressions refer to dataset fields. Dataset-scoped metric expressions refer to the dataset's fields and may also refer to columns of its `source`, written as `source.column`. A model-scoped metric can refer to a dataset-scoped metric only through `AGG(dataset.metric)`. No other metric references are supported. See [Metric Scoping](#metric-scoping) for the rules governing each and [Name Resolution](#name-resolution) for how names resolve. ### Schema @@ -492,6 +492,7 @@ A metric may be defined on an individual dataset or at the model level. Both pla 3. `source` is not reserved: a field or dataset may be named `source`. If a dataset declares a field named `source`, the name `source` refers to that field, so the dataset's metrics cannot refer to source columns. 4. Within a dataset, declared field names and dataset-scoped metric names share one namespace and MUST all be unique across the two. 5. A model-scoped metric's expression references fields by multi-part name, `dataset.field`, and MAY combine fields from more than one dataset. It cannot reference source columns. +6. A model-scoped metric MAY evaluate a dataset-scoped metric with `AGG(dataset.metric)`: `AGG(orders.total_revenue) / COUNT(DISTINCT customers.customer_id)`. The argument MUST be a single reference to a dataset-scoped metric, written as `dataset.metric`, and the call MUST NOT have a `FILTER (WHERE ...)` clause. A model-scoped metric MUST NOT refer to a metric in any other way: a bare `orders.total_revenue`, `AGG` of a field, and `AGG` of a model-scoped metric are invalid. **Example: dataset-scoped metrics** @@ -659,7 +660,7 @@ exposes nothing to keys, relationships, or model-scoped metrics. | `relationships[].from_columns` | A field of the `from` dataset | | `relationships[].to_columns` | A field of the `to` dataset | | Dataset-scoped metric `expression` (`datasets[].metrics`) | Unqualified: a field of the same dataset. `source.column`: a column of its `source` | -| Model-scoped metric `expression` (model-root `metrics`) | A field of the named dataset, qualified as `dataset.field` | +| Model-scoped metric `expression` (model-root `metrics`) | A field of the named dataset, qualified as `dataset.field`. Inside `AGG`: a dataset-scoped metric of the named dataset, qualified as `dataset.metric` | For example, a dataset can expose the source column `o_totalprice` as the field `total_amount`, and derive `total_usd` from `total_cents`: @@ -722,7 +723,8 @@ This version of the specification does not support: - a field expression that refers to another field, in the same or another dataset; -- a metric expression that refers to another metric; +- a metric expression that refers to another metric, except a model-scoped + metric that evaluates a dataset-scoped metric with `AGG(dataset.metric)`; - a dataset that uses another dataset as its `source`. Future versions may add these. @@ -874,6 +876,7 @@ including rationale and migration impact for consumers, see the - Breaking: in `OSSIE_SQL_2026`, `ROUND(x, d)` breaks ties half away from zero and `/` is true division (`5 / 2` is `2.5`). Earlier versions did not specify either, and engines differ on both; an engine with another default must evaluate an equivalent expression. See [Numeric Semantics](expression_language.md#numeric-semantics). - Breaking: metric expressions, `primary_key`, `unique_keys`, and relationship `from_columns`/`to_columns` refer to dataset fields, not columns of the dataset's `source`. Model-scoped metric expressions must use qualified `dataset.field` references; dataset-scoped metric expressions use unqualified field names. Earlier versions did not specify this, and some converters read these names as source columns; those converters must now resolve them as fields. See [Name Resolution](#name-resolution). - Dataset-scoped metric expressions may reference columns of the dataset's `source`, written as `source.column`. See [Metric Scoping](#metric-scoping). + - Model-scoped metric expressions may evaluate a dataset-scoped metric with `AGG(dataset.metric)`. See [Metric Scoping](#metric-scoping). - **0.1.1** (2025-12-11): Initial release - Core semantic model structure - Support for datasets, relationships, fields, and metrics diff --git a/core-spec/spec.yaml b/core-spec/spec.yaml index 5dfd4ba4..b0751071 100644 --- a/core-spec/spec.yaml +++ b/core-spec/spec.yaml @@ -284,7 +284,8 @@ metrics: # not columns of a dataset's source # Dataset-scoped metrics reference unqualified field names, and may also # reference source columns as source.column - # Metrics cannot reference other metrics + # A model-scoped metric can refer to a dataset-scoped metric only through + # AGG(dataset.metric); no other metric references are supported # At least one of the portable `sql` or `dialects` must be present; either may stand alone expression: sql: string # Primary, portable OSSIE_SQL_2026 form, e.g., "SUM(orders.sales)", "AVG(orders.amount)" diff --git a/core-spec/wide_table_semantics.md b/core-spec/wide_table_semantics.md index 4d1f34e2..84917520 100644 --- a/core-spec/wide_table_semantics.md +++ b/core-spec/wide_table_semantics.md @@ -222,7 +222,7 @@ The process is: split metrics into components (Section 5.2), check reachability A **component** is an aggregate expression over fields of one **home dataset**. A row of a home dataset is a **home row**. The lowering defines each component as an internally named measure of its home dataset, and evaluates it with one `AGG()` call (Layer 2 Sections 3.4 and 5.1). - A dataset-scoped metric `D.m` is one component with home dataset `D`, whatever its expression. The expression may combine several aggregate calls, such as `SUM(revenue) / NULLIF(COUNT(*), 0)`, and may use `COUNT(*)` with or without a `FILTER (WHERE ...)` clause. It is still one measure and one `AGG()` call. -- In a model-scoped metric, each aggregate call is a separate component. Its home dataset is the one dataset that its arguments read. Its `FILTER (WHERE ...)` clause MUST read only that dataset (Layer 1, `FILTER (WHERE ...)`), and it does not determine the home dataset. The metric's scalar expression is evaluated from the component values afterward (Section 5.5), as in Layer 1 and Layer 2 (Layer 2 Section 8.1). +- In a model-scoped metric, each aggregate call is a separate component. Its home dataset is the one dataset that its arguments read. Its `FILTER (WHERE ...)` clause MUST read only that dataset (Layer 1, `FILTER (WHERE ...)`), and it does not determine the home dataset. The metric's scalar expression is evaluated from the component values afterward (Section 5.5), as in Layer 1 and Layer 2 (Layer 2 Section 8.1). An `AGG(D.m)` call is one component with home dataset `D`, evaluated as the dataset-scoped metric `D.m`. The **empty-input value** of a component is its value over no rows. For example, `SUM(x)` gives NULL, `COUNT(*)` gives 0, `COALESCE(SUM(x), 0)` gives 0, and `SUM(revenue) / NULLIF(COUNT(*), 0)` gives NULL. It equals the value of `AGG()` for an empty input set (Layer 2 Section 8.1). Section 5.5 requires it. diff --git a/validation/test_validate.py b/validation/test_validate.py index 73a122f9..40eca8fc 100644 --- a/validation/test_validate.py +++ b/validation/test_validate.py @@ -3,7 +3,7 @@ # dependencies = [ # "jsonschema>=4.26.0", # "pyyaml>=6.0.3", -# "sqlglot>=30.12.0", +# "sqlglot>=30.19.0", # ] # /// diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 0a718ab6..6ccdcc46 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -2857,6 +2857,115 @@ def test_warns_on_metric_that_references_a_source_column() -> None: assert "'orders.o_totalprice' is not a declared field of dataset 'orders'" in errors[0] +def _model_metric_over_order_revenue(expression: str, dialect: str = "OSSIE_SQL_2026") -> dict: + """The renamed model, with a dataset-scoped metric orders.order_revenue and a + model-scoped metric whose expression and dialect are given. AGG is defined + for OSSIE_SQL_2026, so that is the default.""" + document = _renamed_model() + document["datasets"][0]["metrics"] = [_metric("order_revenue", "SUM(total_usd)")] + document["metrics"] = [_metric("total_revenue", expression, dialect)] + return document + + +def test_accepts_agg_of_a_dataset_scoped_metric() -> None: + document = _model_metric_over_order_revenue( + "AGG(orders.order_revenue) / COUNT(DISTINCT customers.id)" + ) + assert _field_reference_findings(document) == [] + + +def test_warns_on_a_bare_dataset_scoped_metric_reference() -> None: + # A bare metric reference is the existing "names another metric" finding, so + # it stays a warning, with a hint toward AGG. + errors = _field_reference_findings(_model_metric_over_order_revenue("orders.order_revenue")) + assert len(errors) == 1 + assert isinstance(errors[0], _VALIDATE.ValidationWarning) + assert ( + "'orders.order_revenue' names a dataset-scoped metric; " + "write AGG(orders.order_revenue) to evaluate it" + ) in errors[0] + + +@pytest.mark.parametrize( + ("expression", "expected"), + [ + ("AGG(orders.total_usd)", "names a field, and fields are never measures"), + ("AGG(total_revenue)", "names the model-scoped metric 'total_revenue'"), + ("AGG(order_revenue)", "AGG(order_revenue) is not qualified"), + ("AGG(orders.order_revenue + 1)", "AGG(orders.order_revenue + 1): AGG takes a single"), + ("AGG(orders.missing)", "'missing' is not a dataset-scoped metric of dataset 'orders'"), + ("AGG(shipments.revenue)", "references unknown dataset 'shipments'"), + ( + "AGG(orders.order_revenue) FILTER (WHERE orders.customer_id = 1)", + "has a FILTER (WHERE ...) clause; AGG does not take one", + ), + ], +) +def test_rejects_an_invalid_agg_call(expression: str, expected: str) -> None: + # A misused AGG call is an error, unlike the other reference findings: no + # model written before AGG was allowed can contain one. + errors = _field_reference_findings(_model_metric_over_order_revenue(expression)) + assert len(errors) == 1, errors + assert expected in errors[0] + assert errors[0].startswith("[Reference] Metric 'total_revenue'") + assert not isinstance(errors[0], _VALIDATE.ValidationWarning) + + +@pytest.mark.parametrize( + ("kind", "expected"), + [ + ("field", "Field 'orders.revenue' in model 'm' (OSSIE_SQL_2026) calls AGG in a field expression"), + ("metric", "Metric 'orders.revenue' in model 'm' (OSSIE_SQL_2026) calls AGG in a dataset-scoped metric"), + ], +) +def test_rejects_agg_outside_a_model_scoped_metric(kind: str, expected: str) -> None: + document = _renamed_model() + member = {"name": "revenue", "expression": {"sql": "AGG(source.revenue)"}} + document["datasets"][0]["fields" if kind == "field" else "metrics"] = [member] + + errors = _VALIDATE.validate_agg_placement(document) + + assert len(errors) == 1 + assert expected in errors[0] + assert not isinstance(errors[0], _VALIDATE.ValidationWarning) + + +def test_agg_placement_accepts_agg_in_a_model_scoped_metric() -> None: + document = _model_metric_over_order_revenue("AGG(orders.order_revenue)") + assert _VALIDATE.validate_agg_placement(document) == [] + + +def test_agg_placement_skips_other_dialects() -> None: + # The AGG rules are for OSSIE_SQL_2026; other dialects are not affected. + document = _renamed_model() + document["datasets"][0]["fields"].append(_field("revenue", "AGG(x)", "SNOWFLAKE")) + document["datasets"][0]["metrics"] = [_metric("revenue_total", "AGG(total_usd)", "SNOWFLAKE")] + + assert _VALIDATE.validate_agg_placement(document) == [] + assert _VALIDATE.validate_metric_scoping(document) == [] + + +def test_dataset_scoped_agg_is_reported_once() -> None: + # The placement check reports the call; the scoping check does not also + # report the name inside it as an undeclared field. + document = _renamed_model() + document["datasets"][0]["metrics"] = [ + {"name": "revenue", "expression": {"sql": "AGG(order_revenue)"}} + ] + + assert _VALIDATE.validate_metric_scoping(document) == [] + assert len(_VALIDATE.validate_agg_placement(document)) == 1 + + +def test_model_metric_agg_checks_skip_other_dialects() -> None: + # In another dialect, AGG is an ordinary function call: no AGG warnings, and + # the names inside it are read as field references, as before AGG was defined. + document = _model_metric_over_order_revenue( + "AGG(orders.total_usd) FILTER (WHERE orders.customer_id = 1)", "SNOWFLAKE" + ) + assert _field_reference_findings(document) == [] + + def test_warns_on_metric_with_unqualified_field_reference() -> None: document = _renamed_model() document["metrics"][0]["expression"]["dialects"][0]["expression"] = "SUM(total_usd)" diff --git a/validation/validate.py b/validation/validate.py index 622326d2..fd34e74b 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -5,7 +5,7 @@ # dependencies = [ # "jsonschema>=4.26.0", # "pyyaml>=6.0.3", -# "sqlglot>=30.12.0", +# "sqlglot>=30.19.0", # ] # /// @@ -740,20 +740,41 @@ def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]: yield exp.column(unit.name) +def declared_dataset_metrics(model: dict) -> dict[str, set[str]]: + """The case-folded names of the dataset-scoped metrics each dataset + declares, by case-folded dataset name.""" + 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) + ) + return metrics + + def validate_metric_references(data: dict) -> list[str]: - """Warn when a metric expression refers to anything but a declared field - written as dataset.field (spec.md, Name Resolution): an unqualified name, - another metric, a dataset the model does not declare or a field the dataset - does not. Dialects sqlglot cannot parse are skipped and an expression that - does not parse is left to the SQL check.""" + """Report when a metric expression refers to anything but a declared field + written as dataset.field, or a dataset-scoped metric evaluated as + AGG(dataset.metric) (spec.md, Name Resolution and Metric Scoping). + + An unqualified name, another metric outside AGG, a dataset the model does + not declare or a field the dataset does not is a warning for now. A misused + AGG call (an argument that is not a single dataset.metric reference, or a + FILTER) is an error: no model written before AGG was allowed can contain + one. Dialects sqlglot cannot parse are skipped and an expression that does + not parse is left to the SQL check.""" 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 = {m["name"].casefold(): m["name"] for m in metrics if isinstance(m.get("name"), str)} - warnings = [] + findings = [] for metric in metrics: metric_name = metric.get("name", "") @@ -769,8 +790,27 @@ def validate_metric_references(data: dict) -> list[str]: tree = parse_tree(expression.text, expression.dialect, context) if tree is None: continue + # 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 + agg_arguments = set() + for call in tree.find_all(exp.Agg) if portable else (): + arg = call.this + if arg is not None: + agg_arguments.update(id(c) for c in arg.find_all(exp.Column)) + message = agg_argument_problem(arg, fields, dataset_metrics, declared_metrics) + if message is None and isinstance(call.parent, exp.Filter): + message = ( + f"AGG({arg.sql()}) has a FILTER (WHERE ...) clause; AGG does not " + f"take one" + ) + if message: + findings.append(f"[Reference] {context}: {message}") seen = set() 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) if key in seen: continue @@ -797,6 +837,15 @@ def validate_metric_references(data: dict) -> list[str]: f"'{column.table}.{column.name}' references unknown dataset " f"'{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" + ) elif name not in fields[table]: message = ( f"'{column.table}.{column.name}' is not a declared field of dataset " @@ -804,8 +853,40 @@ def validate_metric_references(data: dict) -> list[str]: ) else: continue - warnings.append(ValidationWarning(f"[Reference] Warning: {context}: {message}")) - return warnings + findings.append(ValidationWarning(f"[Reference] Warning: {context}: {message}")) + return findings + + +def agg_argument_problem( + arg, fields: dict[str, set[str]], dataset_metrics: dict[str, set[str]], + model_metrics: dict[str, str], +) -> str | None: + """Why the argument of an AGG call in a model-scoped metric is not a single + dataset.metric reference to a dataset-scoped metric, or None if it is.""" + 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: + if name in model_metrics: + return ( + f"AGG({arg.name}) names the model-scoped metric '{model_metrics[name]}'; " + f"{expected}" + ) + return f"AGG({arg.name}) is not qualified; {expected}" + if table not in fields: + return f"AGG({arg.table}.{arg.name}) references unknown dataset '{arg.table}'" + 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; " + f"{expected}" + ) + return ( + f"AGG({arg.table}.{arg.name}): '{arg.name}' is not a dataset-scoped metric of " + f"dataset '{arg.table}'" + ) def validate_field_shadowing(data: dict) -> list[str]: @@ -1435,6 +1516,12 @@ def scope_errors(expression: Expression) -> list[str]: if tree is None: return [] + # validate_agg_placement reports an OSSIE_SQL_2026 AGG call here, so the + # names inside it are not checked again. + inside_agg = set() + if expression.dialect == PORTABLE_DIALECT: + for call in tree.find_all(exp.Agg): + inside_agg.update(id(c) for c in call.find_all(exp.Column)) qualifiers = set() undeclared = set() uses_source = False @@ -1446,6 +1533,8 @@ def scope_errors(expression: Expression) -> list[str]: if isinstance(col.this, exp.Star) and col.table ) 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 @@ -1496,6 +1585,41 @@ def scope_errors(expression: Expression) -> list[str]: return errors +def validate_agg_placement(data: dict) -> list[str]: + """Report AGG in a field expression or a dataset-scoped metric. + + This version allows AGG only in model-scoped metrics, as AGG(dataset.metric) + (expression_language.md, Measure Evaluation: AGG); validate_metric_references + checks those calls. The rule is for OSSIE_SQL_2026, so other dialects are + skipped. + """ + if not SQLGLOT_AVAILABLE or not isinstance(data, dict) or "datasets" not in data: + return [] + + model_name = data.get("name", "") + errors = [] + for expression in iter_expressions(data): + # A superseded OSSIE_SQL_2026 dialect entry is non-authoritative; the + # top-level `sql` it defers to is checked in its place. + if ( + expression.kind == "model_metric" + or expression.dialect != PORTABLE_DIALECT + or not expression.text + or expression.superseded_by is not None + ): + continue + context = expression.context(model_name) + tree, _ = _parse_sql_expression(expression.text, expression.dialect, context) + if tree is None or tree.find(exp.Agg) is None: + continue + where = "a field expression" if expression.kind == "field" else "a dataset-scoped metric" + errors.append( + f"[Scope] {context} calls AGG in {where}. This version allows AGG only in " + f"model-scoped metrics, as AGG(dataset.metric)." + ) + return errors + + def as_list(value: object) -> list: """The items of a list, or nothing for shapes that already failed the schema.""" return value if isinstance(value, list) else [] @@ -2377,6 +2501,7 @@ def clean() -> bool: errors.extend(validate_metric_references(data)) errors.extend(validate_field_shadowing(data)) errors.extend(validate_metric_scoping(data)) + errors.extend(validate_agg_placement(data)) errors.extend(validate_sql(data)) errors.extend(validate_metric_agreement(data)) if clean() and isinstance(data, dict) and "ontology" in data: