diff --git a/core-spec/expression_language.md b/core-spec/expression_language.md index de65ecf0..fcb4931f 100644 --- a/core-spec/expression_language.md +++ b/core-spec/expression_language.md @@ -112,8 +112,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, 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 **field expression**, identifiers refer to columns of the dataset's `source`. A field expression cannot refer to other fields or to a measure column of the `source`. +* 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. Inside `AGG`, an identifier written `source.measure` refers to a measure column of the dataset's `source`; this is the only way to refer to a source measure. * 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. @@ -152,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(...)` outside a model-scoped metric | Reserved for a future version. See [Measure Evaluation: `AGG`](#measure-evaluation-agg). | +| `AGG(...)` outside a metric | Reserved for a future version. Metrics may call `AGG` only in the forms that [Measure Evaluation: `AGG`](#measure-evaluation-agg) lists. | ### Operator Precedence @@ -284,7 +284,12 @@ A non-matching row contributes `NULL`, which these functions ignore. An `ELSE 0` 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`. -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. +This version defines two uses of `AGG`, both in metrics (see [Metric Scoping](spec.md#metric-scoping)): + +* 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. +* A dataset-scoped metric may use `AGG` to evaluate a measure of the dataset's `source`, as in `AGG(source.total_revenue)`, when the `source` is a measure relation (see [Measure Relation as a `source`](spec.md#measure-relation-as-a-source)). The argument is a single `source.measure` reference. The call composes the measure into the metric: the measure is evaluated when a consuming query evaluates the metric, not where the metric is defined. + +In both uses, the call takes no `FILTER (WHERE ...)` clause. `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`. @@ -930,7 +935,8 @@ 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)` | +| 0.3.0.dev0 | 2026-11-06 | Allow model-scoped metrics to evaluate a dataset-scoped metric with `AGG(dataset.metric)` | +| 0.3.0.dev0 | 2026-11-20 | Allow dataset-scoped metrics to evaluate a source measure with `AGG(source.measure)` when the `source` is a measure relation | --- diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index 6fcbc83e..8c9b9340 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -254,7 +254,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 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." + "description": "Dataset-scoped metrics: measures defined on this dataset's relation that semantically belong to the dataset. A metric aggregates the dataset's rows, or derives from measures of the dataset's source. The expression references this dataset's declared fields by single-part (unqualified) name, and columns of the dataset's source as source.column. When the source is a measure relation, it may evaluate a source measure with AGG(source.measure). 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." }, "nonportable_extensions": { "type": "array", diff --git a/core-spec/relational_semantics.md b/core-spec/relational_semantics.md index 90761650..3902fb63 100644 --- a/core-spec/relational_semantics.md +++ b/core-spec/relational_semantics.md @@ -244,8 +244,8 @@ SQL-native names. The correspondence: |---|---|---| | relation | `dataset` | A logical table (fact or dimension) exposed as a SQL relation. | | field | `field` | A scalar (non-measure) column; we adopt Ossie's term. Ossie's optional `dimension` role (e.g. `is_time`) is metadata this interface does not require. | -| measure | dataset-scoped `metric` (`datasets[].metrics`) | An aggregate expression over the dataset's rows (of any scalar result type), exposed as a measure on the dataset's relation. Model-scoped metrics are not exposed as measure columns (Section 10.3). | -| row identity (Section 3.2) | `primary_key` | A dataset's declared primary key is a natural source of a measure's row identity. | +| measure | dataset-scoped `metric` (`datasets[].metrics`) | A measure on the dataset's relation, of any scalar result type. A dataset-scoped metric that composes measures of the dataset's `source` with `AGG(source.measure)` is a derived measure (Section 5.2), and the dataset remains a relation. The `source` must be a measure relation (see [Measure Relation as a `source`](spec.md#measure-relation-as-a-source)). Each measure of the `source` that it references keeps its own source rows and row identity, which can originate upstream of the dataset (Sections 3.2 and 3.3); its other aggregates read the dataset's rows. Model-scoped metrics are not exposed as measure columns (Section 10.3). | +| row identity (Section 3.2) | `primary_key` | A dataset's declared primary key is a natural source of the row identity of a base measure. A measure of the dataset's `source` that a derived measure evaluates keeps the row identity that it has there. | | join relationship (Section 11.3) | `relationship` (`from`/`to`, `from_columns`/`to_columns`) | `from`/`to` map to source/target and the columns to the join predicate (`from` many, `to` one); Section 11.3 adds cardinality, roles, and arbitrary `ON`. | | Layer 1 expression | `OSSIE_SQL_2026` expression (`expression.sql`, or an `OSSIE_SQL_2026` entry in `dialects`) | The portable form of an Ossie expression, in the Layer 1 language (Section 1.1). For the resolution rules, see [Expression Object](spec.md#expression-object). | diff --git a/core-spec/spec.md b/core-spec/spec.md index 0d7d52a1..cefe33b6 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -173,7 +173,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 its source columns as `source.column`, 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. When the `source` is a measure relation, they may evaluate its measures with `AGG(source.measure)`. See [Metric Scoping](#metric-scoping). | | `nonportable_extensions` | array | No | Vendor-specific attributes | ### Primary Key Examples @@ -321,6 +321,7 @@ expression: - At least one of the top-level `sql` or `dialects` MUST be present; either MAY stand alone - If both the top-level `sql` and an `OSSIE_SQL_2026` entry in `dialects` are present, the top-level `sql` is authoritative and consumers MUST use it as the OSSIE_SQL_2026 form - Identifiers refer to columns of the dataset's `source`, not to other fields. See [Name Resolution](#name-resolution). +- A field expression MUST NOT refer to a measure column of the `source`, because a field is never a measure. A dataset-scoped metric evaluates a source measure with `AGG(source.measure)`. A consumer that generates SQL against the `source` checks this rule (see [Metric Scoping](#metric-scoping), rule 9). - Multiple dialect versions can be provided for the same field ### Dimension Object @@ -423,7 +424,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`. 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. +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. When a dataset's `source` is a measure relation, its dataset-scoped metrics may evaluate the source's measures with `AGG(source.measure)`. See [Metric Scoping](#metric-scoping) for the rules governing each and [Name Resolution](#name-resolution) for how names resolve. ### Schema @@ -484,12 +485,12 @@ At least one of the top-level `sql` or `dialects` MUST be present; either MAY st A metric may be defined on an individual dataset or at the model level. Both placements use the identical metric structure; they differ in what the expression may reference and in what the metric is for: -- A **dataset-scoped** metric (`datasets[].metrics`) belongs to a single dataset: it aggregates that dataset's own fields, at the dataset's row level, so the dataset carries its own measures and stays queryable on its own. +- A **dataset-scoped** metric (`datasets[].metrics`) belongs to a single dataset and is defined on the dataset's relation: it aggregates the dataset's rows, or derives from measures that the dataset's `source` exposes (rules 7 and 8), so the dataset carries its own measures and stays queryable on its own. - A **model-scoped** metric (the model-root `metrics`) spans datasets across the model: it combines fields from more than one dataset. | | Dataset-scoped (`datasets[].metrics`) | Model-scoped (model-root `metrics`) | |---|---|---| -| Expression references | This dataset's declared fields, single-part: `field`; columns of its `source`: `source.column` | Fields of any dataset, multi-part: `dataset.field` | +| Expression references | This dataset's declared fields, single-part: `field`; columns of its `source`: `source.column`; inside `AGG`, measures of its `source`: `AGG(source.measure)` | Fields of any dataset, multi-part: `dataset.field`; inside `AGG`, dataset-scoped metrics: `AGG(dataset.metric)` | | Spans datasets | No | Yes, via relationships | | Referenced as | `dataset_name.metric_name` | `metric_name` | @@ -501,6 +502,9 @@ A metric may be defined on an individual dataset or at the model level. Both pla 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. +7. A dataset-scoped metric MAY evaluate a measure of the dataset's `source` with `AGG(source.measure)` if the `source` is a measure relation (see [Measure Relation as a `source`](#measure-relation-as-a-source)): `AGG(source.total_revenue) / COUNT(DISTINCT order_id)`. The argument MUST be a single reference to a measure of the `source`, written as `source.measure`, and the call MUST NOT have a `FILTER (WHERE ...)` clause. A dataset-scoped metric MUST NOT refer to a source measure in any other way, and MUST NOT call `AGG` in any other way: `SUM(source.total_revenue)`, `AGG` of a field, and `AGG` of a metric are invalid. If the `source` is not a measure relation, a dataset-scoped metric MUST NOT call `AGG`. +8. A dataset-scoped metric that calls `AGG` is a derived measure ([Relational Query Interface](relational_semantics.md), Section 5.2), and its dataset remains a relation with the metric as a measure column. The `AGG(source.measure)` call composes the source measure into the metric and does not evaluate it where the metric is defined: the source measure is evaluated when a consuming query evaluates the metric, in that query's context. Each measure of the `source` keeps the rows that it aggregates and their row identity (Sections 3.2 and 3.3 of that document), also when the `source` has measures with different row identities. So the metric keeps the no-duplication guarantee of each source measure (Section 8.3 of that document), also when a model-scoped metric evaluates it with `AGG(dataset.metric)`. Its other aggregates, such as `COUNT(DISTINCT order_id)`, aggregate the dataset's rows. +9. The Ossie document does not declare which source columns are measures, so document validation checks only the form of each `AGG` call. A consumer that generates SQL against the dataset's `source` MUST reject a metric or field that refers to a source measure outside `AGG`, and a metric that calls `AGG` on a column that is not a measure of the `source`, including when the `source` has no measures. It MUST NOT replace `AGG` with an ordinary aggregate, and MAY reject a `source` that it does not support. **Example: dataset-scoped metrics** @@ -535,6 +539,34 @@ datasets: Referenced from a consumer as `orders.total_net_amount` and `orders.order_count`. +**Example: dataset-scoped metrics over a measure relation** + +```yaml +datasets: + - name: orders + source: sales.semantic.order_metrics # a measure relation: total_revenue is a measure column + fields: + - name: order_id + expression: + sql: order_id + - name: region + expression: + sql: region + + metrics: + - name: revenue + expression: + sql: AGG(source.total_revenue) + description: Revenue, as the source measure defines it + + - name: revenue_per_order + expression: + sql: AGG(source.total_revenue) / COUNT(DISTINCT order_id) + description: Revenue divided by the number of orders +``` + +In this dataset, `AGG(total_revenue)`, `AGG(region)`, and `SUM(source.total_revenue)` are invalid (rule 7). A field with the expression `total_revenue` is also invalid, because a field expression cannot refer to a measure column (see [Fields](#fields)). + **Example: invalid dataset-scoped metric** ```yaml @@ -553,6 +585,21 @@ datasets: sql: SUM(net_amount) / COUNT(DISTINCT customers.id) ``` +#### Measure Relation as a `source` + +The [Relational Query Interface](relational_semantics.md) defines a measure relation as a relation with at least one measure column (Section 3.1). This section applies that definition to a `source`, which is an object that an engine holds. For rule 7, a `source` is a measure relation if and only if it has at least one measure column and all of these conditions hold. The section numbers refer to that document. + +1. **One multiset of rows.** The `source` has one multiset of rows, and every query over the `source` reads it. The multiset does not depend on the columns that a query selects. So, for the same grouping columns and filters, a query returns the same groups whether it evaluates no measure, one measure, or several measures (Section 8.4). +2. **Every measure by every column.** A query can group and filter every measure by every column of the `source` that is not a measure (Sections 7.3 and 7.4). +3. **Measure evaluation.** Each measure aggregates rows that are fixed where the measure is defined. Those rows have a row identity that a query does not change (Section 3.2). A query evaluates the measure as Section 8.1 defines. +4. **Joins.** A query can join the `source` to another relation. In that query, each measure still aggregates each of its rows at most once in each group (Sections 7.6 and 8.3). + +An engine that conforms to the Relational Query Interface (Section 12 of that document) exposes measure relations that meet these conditions. + +The conditions apply to each `source`, and to the results that its queries return. The Layer 3 wide table ([Wide Table Query Interface](wide_table_semantics.md)) is not a measure relation, even if a query can name it in `FROM` and evaluate its metrics with `AGG`: the groups that a query returns depend on the metrics that it evaluates (Section 6.1 of that document), so condition 1 does not hold. + +The relation of an Ossie dataset that has dataset-scoped metrics is a measure relation (Section 3.4 of the Relational Query Interface). This version still does not support a dataset that uses another dataset as its `source` (see [Name Resolution](#name-resolution)). + --- ## Non-portable Extensions @@ -647,7 +694,10 @@ see [extensions/vendors.md](../extensions/vendors.md). An Ossie model has three levels of names: 1. **Source columns.** The columns of the table, view, or query named by a - dataset's `source`. The Ossie document does not declare them. + dataset's `source`. The Ossie document does not declare them. When the + `source` is a measure relation, some of its columns are measures; only a + dataset-scoped metric can refer to them, inside `AGG` (see + [Metric Scoping](#metric-scoping), rules 7 to 9). 2. **Dataset fields.** The fields declared in a dataset's `fields`. Each field is defined in terms of that dataset's source columns, just as a view's `SELECT` list can only reference columns from its `FROM` clause. A dataset's @@ -655,7 +705,8 @@ An Ossie model has three levels of names: 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`. + written as `source.column`, and evaluate its source measures with + `AGG(source.measure)`. 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 @@ -663,11 +714,11 @@ exposes nothing to keys, relationships, or model-scoped metrics. | Where the name appears | What it refers to | |------------------------|-------------------| -| Field `expression` | A column of the same dataset's `source` | +| Field `expression` | A column of the same dataset's `source` that is not a measure | | `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`) | Unqualified: a field of the same dataset. `source.column`: a column of its `source` | +| Dataset-scoped metric `expression` (`datasets[].metrics`) | Unqualified: a field of the same dataset. `source.column`: a column of its `source` that is not a measure. Inside `AGG`: a measure column of its `source`, qualified as `source.measure` | | 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 @@ -725,7 +776,8 @@ 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, and each `source.column` reference with `column`. For example, `SUM(orders.total_amount)` compiles to `SUM(o_totalprice)` over -`sales.public.orders`. +`sales.public.orders`, and a dataset-scoped `AGG(source.total_revenue)` +compiles to `AGG(total_revenue)` over the dataset's `source`. This version of the specification does not support: @@ -886,6 +938,7 @@ including rationale and migration impact for consumers, see the - 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). - Breaking: a key names each field once. `primary_key` and each `unique_keys` definition may no longer repeat a field, and because field names resolve case-insensitively, `[email, EMAIL]` repeats one. Documents that named a field twice declared fewer columns than they appeared to and now fail validation. A `unique_keys` definition that restates another remains valid and is reported as a warning. See [Datasets](#datasets). + - Dataset-scoped metric expressions may evaluate a measure of the dataset's `source` with `AGG(source.measure)` when the `source` is a measure relation. A field expression must not refer to a measure 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 b0751071..edf973c5 100644 --- a/core-spec/spec.yaml +++ b/core-spec/spec.yaml @@ -141,9 +141,10 @@ datasets: fields: [] # Optional: Dataset-scoped metrics - # Metrics that semantically belong to this dataset, aggregating its own - # fields at the dataset's row level. Same structure as model-scoped metrics; - # see the Metrics section below. + # Metrics that semantically belong to this dataset, defined on its + # relation: each aggregates the dataset's rows, or derives from measures of + # its source. Same structure as model-scoped metrics; see the Metrics + # section below. # # Rules (see core-spec/spec.md#metric-scoping): # - The expression MUST reference only this dataset's declared fields, @@ -152,6 +153,15 @@ datasets: # - 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. + # - When the source is a measure relation (see + # core-spec/spec.md#measure-relation-as-a-source), the expression MAY + # evaluate a source measure with AGG(source.measure): + # AGG(source.total_revenue). The argument MUST be a single + # source.measure reference, and the call MUST NOT have a FILTER + # clause. A source measure MUST NOT be referenced + # outside AGG, and AGG MUST NOT be used in any other way. Whether a + # column is a measure is checked by a consumer that generates SQL against + # the source, not from this document. # - It MUST NOT reference another dataset; a metric that must do so is # model-scoped and belongs in the model-root metrics. # - Field names and metric names share one namespace; every name MUST be @@ -219,6 +229,7 @@ fields: # Each field can have expressions in different dialects for portability # Can be a simple column reference or a complex scalar expression # Identifiers refer to columns of the dataset's source, not to other fields + # A field expression MUST NOT refer to a measure column of the source # 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., "customer_id", "first_name || ' ' || last_name" @@ -283,7 +294,8 @@ metrics: # 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 + # reference source columns as source.column and evaluate source measures + # as AGG(source.measure) # 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 diff --git a/core-spec/wide_table_semantics.md b/core-spec/wide_table_semantics.md index b1f3cffd..98aa3d2c 100644 --- a/core-spec/wide_table_semantics.md +++ b/core-spec/wide_table_semantics.md @@ -221,7 +221,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. +- 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. This also holds when the expression calls `AGG(source.measure)`: the source measure keeps the rows that it aggregates and their row identity (core specification, Metric Scoping, rule 8), and `D.m` is still one measure of `D` 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). 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/docs/index.md b/docs/index.md index c46e2f93..ec0436f2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -55,7 +55,7 @@ The Ossie core specification (current version: **0.3.0.dev0**, latest released: | **Datasets** | Logical datasets representing business entities (fact and dimension tables), with fields, primary keys, and unique keys. | | **Fields** | Row-level attributes for grouping, filtering, and metric expressions. Fields support multiple SQL dialects for cross-platform compatibility. | | **Relationships** | Foreign key connections between datasets, supporting both simple and composite keys. | -| **Metrics** | Quantitative measures (sums, averages, ratios, etc.). A model-scoped metric's expression may combine fields from several datasets; a dataset-scoped metric aggregates one dataset's own fields at its row level. | +| **Metrics** | Quantitative measures (sums, averages, ratios, etc.). A model-scoped metric's expression may combine fields from several datasets; a dataset-scoped metric is defined on one dataset's relation: it aggregates the dataset's rows, or derives from measures of the dataset's `source`. | | **Non-portable Extensions** | Vendor-specific metadata in `nonportable_extensions`. Core semantics do not depend on it. Behavior defined only there is not portable Ossie behavior. | | **AI Context** | Optional annotations at every level (model, dataset, field, relationship, metric) to help AI tools understand business meaning — including instructions, synonyms, and example queries. | @@ -307,7 +307,7 @@ A practical guide for organizations looking to adopt Ossie. | **Dataset** | A logical representation of a business entity, typically corresponding to a fact table or dimension table in a data warehouse. | | **Field** | A row-level attribute within a dataset, used for grouping, filtering, or as part of metric expressions. Fields can be simple column references or computed expressions. A field's logical data type is declared by the optional top-level `datatype` field (one of `String`, `Integer`, `Decimal`, `Float`, `Boolean`, `Date`, `Time`, `DateTime`, `DateTimeTz`, or `Opaque`). | | **Dimension** | A categorical attribute used to slice and filter data (e.g., region, product category, date). In Ossie, dimensions are represented as fields with optional metadata such as `is_time`. | -| **Metric** | A quantitative measure computed by aggregating fields (e.g., total revenue, average order value). A dataset-scoped metric is defined on an individual dataset, for a measure that semantically belongs to it and is evaluated at the dataset's row level; a model-scoped metric is defined at the model root and may span datasets. | +| **Metric** | A quantitative measure computed by aggregating fields (e.g., total revenue, average order value). A dataset-scoped metric is defined on an individual dataset's relation, for a measure that semantically belongs to the dataset: it aggregates the dataset's rows, or derives from measures of the dataset's `source`; a model-scoped metric is defined at the model root and may span datasets. | | **Relationship** | A foreign key connection between two datasets, defining how they can be joined. Relationships are always many-to-one (from the referencing dataset to the referenced dataset). | | **Dialect** | A SQL or expression language variant an expression is written in (e.g., `ANSI_SQL`). A free-form string; `OSSIE_SQL_2026` is the only dialect Ossie defines, and all others are opaque. | | **Non-portable Extension** | Vendor-specific metadata on a model, dataset, field, relationship, or metric, stored as `nonportable_extensions`. The core specification does not interpret it, and portable behavior does not depend on it. | diff --git a/docs/spec_changes.md b/docs/spec_changes.md index 6aec4c05..fc0a5f5c 100644 --- a/docs/spec_changes.md +++ b/docs/spec_changes.md @@ -56,7 +56,9 @@ the [current core specification](../core-spec/spec.md) and | 2026-11-09 | Core / Ontology [#691](https://github.com/apache/ossie/pull/691) | **Move the in-development version to `0.3.0.dev0`.** The next planned release is `0.3.0-incubating`; no `0.2.0` release is planned. | **Breaking for development documents.** Version constants in the current schemas reject `0.2.0.dev0`; producers must declare `0.3.0.dev0` and coordinate schema/package/converter versions. This is a development-version change, not a release announcement. | | 2026-11-10 | Core [#522](https://github.com/apache/ossie/pull/522) | **Object `nonportable_extensions` data.** Vendor extension payloads become objects, and the field is renamed from `custom_extensions` so portable core semantics stay separate from vendor state. The core schema does not describe keys under `data`. | **Breaking within unreleased `0.3.0.dev0`.** Rename the field to `nonportable_extensions` and write `data` as an object, not a JSON string. The old name does not validate. Quote scalars under `data` that YAML may read as a boolean, number, or date. See [nonportable extensions](../extensions/nonportable_extensions.md). | | 2026-11-12 | Expression language [#687](https://github.com/apache/ossie/pull/687) | **`ROUND` ties and true division in `OSSIE_SQL_2026`.** `ROUND` rounds half away from zero, and `/` is true division also for two integers, because engines differ on both and the same portable metric returned different numbers ([#643](https://github.com/apache/ossie/issues/643); [dev@ lazy consensus](https://lists.apache.org/thread/c1hy8vw7fqcp2y2hhxzj582516wqkoq6)). | Engines and converters with half-to-even `ROUND` or integer division emit the equivalent expressions the Numeric Semantics section gives; exact where `DECIMAL` arithmetic stays `DECIMAL`, best effort for exact ties of binary floating-point values. Documents need no change. | +| 2026-11-13 | Core / Expression language [#703](https://github.com/apache/ossie/pull/703) | **`AGG(dataset.metric)` in model-scoped metrics.** A model-scoped metric can evaluate a dataset-scoped metric, so a model reuses the metric instead of repeating its definition. | Additive. The argument is a single `dataset.metric` reference, and the call takes no `FILTER (WHERE ...)` clause. A model-scoped metric cannot refer to a metric in any other way. Consumers that read model-scoped metrics must resolve `AGG(dataset.metric)`. Existing documents need no change. | | 2026-11-13 | Core / Ontology [#705](https://github.com/apache/ossie/pull/705) | **A key, and an ontology list of names or expressions, names each thing once.** A key is the set of fields it names, and a supertype, identifying relationship, constraint or verbalization pattern given twice says nothing the first already said. | **Validation becomes stricter.** `primary_key` and each `unique_keys` definition reject a repeated field, as do the ontology's `extends`, `identify_by` and `verbalizes` lists and `requires` and `derived_by` wherever they appear. Field names resolve case-insensitively, so `[email, EMAIL]` repeats one field; that case is reported by the validator rather than the schema. Remove the duplicate entry; a document that had one declared less than it appeared to. A `unique_keys` definition that restates another remains valid and is reported as a warning. | +| 2026-11-20 | Core / Expression language [#726](https://github.com/apache/ossie/pull/726) | **`AGG(source.measure)` in dataset-scoped metrics.** When a dataset's `source` is a measure relation, a dataset-scoped metric can compose a source measure into its expression, so a model reuses the measure instead of repeating its definition. The measure keeps the rows that it aggregates and their row identity, and is evaluated when a consuming query evaluates the metric. A `source` is a measure relation only if every query reads one multiset of rows, can group and filter every measure by every other column, and can join the `source` with no duplication in a measure. | Additive. Document validation checks only the form of each `AGG` call. A consumer that generates SQL against a dataset's `source` must reject a metric or field that refers to a source measure outside `AGG`, and a metric that calls `AGG` on a column that is not a measure of the `source`. It must not replace `AGG` with an ordinary aggregate, and may reject a `source` that it does not support. Existing documents need no change. | ## Semi-automated discovery and upkeep diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index f9f77706..4e14aefb 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -3574,25 +3574,113 @@ def test_rejects_an_invalid_agg_call(expression: str, expected: str) -> None: assert not isinstance(errors[0], _VALIDATE.ValidationWarning) +def test_rejects_agg_in_a_field_expression() -> None: + document = _renamed_model() + document["datasets"][0]["fields"] = [ + {"name": "revenue", "expression": {"sql": "AGG(source.revenue)"}} + ] + + errors = _VALIDATE.validate_agg_placement(document) + + assert len(errors) == 1 + assert ( + "Field 'orders.revenue' in model 'm' (OSSIE_SQL_2026) calls AGG in a field expression" + ) in errors[0] + assert not isinstance(errors[0], _VALIDATE.ValidationWarning) + + +def _orders_metrics(**metrics: str) -> dict: + """The renamed model, with the given OSSIE_SQL_2026 dataset-scoped metrics on + orders, by name. The source of orders stands for a measure relation.""" + document = _renamed_model() + document["datasets"][0]["metrics"] = [ + {"name": name, "expression": {"sql": sql}} for name, sql in metrics.items() + ] + return document + + +def _source_measure_findings(document: dict) -> list[str]: + """The checks that read the AGG calls of dataset-scoped metrics.""" + return ( + _VALIDATE.validate_metric_scoping(document) + + _VALIDATE.validate_agg_placement(document) + ) + + @pytest.mark.parametrize( - ("kind", "expected"), + "expression", [ - ("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"), + "AGG(source.revenue)", + "agg(SOURCE.revenue)", + 'AGG(source."Revenue")', + "AGG(source.revenue) / COUNT(DISTINCT order_id)", + "COALESCE(AGG(source.revenue), 0) - AGG(source.refunds)", + "CASE WHEN COUNT(*) > 0 THEN AGG(source.revenue) END", ], ) -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] +def test_accepts_agg_of_a_source_measure(expression: str) -> None: + assert _source_measure_findings(_orders_metrics(revenue_total=expression)) == [] - errors = _VALIDATE.validate_agg_placement(document) - assert len(errors) == 1 +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. + document = _orders_metrics( + revenue_total="AGG(source.revenue)", + revenue_per_order="AGG(source.revenue) / COUNT(DISTINCT order_id)", + ) + document["metrics"] = [ + { + "name": "revenue_per_customer", + "expression": {"sql": "AGG(orders.revenue_total) / COUNT(DISTINCT customers.id)"}, + } + ] + + assert _VALIDATE.validate_document(document, core_schema) == [] + + +@pytest.mark.parametrize( + ("expression", "expected"), + [ + ("AGG(total_usd)", "AGG(total_usd): AGG in a dataset-scoped metric takes"), + ("AGG(order_count)", "AGG(order_count): AGG in a dataset-scoped metric takes"), + ("AGG(orders.order_count)", "AGG(orders.order_count): AGG in a dataset-scoped metric"), + ("AGG(source.revenue + 1)", "AGG(source.revenue + 1): AGG in a dataset-scoped metric"), + ("AGG(DISTINCT source.revenue)", "AGG(DISTINCT source.revenue): AGG in a dataset-scoped"), + ("AGG(source.*)", "AGG(source.*): AGG in a dataset-scoped metric takes"), + ("AGG(db.source.revenue)", "AGG(db.source.revenue): AGG in a dataset-scoped metric"), + ('AGG(source."")', 'AGG(source.""): AGG in a dataset-scoped metric takes'), + ( + "AGG(source.revenue) FILTER (WHERE order_id = 1)", + "AGG(source.revenue) has a FILTER (WHERE ...) clause; AGG does not take one", + ), + ], +) +def test_rejects_an_invalid_dataset_scoped_agg_call(expression: str, expected: str) -> None: + # As in a model-scoped metric, a misused AGG call is an error: no model + # written before AGG was allowed in dataset-scoped metrics can contain one. + document = _orders_metrics(order_count="COUNT(*)", revenue_total=expression) + + errors = _source_measure_findings(document) + + assert len(errors) == 1, errors + assert errors[0].startswith( + "[Scope] Metric 'orders.revenue_total' in model 'm' (OSSIE_SQL_2026): " + ) assert expected in errors[0] assert not isinstance(errors[0], _VALIDATE.ValidationWarning) +def test_rejects_agg_of_a_source_measure_when_a_field_is_named_source() -> None: + document = _orders_metrics(revenue_total="AGG(source.revenue)") + document["datasets"][0]["fields"].append(_field("source", "src")) + + errors = _source_measure_findings(document) + + assert len(errors) == 1, errors + assert "declares a field named 'source'" in errors[0] + + 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) == [] diff --git a/validation/validate.py b/validation/validate.py index e12ff4f8..158f831b 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1929,8 +1929,9 @@ 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. + # validate_agg_placement checks each OSSIE_SQL_2026 AGG call here: it accepts + # AGG(source.measure) and reports any other form. So the names inside an + # AGG call are not checked again. inside_agg = set() if expression.dialect == PORTABLE_DIALECT: for call in tree.find_all(exp.Agg): @@ -1998,13 +1999,43 @@ 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. +def source_agg_problem(call, field_names: frozenset[str]) -> str | None: + """Why an AGG call in a dataset-scoped metric is not AGG(source.measure) + without a FILTER clause, or None if it is (spec.md, Metric Scoping, rule 7). + The document does not declare which source columns are measures, so only + the form of the call is checked (rule 9).""" + expected = "AGG in a dataset-scoped metric takes a single source.measure reference" + arg = call.this + 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 + ): + return f"AGG({arg.sql() if arg else ''}): {expected}" + if SOURCE_QUALIFIER in field_names: + return ( + f"AGG({arg.sql()}): the dataset declares a field named 'source', which takes " + f"precedence over the source qualifier, so this dataset's metrics cannot " + f"refer to source measures" + ) + if isinstance(call.parent, exp.Filter): + return f"AGG({arg.sql()}) has a FILTER (WHERE ...) clause; AGG does not take one" + return None - 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. + +def validate_agg_placement(data: dict) -> list[str]: + """Report AGG in a field expression, and an AGG call in a dataset-scoped + metric that is not AGG(source.measure) without a FILTER clause. + + This version allows AGG only in metrics (expression_language.md, Measure + Evaluation: AGG): as AGG(dataset.metric) in a model-scoped metric, which + validate_metric_references checks, and as AGG(source.measure) in a + dataset-scoped metric (spec.md, Metric Scoping, rule 7), which is checked + here. The document does not declare which source columns are measures, so + only the form of each call is checked (rule 9). 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 [] @@ -2025,11 +2056,17 @@ def validate_agg_placement(data: dict) -> list[str]: 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)." - ) + if expression.kind == "field": + errors.append( + f"[Scope] {context} calls AGG in a field expression. This version allows " + f"AGG only in metrics, as AGG(dataset.metric) in a model-scoped metric and " + f"AGG(source.measure) in a dataset-scoped metric." + ) + continue + for call in tree.find_all(exp.Agg): + message = source_agg_problem(call, expression.field_names) + if message: + errors.append(f"[Scope] {context}: {message}") return errors