From 4c853495b018c8fbe2afa693acdc98f9d2ce3c96 Mon Sep 17 00:00:00 2001 From: Ayush Saxena Date: Wed, 11 Nov 2026 07:54:47 +0530 Subject: [PATCH 1/2] fix(core-spec, ontology): reject a list that names the same thing twice No schema used uniqueItems, so a key could name one field twice and a list could carry the same entry twice: primary_key: [order_id, order_id] unique_keys: [[order_id, order_id]] verbalizes: ["{Order} has {Total}", "{Order} has {Total}"] A key that repeats a field declares fewer columns than it appears to, and a repeated entry constrains, derives, names or verbalizes nothing the first already did. ossie-schema.json marks primary_key and each definition inside unique_keys. ontology.json marks the eight lists of names and expressions: extends, identify_by and verbalizes, and requires and derived_by wherever they appear. models.py mirrors the two core-spec keys. Pydantic 2 dropped unique_items, so an AfterValidator stands in for it, as min_length already stands in for minItems. The list of unique_keys definitions carries no uniqueItems. A definition written twice is redundant rather than wrong, and a schema error stops the semantic checks, so the author would lose every reference and SQL diagnostic over a document that states nothing untrue. uniqueItems also compares entries as written, while a key means the set of fields its entries name, and regular identifiers are case insensitive (expression_language.md), so a schema keyword could not reach these at all: primary_key: [order_id, ORDER_ID] unique_keys: [[order_id, line_number], [line_number, order_id]] validate_key_declarations reports both, and the verbatim repeat with them. A key that names one field twice claims a column it does not have, which is an error. Two unique_keys definitions holding the same set of fields are one key written twice, which is redundant, so that is a warning. Definitions are compared by position rather than by identity, because a YAML alias, unique_keys: [&k [email], *k], makes one list object the value of two. An entry whose folded form names no declared field is left out of both: it names nothing to compare, validate_references reports it as undeclared, and calling it a repeat would name a field the dataset does not have. An empty entry, which passes the schema because key items carry no minLength, is dropped the same way but without discarding the entries beside it. A dataset that declares two field names differing only in case declares one field twice, so a key naming both spellings names that field twice and is reported. validate_unique_names compares field names as written and does not report the declaration itself; closing that gap is a change of its own, and it does not make the key's two entries two fields. A unique key that restates the primary key stays silent: DDL commonly declares both, and examples/tpcds_semantic_model.yaml does so in five of its datasets. Relationship from_columns and to_columns are left alone as well: they correspond positionally, so one column of the from dataset may legitimately be compared with two columns of the to dataset. The field tables state the constraints alongside the others they already state. spec.md describes primary_key and unique_keys as naming each field once, with a paragraph on the recased and reordered cases; ontology.md marks its seven documented lists in the convention #673 introduced and documents the root requires, which no row covered. Both Version Histories record the change, and docs/spec_changes.md records its migration impact. --- core-spec/ossie-schema.json | 8 +- core-spec/spec.md | 12 +- docs/spec_changes.md | 1 + ontology/ontology.json | 8 ++ ontology/ontology.md | 21 ++- python/src/ossie/models.py | 25 +++- python/tests/test_models.py | 72 ++++++++++ validation/tests/test_ontology.py | 67 ++++++++++ validation/tests/test_validate.py | 213 ++++++++++++++++++++++++++++++ validation/validate.py | 119 ++++++++++++++++- 10 files changed, 531 insertions(+), 15 deletions(-) diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index 1f60cfad..6fcbc83e 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -219,7 +219,8 @@ "type": "string" }, "minItems": 1, - "description": "Dataset fields that uniquely identify rows" + "uniqueItems": true, + "description": "Dataset fields that uniquely identify rows, each named once" }, "unique_keys": { "type": "array", @@ -228,10 +229,11 @@ "items": { "type": "string" }, - "minItems": 1 + "minItems": 1, + "uniqueItems": true }, "minItems": 1, - "description": "Array of unique key definitions, each a list of dataset fields" + "description": "Array of unique key definitions, each a list of dataset fields naming each field once" }, "description": { "type": "string", diff --git a/core-spec/spec.md b/core-spec/spec.md index 129729f4..51d404f7 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -168,8 +168,8 @@ Logical datasets represent business entities or concepts (fact and dimension tab |-------|------|----------|-------------| | `name` | string | Yes | Unique identifier for the dataset | | `source` | string | Yes | Reference to underlying physical table/view (e.g., `database.schema.table`) or query | -| `primary_key` | array | No | Dataset fields that uniquely identify rows | -| `unique_keys` | array of arrays | No | Array of unique key definitions, each a list of dataset fields | +| `primary_key` | array | No | Dataset fields that uniquely identify rows, each named once | +| `unique_keys` | array of arrays | No | Array of unique key definitions, each a list of dataset fields naming each field once | | `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 | @@ -195,6 +195,13 @@ unique_keys: - [first_name, last_name] # Composite unique key ``` +A key is the set of fields it names, so it names each of them once. Field names +resolve case-insensitively (see [Name Resolution](#name-resolution)), so +`[email, EMAIL]` names one field twice and is invalid. Two `unique_keys` +definitions that name the same fields, in any order and in any case, declare one +key twice; that is redundant rather than invalid, and validation reports it as a +warning. + ### Example ```yaml @@ -877,6 +884,7 @@ including rationale and migration impact for consumers, see the - 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). + - 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). - **0.1.1** (2025-12-11): Initial release - Core semantic model structure - Support for datasets, relationships, fields, and metrics diff --git a/docs/spec_changes.md b/docs/spec_changes.md index 81109562..9e6ef554 100644 --- a/docs/spec_changes.md +++ b/docs/spec_changes.md @@ -56,6 +56,7 @@ 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-11 | 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. | ## Semi-automated discovery and upkeep diff --git a/ontology/ontology.json b/ontology/ontology.json index 5a3064a9..fb7b04b9 100644 --- a/ontology/ontology.json +++ b/ontology/ontology.json @@ -27,6 +27,7 @@ "items": { "$ref": "#/$defs/Expression" }, + "uniqueItems": true, "description": "Expressions that constrain the population of this ontology" }, "ontology": { @@ -80,6 +81,7 @@ "type": "string", "minLength": 1 }, + "uniqueItems": true, "description": "Indicates that this concept extends one or more other concepts" }, "derived_by": { @@ -87,6 +89,7 @@ "items": { "$ref": "#/$defs/Expression" }, + "uniqueItems": true, "description": "Expressions that define how this concept is derived" }, "identify_by": { @@ -95,6 +98,7 @@ "type": "string", "minLength": 1 }, + "uniqueItems": true, "description": "Names of relationships to use as the preferred identifier of this concept" }, "requires": { @@ -102,6 +106,7 @@ "items": { "$ref": "#/$defs/Expression" }, + "uniqueItems": true, "description": "Expressions that constrain the population of this concept" }, "relationships": { @@ -153,6 +158,7 @@ "items": { "$ref": "#/$defs/Expression" }, + "uniqueItems": true, "description": "Expressions that define how this concept is derived" }, "requires": { @@ -160,6 +166,7 @@ "items": { "$ref": "#/$defs/Expression" }, + "uniqueItems": true, "description": "Expressions that constrain the population of this relationship" }, "verbalizes": { @@ -168,6 +175,7 @@ "type": "string", "minLength": 1 }, + "uniqueItems": true, "description": "Natural language expressions that verbalize this relationship" }, "iri": { diff --git a/ontology/ontology.md b/ontology/ontology.md index 82bb2aac..adbd42a5 100644 --- a/ontology/ontology.md +++ b/ontology/ontology.md @@ -88,11 +88,16 @@ A field described below as non-empty cannot be the empty string `""`. This appli string that names or references something, to IRIs, and to expressions. Descriptions are free text and may be empty. +A list whose entries are described below as listed once cannot repeat one. A supertype, an +identifying relationship, a constraint or a verbalization pattern given twice says nothing +the first one does not already say. + | Field | Type | Required | Description | |-------|------|----------|-------------| | `name` | string | Yes | Unique name of this specification; must be non-empty | | `description` | string | No | Human-readable description | | `ai_context` | string/object | No | Additional context for AI tools | +| `requires` | list | No | Expressions that constrain the population of this ontology; each must be non-empty and listed once | | `ontology` | list | Yes | Concepts and relationships they group that form this ontology | | `prefixes` | object | No | Namespace prefixes used to abbreviate [IRIs](#global-identifiers); each prefix's IRI must be non-empty | | `ontology_mappings` | list | No | Deprecated; accepted only so existing documents continue to validate. Write mappings as [mapping documents](#mapping-documents) instead | @@ -114,10 +119,10 @@ Concepts have the following schema: | `concept` | string | Yes | Unique name of this concept; must be non-empty | | `type` | ConceptType | Yes | Entity type or value type | | `description` | string | No | Human-readable description | -| `extends` | list | No | Names of this concept's supertypes; each must be non-empty | -| `derived_by` | list | No | Expressions that derive this concept's population; each must be non-empty | -| `identify_by` | list | No | Names of relationships that uniquely reference objects of this concept; each must be non-empty | -| `requires` | list | No | Expressions that constrain this concept's population; each must be non-empty | +| `extends` | list | No | Names of this concept's supertypes; each must be non-empty and listed once | +| `derived_by` | list | No | Expressions that derive this concept's population; each must be non-empty and listed once | +| `identify_by` | list | No | Names of relationships that uniquely reference objects of this concept; each must be non-empty and listed once | +| `requires` | list | No | Expressions that constrain this concept's population; each must be non-empty and listed once | | `relationships` | list | No | Relationships where this concept plays the first role | | `iri` | string | No | Optional [global identifier](#global-identifiers) of this concept; must be non-empty when present | @@ -161,9 +166,9 @@ Each relationship that is declared under a concept conforms to the following sch | `description` | string | No | Human-readable description | | `multiplicity` | enum | No | Multiplicity constraint | | `roles` | list | No | List of additional roles in this relationship | -| `derived_by` | list | No | Expressions that derive links of this relationship; each must be non-empty | -| `requires` | list | No | Expressions that constrain this relationship's population; each must be non-empty | -| `verbalizes` | list | Yes | Patterns describing how to verbalize links; each must be non-empty | +| `derived_by` | list | No | Expressions that derive links of this relationship; each must be non-empty and listed once | +| `requires` | list | No | Expressions that constrain this relationship's population; each must be non-empty and listed once | +| `verbalizes` | list | Yes | Patterns describing how to verbalize links; each must be non-empty and listed once | | `iri` | string | No | Optional [global identifier](#global-identifiers) of this relationship; must be non-empty when present | Each relationship is uniquely identified by prepending its declared name with that of the containing @@ -699,6 +704,8 @@ though `Store` plays a role in three of the relationships. - **0.3.0.dev0** (Unreleased; started as 0.2.0.dev0 on 2026-05-29): Basic support for ontologies and logical schema mappings - Breaking: each ontology map's `semantic_model` now requires its own `version`. - Breaking: names, IRIs, prefix IRIs and expressions can no longer be empty strings. + - Breaking: `extends`, `identify_by`, `verbalizes`, and `requires` and `derived_by` wherever + they appear, list each entry once; a repeated name or expression is no longer accepted. - Core ontology structure: Concepts, relationships, and business rules (requires and derived_by) - Schema mappings from one or more logical models into an ontology - Optional IRIs on concepts and relationships, with namespace prefixes declared at the top level diff --git a/python/src/ossie/models.py b/python/src/ossie/models.py index b22a8ba6..9d383eb8 100644 --- a/python/src/ossie/models.py +++ b/python/src/ossie/models.py @@ -23,6 +23,7 @@ import yaml from pydantic import ( + AfterValidator, BaseModel, ConfigDict, Field, @@ -339,6 +340,20 @@ class OssieMetric(BaseModel): nonportable_extensions: Optional[list[OssieNonportableExtension]] = None +def _distinct(names: list[str]) -> list[str]: + """Mirror the schema's `uniqueItems`, which `Field` cannot express. + + Names are compared as written, as the keyword does, so this serves one key: + `primary_key` and each definition inside `unique_keys`. + """ + seen: set[str] = set() + for name in names: + if name in seen: + raise ValueError(f"repeats {name!r}") + seen.add(name) + return names + + class OssieDataset(BaseModel): """Logical dataset representing a business entity (fact or dimension table).""" @@ -348,10 +363,16 @@ class OssieDataset(BaseModel): source: str = Field(..., min_length=1) # The schema gives both `minItems: 1`, as it does the relationship column arrays. # An empty key names nothing, and `Field` mirrors minItems as `min_length` here. - primary_key: Optional[list[str]] = Field(default=None, min_length=1) - unique_keys: Optional[list[Annotated[list[str], Field(min_length=1)]]] = Field( + # Each key is also `uniqueItems`: one that names a field twice declares fewer + # columns than it appears to. The list of definitions is not, since two holding + # the same key are redundant rather than wrong; validate.py warns about them, + # reordered and recased ones included, which a schema keyword cannot reach. + primary_key: Optional[Annotated[list[str], AfterValidator(_distinct)]] = Field( default=None, min_length=1 ) + unique_keys: Optional[ + list[Annotated[list[str], Field(min_length=1), AfterValidator(_distinct)]] + ] = Field(default=None, min_length=1) description: Optional[str] = None ai_context: Optional[OssieAIContext] = None fields: Optional[list[OssieField]] = None diff --git a/python/tests/test_models.py b/python/tests/test_models.py index fa79420f..0e0a5b85 100644 --- a/python/tests/test_models.py +++ b/python/tests/test_models.py @@ -642,6 +642,78 @@ def test_unique_key_definitions_may_not_be_empty() -> None: assert any(item["loc"] == ("unique_keys", 0) for item in error.value.errors()) +# One repeat per property the schema marks `uniqueItems`, so a keyword added to the +# schema without a matching model constraint fails the parity test below. +_REPEATED_CASES = { + ("Dataset", "primary_key"): lambda: OssieDataset( + name="orders", source="db.s.orders", primary_key=["order_id", "order_id"] + ), +} + + +def test_unique_items_parity_with_core_schema() -> None: + """The models must reject the repeats the schema rejects. + + Pydantic 2 dropped `unique_items`, so there is no `Field` keyword to compare + against the schema's; each property is exercised instead. + """ + schema_path = Path(__file__).parents[2] / "core-spec" / "ossie-schema.json" + schema = json.loads(schema_path.read_text()) + + checked = 0 + for node, model in _CONSTRAINED_NODES.items(): + for prop, prop_schema in schema["$defs"][node]["properties"].items(): + if not prop_schema.get("uniqueItems"): + continue + build = _REPEATED_CASES.get((node, prop)) + assert build is not None, ( + f"{node}.{prop} is uniqueItems in the schema with no case here" + ) + with pytest.raises(ValidationError) as error: + build() + assert any(item["loc"] == (prop,) for item in error.value.errors()) + checked += 1 + + # Guards against the loop silently checking nothing if the schema moves. + assert checked == 1 + + +def test_a_unique_key_definition_may_be_written_twice() -> None: + """`unique_keys` carries no `uniqueItems`, so the model does not reject one either. + + A definition written twice is redundant rather than wrong; validate.py warns + about it, where a rejection here would refuse to build the document at all. + """ + schema_path = Path(__file__).parents[2] / "core-spec" / "ossie-schema.json" + schema = json.loads(schema_path.read_text()) + unique_keys = schema["$defs"]["Dataset"]["properties"]["unique_keys"] + + assert "uniqueItems" not in unique_keys + + dataset = OssieDataset( + name="orders", source="db.s.orders", unique_keys=[["order_id"], ["order_id"]] + ) + + assert dataset.unique_keys == [["order_id"], ["order_id"]] + + +def test_a_unique_key_definition_may_not_repeat_a_field() -> None: + """The constraint nests, as the one on emptiness does. + + The field names inside one definition are a set too, and the parity test + above reads only the top level of each property. + """ + schema_path = Path(__file__).parents[2] / "core-spec" / "ossie-schema.json" + schema = json.loads(schema_path.read_text()) + unique_keys = schema["$defs"]["Dataset"]["properties"]["unique_keys"] + + assert unique_keys["items"]["uniqueItems"] is True + + with pytest.raises(ValidationError) as error: + OssieDataset(name="orders", source="db.s.orders", unique_keys=[["a", "a"]]) + assert any(item["loc"] == ("unique_keys", 0) for item in error.value.errors()) + + @pytest.mark.parametrize( ("build", "label"), [ diff --git a/validation/tests/test_ontology.py b/validation/tests/test_ontology.py index df13bb93..736a4cf9 100644 --- a/validation/tests/test_ontology.py +++ b/validation/tests/test_ontology.py @@ -408,6 +408,73 @@ def test_ontology_still_accepts_an_empty_description(ontology_validator): assert not _only_min_length_paths(ontology_validator, document) +def _only_unique_items_paths(validator, document) -> list[tuple]: + """Paths of the uniqueItems errors, so a case cannot pass on another error.""" + return [ + tuple(error.absolute_path) + for error in validator.iter_errors(document) + if error.validator == "uniqueItems" + ] + + +@pytest.mark.parametrize( + "mutate, path", + [ + (lambda d: d.update(requires=["1 = 1", "1 = 1"]), ("requires",)), + (lambda d: d["ontology"][0].update(extends=["Record", "Record"]), + ("ontology", 0, "extends")), + (lambda d: d["ontology"][0].update(derived_by=["1 = 1", "1 = 1"]), + ("ontology", 0, "derived_by")), + (lambda d: d["ontology"][0].update(identify_by=["order_id", "order_id"]), + ("ontology", 0, "identify_by")), + (lambda d: d["ontology"][0].update(requires=["1 = 1", "1 = 1"]), + ("ontology", 0, "requires")), + (lambda d: d["ontology"][0]["relationships"][0].update( + derived_by=["1 = 1", "1 = 1"]), + ("ontology", 0, "relationships", 0, "derived_by")), + (lambda d: d["ontology"][0]["relationships"][0].update( + requires=["1 = 1", "1 = 1"]), + ("ontology", 0, "relationships", 0, "requires")), + (lambda d: d["ontology"][0]["relationships"][0].update( + verbalizes=["{Order} is identified by {OrderId}"] * 2), + ("ontology", 0, "relationships", 0, "verbalizes")), + ], + ids=[ + "ontology-requires", + "extends", + "concept-derived_by", + "identify_by", + "concept-requires", + "relationship-derived_by", + "relationship-requires", + "verbalizes", + ], +) +def test_ontology_rejects_a_list_that_repeats_an_entry(ontology_validator, mutate, path): + """Each of these lists is a set. + + A second copy says nothing the first did not. + """ + document = _detailed_ontology() + assert not _only_unique_items_paths(ontology_validator, document) + + mutate(document) + + assert _only_unique_items_paths(ontology_validator, document) == [path] + + +def test_ontology_accepts_two_entries_that_differ_only_in_text(ontology_validator): + """The schema compares entries as written, not by what they mean. + + Two expressions that evaluate alike are still two entries, so this reaches + only the exact copies a producer emits by mistake. + """ + document = _detailed_ontology() + document["ontology"][0]["requires"] = ["1 = 1", "1 = 1 "] + + assert not _only_unique_items_paths(ontology_validator, document) + + def _mapping_with_nested_mappings() -> dict: document = _mapping_document() document["concept_mappings"] = [ diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index ec67f7b8..94dd20c7 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -39,6 +39,7 @@ _SPEC.loader.exec_module(_VALIDATE) validate_references = _VALIDATE.validate_references +validate_key_declarations = _VALIDATE.validate_key_declarations validate_relationship_column_arity = _VALIDATE.validate_relationship_column_arity @@ -186,6 +187,218 @@ def test_rejects_empty_root_datasets(core_schema: dict) -> None: assert errors == ["[Schema] datasets: [] should be non-empty"] +@pytest.mark.parametrize("keys, expected", [ + ({"primary_key": ["id", "id"]}, "primary_key: ['id', 'id']"), + ({"unique_keys": [["id", "id"]]}, "unique_keys -> 0: ['id', 'id']"), +], ids=["primary_key", "one key twice over a field"]) +def test_rejects_a_key_that_names_a_field_twice(core_schema: dict, keys, expected) -> None: + """A key is a set of fields: repeating one declares fewer columns than it looks like.""" + customers = {**_CUSTOMERS, **keys} + + errors = _VALIDATE.validate_schema(_document([_ORDERS, customers], []), core_schema) + + assert errors == [f"[Schema] datasets -> 1 -> {expected} has non-unique elements"] + + +def test_accepts_a_unique_key_definition_written_twice(core_schema: dict) -> None: + """The list of definitions carries no `uniqueItems`, deliberately. + + A definition written twice states nothing untrue, and a schema error stops + the semantic checks, so the author would lose every reference and SQL + diagnostic over a redundancy. validate_key_declarations warns instead; this + asserts that hand-off rather than assuming it. + """ + customers = {**_CUSTOMERS, "unique_keys": [["email"], ["email"]]} + document = _document([_ORDERS, customers], []) + + assert _VALIDATE.validate_schema(document, core_schema) == [] + + errors = validate_key_declarations(document) + assert errors == [ + "[Unique] Warning: Dataset 'customers' in model 'm': unique_keys " + "['email'] declares the same key as unique_keys ['email']" + ] + assert all(isinstance(error, _VALIDATE.ValidationWarning) for error in errors) + + +def test_accepts_a_relationship_column_named_twice(core_schema: dict) -> None: + """from_columns and to_columns correspond positionally, not as sets. + + One column of the from dataset may be compared with two columns of the to + dataset, so neither array is constrained the way a key is. + """ + relationship = { + "name": "orders_to_customers", + "from": "orders", + "to": "customers", + "from_columns": ["customer_id", "customer_id"], + "to_columns": ["id", "tenant_id"], + } + + document = _document([_ORDERS, _CUSTOMERS], [relationship]) + + assert _VALIDATE.validate_schema(document, core_schema) == [] + + +def _keyed(**keys) -> dict: + """The customers dataset with its key declarations replaced.""" + return {**_CUSTOMERS, **keys} + + +def _declaring(*names: str) -> dict: + """A customers dataset declaring exactly the fields named, in that order.""" + return {**_CUSTOMERS, "fields": [_field(name) for name in names]} + + +@pytest.mark.parametrize("keys, expected", [ + ({"primary_key": ["id", "ID"]}, "primary_key names field 'id' more than once"), + ({"unique_keys": [["email", "EMAIL"]]}, + "unique_keys ['email', 'EMAIL'] names field 'email' more than once"), +], ids=["primary_key", "unique key"]) +def test_rejects_a_key_that_names_one_field_under_two_spellings(keys, expected) -> None: + """Key field names resolve case-insensitively, so these claim a column they lack. + + The schema's `uniqueItems` compares the strings, so only this check sees it. + """ + errors = validate_key_declarations(_document([_ORDERS, _keyed(**keys)], [])) + + assert errors == [f"[Unique] Dataset 'customers' in model 'm': {expected}"] + + +@pytest.mark.parametrize("declared, named", [ + (["ID"], "ID"), + (["Id"], "Id"), +], ids=["upper", "mixed"]) +def test_a_repeated_key_entry_is_reported_as_the_field_it_resolves_to(declared, named): + """Either spelling in the key folds onto the one the dataset declares.""" + dataset = {**_declaring(*declared), "primary_key": ["id", "ID"], "unique_keys": None} + + errors = validate_key_declarations(_document([_ORDERS, dataset], [])) + + assert errors == [ + f"[Unique] Dataset 'customers' in model 'm': primary_key names field " + f"'{named}' more than once" + ] + + +@pytest.mark.parametrize("keys, expected", [ + ({"primary_key": ["id", "ID"]}, + "primary_key names field 'id' more than once"), + ({"primary_key": ["ID", "Id"]}, + "primary_key names field 'id' more than once"), + ({"primary_key": ["id"], "unique_keys": [["ID"], ["Id"]]}, + "unique_keys ['Id'] declares the same key as unique_keys ['ID']"), +], ids=["both spellings", "neither spelling declared first", "a key for each"]) +def test_a_dataset_declaring_a_name_twice_in_two_cases_has_one_field(keys, expected): + """Regular identifiers are case insensitive (expression_language.md), so + `id`, `ID` and `Id` are one field however the dataset spells them. + + validate_unique_names compares field names as written and so does not report + the duplicate declaration, but that gap does not make these two fields: the + first declared is the one everything resolves to, per validate_field_shadowing. + """ + dataset = {**_declaring("id", "ID"), "primary_key": None, "unique_keys": None, **keys} + + errors = validate_key_declarations(_document([_ORDERS, dataset], [])) + + assert [error.removeprefix("[Unique] ").removeprefix("Warning: ") for error in errors] == [ + f"Dataset 'customers' in model 'm': {expected}" + ] + + +@pytest.mark.parametrize("keys", [ + {"primary_key": ["ghost", "GHOST"]}, + {"unique_keys": [["ghost"], ["GHOST"]]}, +], ids=["one key", "a key for each"]) +def test_says_nothing_about_a_key_entry_that_names_no_declared_field(keys) -> None: + """An undeclared entry names no field, so calling it a repeat of another + entry would name a field the dataset does not have. + + validate_references is what reports it, which the assertion below checks + rather than assumes. + """ + dataset = {**_declaring("id"), "primary_key": None, "unique_keys": None, **keys} + document = _document([_ORDERS, dataset], []) + + assert validate_key_declarations(document) == [] + assert any("undeclared field 'ghost'" in error for error in validate_references(document)) + + +def test_reports_a_repeated_entry_alongside_an_empty_one() -> None: + """An empty entry is validate_references' to report, and is dropped here. + + Dropping it rather than skipping the declaration keeps the entries around it + compared, so one malformed key does not hide the other problem in it. + """ + dataset = {**_declaring("id"), "primary_key": ["id", "ID", ""], "unique_keys": None} + document = _document([_ORDERS, dataset], []) + + assert validate_key_declarations(document) == [ + "[Unique] Dataset 'customers' in model 'm': primary_key names field " + "'id' more than once" + ] + assert any("undeclared field ''" in error for error in validate_references(document)) + + +@pytest.mark.parametrize("unique_keys, repeat, first", [ + ([["id", "email"], ["email", "id"]], "['email', 'id']", "['id', 'email']"), + ([["email"], ["EMAIL"]], "['EMAIL']", "['email']"), +], ids=["reordered", "recased"]) +def test_warns_when_two_unique_keys_hold_the_same_fields(unique_keys, repeat, first) -> None: + """A key is a set, so neither order nor case makes a second declaration a new key.""" + errors = validate_key_declarations( + _document([_ORDERS, _keyed(unique_keys=unique_keys)], []) + ) + + assert errors == [ + f"[Unique] Warning: Dataset 'customers' in model 'm': unique_keys {repeat} " + f"declares the same key as unique_keys {first}" + ] + assert all(isinstance(error, _VALIDATE.ValidationWarning) for error in errors) + + +def test_warns_when_a_yaml_alias_declares_a_unique_key_twice() -> None: + """An alias makes one list object the value of two definitions. + + Definitions are compared by position rather than by identity, so the second + is reported even though it is the first one over again. + """ + document = _document( + [_ORDERS, _keyed(unique_keys=yaml.safe_load("[&k [email], *k]"))], [] + ) + declared = document["datasets"][1]["unique_keys"] + assert declared[0] is declared[1] # the alias survives _document's deep copy + + assert validate_key_declarations(document) == [ + "[Unique] Warning: Dataset 'customers' in model 'm': unique_keys " + "['email'] declares the same key as unique_keys ['email']" + ] + + +@pytest.mark.parametrize("keys", [ + {"unique_keys": [["id"]]}, + {"primary_key": ["id", "email"], "unique_keys": [["email", "id"]]}, +], ids=["single column", "composite reordered"]) +def test_accepts_a_unique_key_that_restates_the_primary_key(keys) -> None: + """DDL commonly declares both, and examples/tpcds_semantic_model.yaml does so + in five datasets, so this is not reported. + """ + assert validate_key_declarations(_document([_ORDERS, _keyed(**keys)], [])) == [] + + +@pytest.mark.parametrize("unique_keys", [ + [["email"], ["region"]], + [["email"], ["email", "region"]], +], ids=["disjoint", "one a superset of the other"]) +def test_accepts_unique_keys_that_hold_different_fields(unique_keys) -> None: + """Only set equality is a repeat; a key that merely contains another is its own.""" + errors = validate_key_declarations( + _document([_ORDERS, _keyed(unique_keys=unique_keys)], []) + ) + + assert errors == [] + + def test_semantic_model_definition_does_not_require_document_version(core_schema: dict) -> None: # The reusable contents definition remains independent of document metadata. embedded_schema = { diff --git a/validation/validate.py b/validation/validate.py index f1cdd55b..a6f5b41a 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -34,7 +34,7 @@ nonportable_extensions data is a JSON value (dates, timestamps, and non-finite floats are rejected; the schema types data as object and does not look inside, and portable checks do not read the payload) -2. Unique names (datasets, fields, metrics, relationships) +2. Unique names (datasets, fields, metrics, relationships) and key declarations 3. Valid relationship references 4. Relationship column arity (from_columns and to_columns lengths match) 5. SQL syntax (using sqlglot) @@ -647,6 +647,122 @@ def validate_unique_names(data: dict) -> list[str]: return errors +def _field_by_fold(dataset: dict) -> dict[str, str]: + """The name each of a dataset's fields is known by, keyed by case-folded form. + + Regular identifiers are case insensitive (expression_language.md), so two + field names differing only in case name one field, and + validate_field_shadowing compares other expressions against the first + declared of them. That first spelling is what a key entry names. + """ + by_fold: dict[str, str] = {} + for field in as_list(dataset.get("fields")): + if not isinstance(field, dict): + continue + name = field.get("name") + if isinstance(name, str) and name: + by_fold.setdefault(name.casefold(), name) + return by_fold + + +def _key_identities(key: object, fields: dict[str, str]) -> list[str | None] | None: + """The field each entry of a key declaration names, or None if it names none. + + None for the whole key when an entry is not a string, which already failed + schema validation. The empty string passes schema validation, since key items + carry no minLength; it is dropped so the entries around it are still + compared, and validate_references reports it as naming no declared field. + + Every other entry names the field its case-folded form does, since + identifiers are case insensitive, or None when the dataset declares no such + field. An undeclared entry names nothing to compare and validate_references + reports it, so claiming it repeats another entry would name a field the + dataset does not have. + """ + if not isinstance(key, list) or not key: + return None + if any(not isinstance(name, str) for name in key): + return None + + return [fields.get(name.casefold()) for name in key if name] + + +def validate_key_declarations(data: dict) -> list[str]: + """Validate that a key names distinct fields and that none is declared twice. + + A key is a set of fields, and an entry names one case-insensitively, so the + schema's `uniqueItems` on a key reaches only an entry repeated verbatim. A + key that names one field twice claims a column it does not have, which is an + error here as it is there. + + Two unique_keys definitions holding the same set of fields are one key + written twice. That is redundant rather than wrong, so it is a warning, and + the list of definitions carries no `uniqueItems`: a schema error would stop + the semantic checks, and the author would lose every reference and SQL + diagnostic over a document that states nothing untrue. Reordered, recased + and verbatim repeats are all reported here, by the fields they name. + + A unique key that restates the primary key is left alone. It carries nothing + new, but DDL commonly declares both and examples/tpcds_semantic_model.yaml + mirrors that in five of its datasets. + + A dataset that declares two field names differing only in case declares one + field twice, since identifiers are case insensitive, and a key naming both + spellings names that field twice. validate_unique_names compares field names + as written and so does not report the declaration itself; that gap is not + this check's to close, and it does not make the key's two entries two fields. + """ + if not isinstance(data, dict) or "datasets" not in data: + return [] + + model = data + errors = [] + + model_name = model.get("name", "") + + for dataset in as_list(model.get("datasets")): + if not isinstance(dataset, dict): + continue + prefix = f"Dataset '{dataset.get('name', '')}' in model '{model_name}'" + fields = _field_by_fold(dataset) + unique_keys = as_list(dataset.get("unique_keys")) + + for name, key in [("primary_key", dataset.get("primary_key"))] + [ + ("unique_keys", k) for k in unique_keys + ]: + identities = _key_identities(key, fields) + if identities is None: + continue + label = name if name == "primary_key" else f"unique_keys {key}" + for field in find_duplicates([i for i in identities if i is not None]): + errors.append( + f"[Unique] {prefix}: {label} names field '{field}' more than once" + ) + + first_seen: dict[frozenset[str], int] = {} + for position, key in enumerate(unique_keys): + identities = _key_identities(key, fields) + # Compare only a key whose every entry names a declared field. An + # empty or undeclared entry is reported by validate_references, and a + # key already holding one field twice is reported above; letting + # either stand in would compare a key the document does not declare. + if identities is None or len(identities) != len(key): + continue + if None in identities or find_duplicates(identities): + continue + # Compared by position rather than by identity, since a YAML alias + # makes one list object the value of two definitions, and those two + # are still a key written twice. + earlier = first_seen.setdefault(frozenset(identities), position) + if earlier != position: # another definition held this set first + errors.append(ValidationWarning( + f"[Unique] Warning: {prefix}: unique_keys {key} declares the " + f"same key as unique_keys {unique_keys[earlier]}" + )) + + return errors + + def validate_references(data: dict) -> list[str]: """Validate relationship and key names against declared fields. @@ -1944,6 +2060,7 @@ def validate_semantic_model(data: dict) -> list[str]: return [] errors = [] errors.extend(validate_unique_names(data)) + errors.extend(validate_key_declarations(data)) errors.extend(validate_references(data)) errors.extend(validate_relationship_column_arity(data)) errors.extend(validate_metric_references(data)) From 24c5bf53e9c619f9541e7e62ad7aa1e0c5314c04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?JB=20Onofr=C3=A9?= Date: Fri, 13 Nov 2026 11:01:30 +0100 Subject: [PATCH 2/2] docs(core-spec): cite the identifier case rule for keys and set the merge date The key paragraph cited Name Resolution for case-insensitive field names, but that section says nothing about case. The rule lives in expression_language.md and covers unquoted identifiers only, since quoted ones match exactly. The spec_changes.md row records the merge date, so it now carries today's date rather than the date the change was written. --- core-spec/spec.md | 7 ++++--- docs/spec_changes.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/core-spec/spec.md b/core-spec/spec.md index 51d404f7..0d7d52a1 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -195,9 +195,10 @@ unique_keys: - [first_name, last_name] # Composite unique key ``` -A key is the set of fields it names, so it names each of them once. Field names -resolve case-insensitively (see [Name Resolution](#name-resolution)), so -`[email, EMAIL]` names one field twice and is invalid. Two `unique_keys` +A key is the set of fields it names, so it names each of them once. Unquoted +field names resolve case-insensitively (see +[Namespacing and Identifier Resolution](expression_language.md#namespacing-and-identifier-resolution)), +so `[email, EMAIL]` names one field twice and is invalid. Two `unique_keys` definitions that name the same fields, in any order and in any case, declare one key twice; that is redundant rather than invalid, and validation reports it as a warning. diff --git a/docs/spec_changes.md b/docs/spec_changes.md index 9e6ef554..6aec4c05 100644 --- a/docs/spec_changes.md +++ b/docs/spec_changes.md @@ -56,7 +56,7 @@ 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-11 | 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-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. | ## Semi-automated discovery and upkeep