From 92a73f1bc8075ecbdbcb496f5d950e12dec535d1 Mon Sep 17 00:00:00 2001 From: Justin Talbot Date: Fri, 30 Oct 2026 11:09:39 -0700 Subject: [PATCH] docs(core-spec): Let dataset-scoped metrics reference source columns as source.column A dataset-scoped metric may now reference a column of its dataset's source, written as source.column. The source qualifier is case insensitive and reaches a column that a field of the same name shadows. Unqualified names must still be declared fields. source is not reserved. If a dataset declares a field named source, the field takes precedence, and the dataset's metrics cannot refer to source columns. The validator accepts source.column and reports its use in a dataset that declares a field named source. Co-authored-by: Isaac --- core-spec/expression_language.md | 4 +-- core-spec/ossie-schema.json | 2 +- core-spec/spec.md | 41 ++++++++++++++----------- core-spec/spec.yaml | 15 ++++++---- python/src/ossie/models.py | 3 +- validation/tests/test_validate.py | 50 +++++++++++++++++++++++++++++-- validation/validate.py | 40 +++++++++++++++++-------- 7 files changed, 113 insertions(+), 42 deletions(-) diff --git a/core-spec/expression_language.md b/core-spec/expression_language.md index dd8f121f2..df45c9d1e 100644 --- a/core-spec/expression_language.md +++ b/core-spec/expression_language.md @@ -111,9 +111,9 @@ 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**, identifiers are unqualified and refer to fields declared in that dataset. +* 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. -* Metric expressions cannot refer to columns of the dataset's `source` or to other metrics. If a field and a source column share a name, a metric expression refers to the field. +* 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. See [Name Resolution](spec.md#name-resolution) in the core specification. diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index cf7949b19..d6ecba64b 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -252,7 +252,7 @@ "items": { "$ref": "#/$defs/Metric" }, - "description": "Dataset-scoped metrics: aggregations evaluated at this dataset's row level, for measures that semantically belong to the dataset. The expression references this dataset's declared fields by single-part (unqualified) name and must resolve entirely within this dataset; an expression that must reference another dataset belongs in the model-scoped metrics instead. Referencing a column of the source that is not a declared field is a future extension. Within the dataset, field names and metric names share one namespace and must all be unique across the two." + "description": "Dataset-scoped metrics: aggregations evaluated at this dataset's row level, for measures that semantically belong to the dataset. The expression references this dataset's declared fields by single-part (unqualified) name, and columns of the dataset's source as source.column. It must resolve entirely within this dataset; an expression that must reference another dataset belongs in the model-scoped metrics instead. Within the dataset, field names and metric names share one namespace and must all be unique across the two." }, "custom_extensions": { "type": "array", diff --git a/core-spec/spec.md b/core-spec/spec.md index 259adc436..9faf61ac8 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -167,7 +167,7 @@ Logical datasets represent business entities or concepts (fact and dimension tab | `description` | string | No | Human-readable description | | `ai_context` | string/object | No | Additional context for AI tools (e.g., synonyms, common terms) | | `fields` | array | No | Row-level attributes for grouping, filtering, and metric expressions | -| `metrics` | array | No | Dataset-scoped metrics that semantically belong to this dataset; expressions reference its declared fields by single-part name and resolve entirely within it. See [Metric Scoping](#metric-scoping). | +| `metrics` | array | No | Dataset-scoped metrics that semantically belong to this dataset; expressions reference its declared fields by single-part name and its source columns as `source.column`, and resolve entirely within it. See [Metric Scoping](#metric-scoping). | | `custom_extensions` | array | No | Vendor-specific attributes | ### Primary Key Examples @@ -418,10 +418,10 @@ Quantitative measures defined on business data, representing key calculations li 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 resolves entirely within it. +- **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. -Metric expressions refer to dataset fields. They cannot refer to columns of a dataset's `source` or to other metrics. 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`. 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. ### Schema @@ -490,17 +490,17 @@ A metric may be defined on an individual dataset or at the model level. Both pla | | Dataset-scoped (`datasets[].metrics`) | Model-scoped (model-root `metrics`) | |---|---|---| -| Expression references | This dataset's declared fields, single-part: `field` | Fields of any dataset, multi-part: `dataset.field` | +| Expression references | This dataset's declared fields, single-part: `field`; columns of its `source`: `source.column` | Fields of any dataset, multi-part: `dataset.field` | | Spans datasets | No | Yes, via relationships | | Referenced as | `dataset_name.metric_name` | `metric_name` | **Rules** -1. A dataset-scoped metric's expression MUST reference only the declared fields of the dataset that declares it, written by single-part (unqualified) name: `SUM(net_amount)`. It MUST NOT reference a field of another dataset; a metric that must do so is model-scoped and MUST be declared in the model-root `metrics`. -2. Within a dataset, declared field names and dataset-scoped metric names share one namespace and MUST all be unique across the two. -3. A model-scoped metric's expression references fields by multi-part name, `dataset.field`, and MAY combine fields from more than one dataset. - -> Referencing a column of a dataset's `source` that is not a declared field is a future extension. Today a dataset-scoped expression reaches only the dataset's declared fields. +1. A dataset-scoped metric's expression MUST reference only the declared fields of the dataset that declares it, written by single-part (unqualified) name: `SUM(net_amount)`, and the columns of that dataset's `source`, written as `source.column`: `SUM(source.quantity)`. It MUST NOT reference a field of another dataset; a metric that must do so is model-scoped and MUST be declared in the model-root `metrics`. +2. In a dataset-scoped metric, an unqualified name MUST be a declared field of the dataset. A source column MUST be qualified with `source`, which is case insensitive: `source.quantity` and `SOURCE.quantity` name the same column. `source.amount` refers to the source column even when the dataset declares a field named `amount`. +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. **Example: dataset-scoped metrics** @@ -612,9 +612,12 @@ An Ossie model has three levels of names: fields are its public interface. 3. **Metrics.** Dataset-scoped metrics (`datasets[].metrics`) and model-scoped metrics (the model-root `metrics`), defined in terms of dataset fields. + Dataset-scoped metrics may also use their own dataset's source columns, + written as `source.column`. -Metrics and relationships do not reach through a dataset to its source -columns, so a dataset that declares no fields exposes nothing to them. +Apart from a dataset's own fields and dataset-scoped metrics, nothing reaches +through a dataset to its source columns. A dataset that declares no fields +exposes nothing to keys, relationships, or model-scoped metrics. | Where the name appears | What it refers to | |------------------------|-------------------| @@ -622,7 +625,7 @@ columns, so a dataset that declares no fields exposes nothing to them. | `datasets[].primary_key`, `datasets[].unique_keys` | A field of the same dataset | | `relationships[].from_columns` | A field of the `from` dataset | | `relationships[].to_columns` | A field of the `to` dataset | -| Dataset-scoped metric `expression` (`datasets[].metrics`) | A field of the same dataset, unqualified | +| 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` | For example, a dataset can expose the source column `o_totalprice` as the @@ -677,17 +680,20 @@ In this model, these references are invalid: - `SUM(total_usd)` in a model-scoped metric, because model-scoped metric expressions must qualify field names with the dataset name, even when only one dataset has a field with that name. -- `SUM(o_totalprice)` in a metric declared on `orders`, because dataset-scoped - metrics reach only the dataset's declared fields, not its source columns. +- `SUM(o_totalprice)` in a metric declared on `orders`, because an unqualified + name in a dataset-scoped metric must be a declared field. Write + `SUM(source.o_totalprice)` to refer to the source column. If a field and a source column share a name (as in a field `amount` defined as `amount`), the name refers to the source column inside that dataset's field -expressions and to the field everywhere else. +expressions and to the field everywhere else. A dataset-scoped metric can +still refer to the source column as `source.amount`. Consumers that generate SQL against the source tables, rather than against a layer that exposes the fields, must replace each field reference with the -field's expression. For example, `SUM(orders.total_amount)` compiles to -`SUM(o_totalprice)` over `sales.public.orders`. +field's expression, and each `source.column` reference with `column`. For +example, `SUM(orders.total_amount)` compiles to `SUM(o_totalprice)` over +`sales.public.orders`. This version of the specification does not support: @@ -854,6 +860,7 @@ ai_context: - **0.2.0.dev0** (Unreleased): In-development next minor release. Schema is mutable; do not depend on this version in production. - Breaking: each standalone document contains one model directly at the root; the `semantic_model` array is removed. - 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). - **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 58c66569e..3828efe51 100644 --- a/core-spec/spec.yaml +++ b/core-spec/spec.yaml @@ -147,11 +147,13 @@ datasets: # # Rules (see core-spec/spec.md#metric-scoping): # - The expression MUST reference only this dataset's declared fields, - # written by single-part (unqualified) name: SUM(net_amount). + # written by single-part (unqualified) name: SUM(net_amount), and the + # columns of its source, written as source.column: SUM(source.quantity). + # - The source qualifier is case insensitive. If the dataset declares a + # field named source, the name refers to that field, and the metrics + # cannot refer to source columns. # - It MUST NOT reference another dataset; a metric that must do so is # model-scoped and belongs in the model-root metrics. - # - Referencing a column of the source that is not a declared field is a - # future extension. # - Field names and metric names share one namespace; every name MUST be # unique across the two. # - Referenced from outside the dataset as dataset_name.metric_name. @@ -278,9 +280,10 @@ metrics: # Required: Expression definition with dialect support # Supports multiple SQL dialects for cross-platform compatibility # Each metric can have expressions in different dialects for portability - # References are dataset fields, not columns of the dataset's source - # Model-scoped metrics qualify them as dataset.field; dataset-scoped - # metrics use unqualified field names + # Model-scoped metrics reference dataset fields, qualified as dataset.field, + # 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 # At least one of the portable `sql` or `dialects` must be present; either may stand alone expression: diff --git a/python/src/ossie/models.py b/python/src/ossie/models.py index 4cd11736a..0d03c4227 100644 --- a/python/src/ossie/models.py +++ b/python/src/ossie/models.py @@ -313,7 +313,8 @@ class OssieDataset(BaseModel): description: Optional[str] = None ai_context: Optional[OssieAIContext] = None fields: Optional[list[OssieField]] = None - # Dataset-scoped: expressions reference this dataset's declared fields by single-part (unqualified) name. + # Dataset-scoped: expressions reference this dataset's declared fields by single-part + # (unqualified) name and its source columns as source.column. metrics: Optional[list[OssieMetric]] = None custom_extensions: Optional[list[OssieCustomExtension]] = None diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 1a9d5ec68..8546043fb 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1729,6 +1729,49 @@ 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_accepts_source_columns() -> None: + # The source qualifier is case insensitive, and reaches a column that a field + # of the same name shadows. + doc = _orders_with( + fields=[{"name": "amount", "expression": _ds_expr("amount * 100")}], + metrics=[ + {"name": "total_amount", "expression": _ds_expr("SUM(source.amount)")}, + {"name": "total_qty", "expression": _ds_expr("SUM(SOURCE.quantity)")}, + {"name": "total_cents", "expression": _ds_expr("SUM(amount)")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [] + + +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)")}], + ) + + errors = _VALIDATE.validate_metric_scoping(doc) + + assert any(error.startswith("[Scope]") and "'source'" in error for error in errors) + + +def test_dataset_scoped_metric_rejects_source_columns_when_a_field_is_named_source() -> None: + # A field named source takes precedence over the source qualifier. + doc = _orders_with( + fields=[{"name": "source", "expression": _ds_expr("channel")}], + metrics=[ + {"name": "sources", "expression": _ds_expr("COUNT(DISTINCT source)")}, + {"name": "total_amount", "expression": _ds_expr("SUM(source.amount)")}, + ], + ) + + assert _VALIDATE.validate_metric_scoping(doc) == [ + "[Scope] Dataset-scoped metric 'orders.total_amount' in model 'm' (OSSIE_SQL_2026) " + "uses source.column, but dataset 'orders' declares a field named 'source', which " + "takes precedence over the source qualifier. This dataset's metrics cannot refer " + "to source columns." + ] + + def test_dataset_scoped_metric_count_star_references_no_field() -> None: doc = _orders_with(metrics=[{"name": "n", "expression": _ds_expr("COUNT(*)")}]) @@ -1781,8 +1824,9 @@ def test_dataset_scoped_metric_portable_sql_rejects_a_cross_dataset_reference() assert _VALIDATE.validate_metric_scoping(doc) == [ "[Scope] Dataset-scoped metric 'orders.bad' in model 'm' (OSSIE_SQL_2026) uses " "qualified reference(s) 'customers'. A dataset-scoped metric expression must " - "reference the dataset's fields by single-part (unqualified) name; a metric that " - "must reference another dataset belongs in the model-root metrics." + "reference the dataset's fields by single-part (unqualified) name and its source " + "columns as source.column; a metric that must reference another dataset belongs " + "in the model-root metrics." ] @@ -1795,7 +1839,7 @@ def test_dataset_scoped_metric_portable_sql_rejects_an_undeclared_field() -> Non assert _VALIDATE.validate_metric_scoping(doc) == [ "[Scope] Dataset-scoped metric 'orders.total_qty' in model 'm' (OSSIE_SQL_2026) " "references undeclared field(s) 'quantity'. A dataset-scoped metric may reference " - "only the dataset's declared fields." + "only the dataset's declared fields, and its source columns as source.column." ] diff --git a/validation/validate.py b/validation/validate.py index c123869c5..9b9014a66 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -971,18 +971,24 @@ def validate_sql(data: dict) -> list[str]: return errors +# The qualifier for a dataset's source columns in its dataset-scoped metrics. +SOURCE_QUALIFIER = "source" + + def validate_metric_scoping(data: dict) -> list[str]: - """Validate the field references in each dataset-scoped metric expression. + """Validate the references in each dataset-scoped metric expression. A dataset-scoped metric references the declaring dataset's declared fields by - single-part (unqualified) name. Two rules are enforced: + single-part (unqualified) name, and its source columns as `source.column`. + These rules are enforced: - * No qualified reference (`dataset.field`): that is model-scoped and belongs - in the model-root metrics. - * Every field a dataset-scoped metric references must be a declared field of - the dataset; referencing an undeclared name (e.g. a raw source column) is - not yet allowed. A bare name is compared case-insensitively; `COUNT(*)` and - literals reference no field and are fine. + * 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. + * `source.column` is not allowed when the dataset declares a field named + `source`, since the field takes precedence over the qualifier. Checking the expression needs sqlglot; dialects it cannot parse are skipped rather than reported. @@ -1002,9 +1008,12 @@ def scope_errors(expression: Expression) -> list[str]: qualifiers = set() undeclared = set() + uses_source = False for col in tree.find_all(exp.Column): parts = [part.name for part in col.parts] - if len(parts) > 1 and parts[0]: + 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]) @@ -1019,14 +1028,21 @@ def scope_errors(expression: Expression) -> list[str]: out.append( f"{prefix} uses qualified reference(s) {names}. A dataset-scoped metric " f"expression must reference the dataset's fields by single-part " - f"(unqualified) name; a metric that must reference another dataset " - f"belongs in the model-root metrics." + f"(unqualified) name and its source columns as source.column; a metric " + f"that must reference another dataset belongs in the model-root metrics." ) if undeclared: names = ", ".join(repr(n) for n in sorted(undeclared)) out.append( f"{prefix} references undeclared field(s) {names}. A dataset-scoped " - f"metric may reference only the dataset's declared fields." + 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: + out.append( + f"{prefix} uses source.column, but dataset '{expression.dataset_name}' " + f"declares a field named 'source', which takes precedence over the source " + f"qualifier. This dataset's metrics cannot refer to source columns." ) return out