From d6267efd6a1d73fa764925e92bd8de9849db3309 Mon Sep 17 00:00:00 2001 From: Chris Eubank <108756251+christianeu-db@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:22:56 +0000 Subject: [PATCH] feat(core-spec): make relationship cardinality explicit A relationship may declare `cardinality`: ManyToOne, OneToMany, or OneToOne, stated from `from` to `to`. An absent value means ManyToOne, so existing documents keep their meaning. There is no many-to-many value. Layer 2 semantics are unchanged; its mapping text now maps `cardinality`. Layer 3 paths follow every step that does not increase granularity: from `from` to `to` for ManyToOne and OneToOne, and from `to` to `from` for OneToMany and OneToOne. Filter propagation stays out of scope. The validator checks key coverage on each one side of the cardinality. The schema, spec.yaml, the spec type generator, and the Python SDK gain the Cardinality enum. Discussion: https://lists.apache.org/thread/1kggjhy5tjqjyvlf6rsvs9ygxt6x9zkr Co-authored-by: Isaac --- core-spec/ossie-schema.json | 22 +++-- core-spec/relational_semantics.md | 12 +-- core-spec/spec.md | 24 ++++-- core-spec/spec.yaml | 27 ++++-- core-spec/wide_table_semantics.md | 4 +- docs/index.md | 4 +- docs/spec_changes.md | 1 + python/src/ossie/__init__.py | 2 + python/src/ossie/models.py | 12 ++- python/tests/test_models.py | 49 +++++++++++ python/tests/test_serialization.py | 1 + scripts/generate-spec-types.py | 11 +++ validation/tests/test_generate_spec_types.py | 19 +++-- validation/tests/test_validate.py | 54 ++++++++++++ validation/validate.py | 88 +++++++++++--------- 15 files changed, 253 insertions(+), 77 deletions(-) diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index 8c9b93403..023bac615 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -266,9 +266,18 @@ "required": ["name", "source"], "additionalProperties": false }, + "Cardinality": { + "type": "string", + "enum": [ + "ManyToOne", + "OneToOne", + "OneToMany" + ], + "description": "Relationship cardinality, from `from` to `to`. `ManyToOne`: each `from` row matches at most one `to` row. `OneToMany`: each `to` row matches at most one `from` row. `OneToOne`: both. Absent means `ManyToOne`." + }, "Relationship": { "type": "object", - "description": "Foreign key relationship between datasets", + "description": "Equality conditions between the fields of two datasets", "properties": { "name": { "type": "string", @@ -278,12 +287,12 @@ "from": { "type": "string", "minLength": 1, - "description": "Dataset on the many side of the relationship" + "description": "Dataset containing from_columns" }, "to": { "type": "string", "minLength": 1, - "description": "Dataset on the one side of the relationship" + "description": "Dataset containing to_columns" }, "from_columns": { "type": "array", @@ -291,7 +300,7 @@ "type": "string" }, "minItems": 1, - "description": "Array of field names in the 'from' dataset (foreign key fields)" + "description": "Array of field names in the 'from' dataset" }, "to_columns": { "type": "array", @@ -299,7 +308,10 @@ "type": "string" }, "minItems": 1, - "description": "Array of field names in the 'to' dataset (primary or unique key fields)" + "description": "Array of field names in the 'to' dataset" + }, + "cardinality": { + "$ref": "#/$defs/Cardinality" }, "ai_context": { "$ref": "#/$defs/AIContext" diff --git a/core-spec/relational_semantics.md b/core-spec/relational_semantics.md index 3902fb635..c54b26ff4 100644 --- a/core-spec/relational_semantics.md +++ b/core-spec/relational_semantics.md @@ -246,7 +246,7 @@ SQL-native names. The correspondence: | 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`) | 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`. | +| join relationship (Section 11.3) | `relationship` (`from`/`to`, `from_columns`/`to_columns`) | `from`/`to` map to source/target, the columns to the join predicate, and `cardinality` to the cardinality (`MANY_TO_ONE` if absent); Section 11.3 adds 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). | Ossie model metadata this interface does not natively surface (`ai_context`, `nonportable_extensions`, @@ -956,11 +956,11 @@ ALTER VIEW model.flights ``` An Ossie `relationship` maps onto the equi-join baseline: its `from`/`to` datasets are the -source and target and its `from_columns`/`to_columns` the joined column pairs (`from` the many -side, `to` the one), which round-trips between this interface and the Ossie model. The richer -elements above (explicit cardinality, semantic roles, and arbitrary boolean `ON` predicates) -have no home in current Ossie relationship metadata and do not round-trip without a future Ossie -schema extension (Section 13.2). +source and target, its `from_columns`/`to_columns` the joined column pairs, and its +`cardinality` the cardinality (`MANY_TO_ONE` if absent), which round-trips between this +interface and the Ossie model. The richer elements above (`MANY_TO_MANY`, semantic roles, and +arbitrary boolean `ON` predicates) have no home in current Ossie relationship metadata and do +not round-trip without a future Ossie schema extension (Section 13.2). **Using a relationship.** A tool reads the relationships on a relation, selects the one that fits the analysis, and generates the join from its predicate. The relationship fixes the diff --git a/core-spec/spec.md b/core-spec/spec.md index cefe33b69..cb3a7635b 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -235,17 +235,18 @@ datasets: ## Relationships -Relationships define how logical datasets are connected through foreign key constraints. They support both simple and composite keys. +Relationships connect logical datasets through equality conditions between their fields. They support simple and composite keys. ### Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `name` | string | Yes | Unique identifier for the relationship | -| `from` | string | Yes | The logical dataset on the many side of the relationship | -| `to` | string | Yes | The logical dataset on the one side of the relationship | -| `from_columns` | array | Yes | Array of field names in the "from" dataset (foreign key fields) | -| `to_columns` | array | Yes | Array of field names in the "to" dataset (primary or unique key fields) | +| `from` | string | Yes | The logical dataset containing `from_columns` | +| `to` | string | Yes | The logical dataset containing `to_columns` | +| `from_columns` | array | Yes | Array of field names in the "from" dataset | +| `to_columns` | array | Yes | Array of field names in the "to" dataset | +| `cardinality` | string (enum) | No | `ManyToOne`, `OneToMany`, or `OneToOne`. See [Cardinality](#cardinality). | | `ai_context` | string/object | No | Additional context for AI tools | | `nonportable_extensions` | array | No | Vendor-specific attributes | @@ -257,6 +258,18 @@ Relationships define how logical datasets are connected through foreign key cons - For simple relationships, use a single field: `[field1]` - For composite relationships, use multiple fields: `[field1, field2]` +### Cardinality + +`cardinality` describes the maximum number of matching rows on each side of a relationship: + +| Value | Meaning | +|-------|---------| +| `ManyToOne` | Each `from` row matches at most one `to` row. | +| `OneToMany` | Each `to` row matches at most one `from` row. | +| `OneToOne` | Both conditions hold. | + +The default is `ManyToOne`. Cardinality is informational and does not imply referential integrity, join type, or filter propagation. Many-to-many cardinality is unsupported. + ### Examples **Simple Relationship:** @@ -939,6 +952,7 @@ including rationale and migration impact for consumers, see the - 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). + - Relationships may declare `cardinality`: `ManyToOne` (the default), `OneToMany`, or `OneToOne`. Consumers that assume that `from` is the many side must read it. See [Cardinality](#cardinality). - **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 edf973c5f..534f23b57 100644 --- a/core-spec/spec.yaml +++ b/core-spec/spec.yaml @@ -45,6 +45,13 @@ datatypes: - "DateTimeTz" # Instant identified using offset or timezone context - "Opaque" # Known type outside the portable vocabulary +# Supported relationship cardinalities, stated from `from` to `to` +# Auto-generated from ossie-schema.json ($defs.Cardinality.enum). +cardinalities: + - "ManyToOne" # Each from row matches at most one to row (default) + - "OneToOne" # Each row matches at most one row on the other side + - "OneToMany" # Each to row matches at most one from row + # Vendor name for non-portable extensions (free-form string). # See the known-vendor catalog in extensions/vendors.md. vendor_name: string @@ -107,7 +114,7 @@ datasets: # Optional: Dataset fields that uniquely identify rows # These are fields declared in the dataset, not columns of its source # Can be a single field or a composite of multiple fields - # This is the preferred unique identifier for this dataset and is used in relationships to determine many-to-one or one-to-one. + # This is the preferred unique identifier for this dataset. # Examples: # primary_key: [customer_id] # Simple primary key # @@ -117,7 +124,6 @@ datasets: # Optional: Array of unique key definitions, each a list of dataset fields # These are fields declared in the dataset, not columns of its source # Each unique key can be a single field or a composite of multiple fields - # Used for determining relationship type of either many-to-one or one-to-one # Examples: # unique_keys: # - [field1] @@ -177,30 +183,30 @@ datasets: --- # Relationship Schema # Defines how logical datasets within this model are connected -# Represents foreign key relationships (many-to-one or one-to-one) +# Represents equality relationships (many-to-one, one-to-many, or one-to-one) relationships: # Required: Unique identifier for the relationship - name: string - # Required: The logical dataset on the many side of the relationship + # Required: The logical dataset containing from_columns # References a logical dataset name from: string - # Required: The logical dataset on the one side of the relationship + # Required: The logical dataset containing to_columns # References a logical dataset name to: string - # Required: Array of field names in the "from" dataset (foreign key fields) + # Required: Array of field names in the "from" dataset # These are fields declared in the dataset, not columns of its source # For simple relationships, use a single field: [field1] # For composite relationships, use multiple fields: [field1, field2] # The order of fields must correspond to the order in to_columns # Examples: - # - [customer_id] # Simple foreign key - # - [order_id, line_number] # Composite foreign key + # - [customer_id] # Simple key + # - [order_id, line_number] # Composite key from_columns: [] # Array of field names - # Required: Array of field names in the "to" dataset (primary or unique key fields) + # Required: Array of field names in the "to" dataset # These are fields declared in the dataset, not columns of its source # Must have the same number of fields as from_columns in corresponding order # Examples: @@ -208,6 +214,9 @@ relationships: # - [order_id, line_number] # Composite key to_columns: [] # Array of field names + # Optional: One of the 'cardinalities' enum above; omitted means ManyToOne + cardinality: string + # Optional: Additional context for AI tools (e.g., synonyms, business context) # Helps LLMs understand when and why the datasets should be joined ai_context: {} # see AIContext in ossie-schema.json diff --git a/core-spec/wide_table_semantics.md b/core-spec/wide_table_semantics.md index 98aa3d2c5..5962fc1b2 100644 --- a/core-spec/wide_table_semantics.md +++ b/core-spec/wide_table_semantics.md @@ -197,9 +197,9 @@ The binding identifies the model and reports the errors of Section 8. ## 4. Paths -The **relationship graph** contains one node per dataset and one edge per relationship. Each relationship equates its `from_columns` with its `to_columns`; `from` is the many side and `to` the one side (core specification, Relationships). This many-to-one direction is the relationship's **declared cardinality**; the data need not satisfy it (Layer 2 Section 11.3). +The **relationship graph** contains one node per dataset and one edge per relationship. Each relationship equates its `from_columns` with its `to_columns`. Its `cardinality` is its **declared cardinality** (core specification, Relationships); the data need not satisfy it (Layer 2 Section 11.3). -- A **step** crosses a relationship from `from` to `to`. If the data satisfies the declared cardinality, a step matches at most one `to` row for each `from` row. +- A **step** crosses a relationship from `from` to `to` if its declared cardinality is `ManyToOne` or `OneToOne`, and from `to` to `from` if it is `OneToMany` or `OneToOne`. If the data satisfies the declared cardinality, a step matches at most one row where it ends for each row where it starts. - A **path** from dataset X to dataset Y is a sequence of steps from X to Y with no repeated dataset. The path from a dataset to itself is empty. Y is **reachable** from X if such a path exists. - The lowering joins Y to X along the path from X to Y. If two or more paths lead from X to Y, the engine MUST raise [`E_AMBIGUOUS_PATH`](#8-errors), even if one path is shorter. For example, if `store` relates to `date_dim` through its closing date, the sale date and the closing date give two paths from `store_sales` to `date_dim` (Appendix B.3). diff --git a/docs/index.md b/docs/index.md index ec0436f2b..c79933496 100644 --- a/docs/index.md +++ b/docs/index.md @@ -54,7 +54,7 @@ The Ossie core specification (current version: **0.3.0.dev0**, latest released: | **Semantic Model** | The top-level container representing a complete semantic model, including datasets, relationships, and metrics. | | **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. | +| **Relationships** | Equality conditions between the fields of two datasets, supporting both simple and composite keys, with an optional cardinality. | | **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. | @@ -308,7 +308,7 @@ A practical guide for organizations looking to adopt Ossie. | **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'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). | +| **Relationship** | Equality conditions between the fields of two datasets, defining how they can be joined. Its optional `cardinality` is `ManyToOne` (the default), `OneToMany`, or `OneToOne`. | | **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. | | **AI Context** | Optional annotations on any Ossie construct (model, dataset, field, relationship, metric) that provide additional context for AI tools — including natural language instructions, synonyms, and example queries. | diff --git a/docs/spec_changes.md b/docs/spec_changes.md index fc0a5f5cb..1f7f481cf 100644 --- a/docs/spec_changes.md +++ b/docs/spec_changes.md @@ -59,6 +59,7 @@ the [current core specification](../core-spec/spec.md) and | 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. | +| 2026-11-28 | Core / Wide table interface [#794](https://github.com/apache/ossie/pull/794) | **Explicit relationship `cardinality`.** A relationship may declare `ManyToOne`, `OneToMany`, or `OneToOne`, so converters can keep a source tool's cardinality ([dev@ discussion](https://lists.apache.org/thread/1kggjhy5tjqjyvlf6rsvs9ygxt6x9zkr)). Layer 3 paths follow every step that does not increase granularity. | Additive: absent means `ManyToOne`, so existing documents keep their meaning and their Layer 3 results. Consumers that assume that `from` is the many side must read `cardinality`. Layer 2 semantics are unchanged. See [cardinality](../core-spec/spec.md#cardinality). | ## Semi-automated discovery and upkeep diff --git a/python/src/ossie/__init__.py b/python/src/ossie/__init__.py index 740038511..3d396ed71 100644 --- a/python/src/ossie/__init__.py +++ b/python/src/ossie/__init__.py @@ -25,6 +25,7 @@ from ossie.models import ( OssieAIContext, OssieAIContextObject, + OssieCardinality, OssieNonportableExtension, OssieDataset, OssieDataType, @@ -43,6 +44,7 @@ __all__ = [ "OssieAIContext", "OssieAIContextObject", + "OssieCardinality", "OssieNonportableExtension", "OssieDataset", "OssieDataType", diff --git a/python/src/ossie/models.py b/python/src/ossie/models.py index 83e9f1048..05390d909 100644 --- a/python/src/ossie/models.py +++ b/python/src/ossie/models.py @@ -203,6 +203,14 @@ class OssieDataType(str, Enum): ) +class OssieCardinality(str, Enum): + """Relationship cardinality, from `from` to `to`; absent means `MANY_TO_ONE`.""" + + MANY_TO_ONE = "ManyToOne" + ONE_TO_ONE = "OneToOne" + ONE_TO_MANY = "OneToMany" + + class OssieVendor(str, Enum): """Well-known vendor values. The field accepts any string; see `extensions/vendors.md`.""" @@ -383,7 +391,7 @@ class OssieDataset(BaseModel): class OssieRelationship(BaseModel): - """Foreign key relationship between datasets.""" + """Equality conditions between the fields of two datasets.""" model_config = ConfigDict(frozen=True, extra="forbid", populate_by_name=True) @@ -392,6 +400,8 @@ class OssieRelationship(BaseModel): to: str = Field(..., min_length=1) from_columns: list[str] = Field(..., min_length=1) to_columns: list[str] = Field(..., min_length=1) + # None when omitted, so a round trip does not add the key. None means MANY_TO_ONE. + cardinality: Optional[OssieCardinality] = None ai_context: Optional[OssieAIContext] = None nonportable_extensions: Optional[list[OssieNonportableExtension]] = None diff --git a/python/tests/test_models.py b/python/tests/test_models.py index 0e0a5b85b..4b3672a9e 100644 --- a/python/tests/test_models.py +++ b/python/tests/test_models.py @@ -26,6 +26,7 @@ from ossie import ( OssieAIContextObject, + OssieCardinality, OssieNonportableExtension, OssieDataset, OssieDataType, @@ -444,6 +445,54 @@ def test_relationship_rejects_unknown_fields(document_data: dict) -> None: ) +def test_cardinality_enum_matches_core_schema() -> None: + schema = json.loads((Path(__file__).parents[2] / "core-spec" / "ossie-schema.json").read_text()) + + assert [member.value for member in OssieCardinality] == schema["$defs"]["Cardinality"]["enum"] + assert schema["$defs"]["Relationship"]["properties"]["cardinality"] == {"$ref": "#/$defs/Cardinality"} + + +@pytest.mark.parametrize( + "cardinality", [None, *OssieCardinality], ids=lambda c: "absent" if c is None else c.value +) +def test_relationship_cardinality_round_trips( + document_data: dict, cardinality: OssieCardinality | None +) -> None: + relationship = { + "name": "r", + "from": "events", + "to": "events", + "from_columns": ["occurred_at"], + "to_columns": ["occurred_at"], + } + if cardinality is not None: + relationship["cardinality"] = cardinality.value + document_data["relationships"] = [relationship] + document = OssieDocument.model_validate(document_data) + + assert document.relationships[0].cardinality is cardinality + assert json.loads(document.to_ossie_json())["relationships"][0] == relationship + assert yaml.safe_load(document.to_ossie_yaml())["relationships"][0] == relationship + + +def test_unknown_cardinality_is_rejected(document_data: dict) -> None: + document_data["relationships"] = [ + { + "name": "r", + "from": "events", + "to": "events", + "from_columns": ["occurred_at"], + "to_columns": ["occurred_at"], + "cardinality": "ManyToMany", + } + ] + + with pytest.raises(ValidationError) as error: + OssieDocument.model_validate(document_data) + + assert any(item["loc"] == ("relationships", 0, "cardinality") for item in error.value.errors()) + + def test_nonportable_extension_rejects_unknown_fields(document_data: dict) -> None: document_data["nonportable_extensions"] = [ {"vendor_name": "DBT", "data": {}, "datta": "typo"} diff --git a/python/tests/test_serialization.py b/python/tests/test_serialization.py index 567eddaa2..9fc287a7a 100644 --- a/python/tests/test_serialization.py +++ b/python/tests/test_serialization.py @@ -369,6 +369,7 @@ def _fully_populated_document() -> dict: "to": "orders", "from_columns": ["id"], "to_columns": ["id"], + "cardinality": "OneToOne", "ai_context": dict(ai_context), "nonportable_extensions": list(extensions), } diff --git a/scripts/generate-spec-types.py b/scripts/generate-spec-types.py index 6c3f4e2fe..ce6784750 100755 --- a/scripts/generate-spec-types.py +++ b/scripts/generate-spec-types.py @@ -68,6 +68,17 @@ "Opaque": "Known type outside the portable vocabulary", }, }, + { + "key": "cardinalities", + "schema_path": ["$defs", "Cardinality", "enum"], + "comment_col": 28, + "header": "# Supported relationship cardinalities, stated from `from` to `to`", + "descriptions": { + "ManyToOne": "Each from row matches at most one to row (default)", + "OneToOne": "Each row matches at most one row on the other side", + "OneToMany": "Each to row matches at most one from row", + }, + }, ] diff --git a/validation/tests/test_generate_spec_types.py b/validation/tests/test_generate_spec_types.py index 19bdad633..8d6b94ced 100644 --- a/validation/tests/test_generate_spec_types.py +++ b/validation/tests/test_generate_spec_types.py @@ -32,7 +32,7 @@ """ -# `datatypes` is the one managed section: generate-spec-types.py syncs it from +# These tests exercise `datatypes`, which generate-spec-types.py syncs from # ossie-schema.json ($defs.DataType.enum). `dialects` is intentionally NOT # generated -- `dialect` is a free-form string -- so it appears below only as an # unmanaged, hand-authored section the generator must leave untouched. @@ -59,7 +59,10 @@ def generator(): return module -def _write_spec(tmp_path: Path, text: str) -> Path: +def _write_spec(tmp_path: Path, text: str, generator) -> Path: + # The generator needs every managed section, so append the others in sync. + for section in generator.SECTIONS[1:]: + text += generator._generate_block(section, generator._schema_values(section)) path = tmp_path / "spec.yaml" path.write_text(text) return path @@ -72,7 +75,7 @@ def test_apply_keeps_hand_written_comments_above_a_section(generator, monkeypatc not the hand-written comments above them, so the enumerations preamble survives and --check still reports the file as in sync. """ - path = _write_spec(tmp_path, _SPEC_HEAD.rstrip("\n") + "\n" + _DATATYPES) + path = _write_spec(tmp_path, _SPEC_HEAD.rstrip("\n") + "\n" + _DATATYPES, generator) monkeypatch.setattr(generator, "SPEC", path) generator._apply() @@ -105,7 +108,7 @@ def test_apply_rewrites_a_section_however_its_header_survives( copy above the key, which `--check` then accepts. """ spec = _SPEC_HEAD + above_key + 'datatypes:\n - "String"\n' - path = _write_spec(tmp_path, spec) + path = _write_spec(tmp_path, spec, generator) monkeypatch.setattr(generator, "SPEC", path) generator._apply() @@ -137,7 +140,7 @@ def test_apply_steps_over_blank_lines_in_any_position( + "\n" * below ) spec = _SPEC_HEAD + above_key + 'datatypes:\n - "String"\n' - path = _write_spec(tmp_path, spec) + path = _write_spec(tmp_path, spec, generator) monkeypatch.setattr(generator, "SPEC", path) generator._apply() @@ -156,7 +159,7 @@ def test_apply_does_not_eat_a_blank_line_it_did_not_write(generator, monkeypatch key is the author's and must survive. """ spec = _SPEC_HEAD + _UNMANAGED + _DATATYPES - path = _write_spec(tmp_path, spec) + path = _write_spec(tmp_path, spec, generator) monkeypatch.setattr(generator, "SPEC", path) generator._apply() @@ -169,7 +172,7 @@ def test_apply_does_not_eat_a_blank_line_it_did_not_write(generator, monkeypatch def test_apply_is_idempotent(generator, monkeypatch, tmp_path): - path = _write_spec(tmp_path, _SPEC_HEAD + _DATATYPES) + path = _write_spec(tmp_path, _SPEC_HEAD + _DATATYPES, generator) monkeypatch.setattr(generator, "SPEC", path) generator._apply() @@ -184,7 +187,7 @@ def test_check_reports_a_file_that_is_out_of_sync(generator, monkeypatch, tmp_pa # value is the only thing out of sync (not a missing/incomplete section). section = generator.SECTIONS[0] in_sync = generator._generate_block(section, generator._schema_values(section)) - path = _write_spec(tmp_path, _SPEC_HEAD + in_sync.replace("String", "MADE_UP", 1)) + path = _write_spec(tmp_path, _SPEC_HEAD + in_sync.replace("String", "MADE_UP", 1), generator) monkeypatch.setattr(generator, "SPEC", path) assert generator._check() == 1 diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index b1b9ffef7..a9d62f6d2 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1696,6 +1696,60 @@ def test_still_reports_unknown_datasets() -> None: ] +_PROFILES = { + "name": "profiles", + "source": "db.s.profiles", + "primary_key": ["profile_id"], + "unique_keys": [["customer_id"]], + "fields": [_field("profile_id"), _field("customer_id"), _field("tier")], +} + + +def _customers_to_profiles(from_columns: list[str], to_columns: list[str], cardinality: str) -> dict: + return { + "name": "customers_to_profiles", + "from": "customers", + "to": "profiles", + "from_columns": from_columns, + "to_columns": to_columns, + "cardinality": cardinality, + } + + +@pytest.mark.parametrize( + ("from_columns", "to_columns", "cardinality", "uncovered"), + [ + (["id"], ["tier"], "OneToMany", []), + (["region"], ["customer_id"], "OneToMany", [("from", ["region"], "customers")]), + (["region"], ["customer_id"], "ManyToOne", []), + (["id"], ["customer_id"], "OneToOne", []), + (["region"], ["tier"], "OneToOne", [("from", ["region"], "customers"), ("to", ["tier"], "profiles")]), + ], + ids=["one-to-many", "one-to-many-uncovered", "many-to-one-ignores-from", "one-to-one", "one-to-one-uncovered"], +) +def test_key_coverage_checks_each_one_side( + from_columns: list[str], to_columns: list[str], cardinality: str, uncovered: list +) -> None: + rel = _customers_to_profiles(from_columns, to_columns, cardinality) + + errors = validate_references(_document([_CUSTOMERS, _PROFILES], [rel])) + + assert errors == [ + "[Reference] Warning: Relationship 'customers_to_profiles' in model 'm': " + f"{side}_columns {columns} does not cover the primary key or a unique key of dataset '{dataset}'" + for side, columns, dataset in uncovered + ] + + +def test_unknown_cardinality_fails_the_schema_and_skips_key_coverage(core_schema: dict) -> None: + document = _document([_CUSTOMERS, _PROFILES], [_customers_to_profiles(["region"], ["tier"], "ManyToMany")]) + + schema_errors = _VALIDATE.validate_schema(document, core_schema) + + assert len(schema_errors) == 1 and "ManyToMany" in schema_errors[0] + assert validate_references(document) == [] + + @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") def test_deeply_nested_sql_reports_a_diagnostic_instead_of_crashing() -> None: # Pathologically nested SQL exhausts sqlglot's recursion limit; the diff --git a/validation/validate.py b/validation/validate.py index 599058503..59edd0c80 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -832,15 +832,51 @@ def validate_key_declarations(data: dict) -> list[str]: return errors +# The sides of a relationship whose fields should cover a declared key, by cardinality. +_ONE_SIDES = {"ManyToOne": ("to",), "OneToMany": ("from",), "OneToOne": ("from", "to")} + + +def _key_coverage_warning( + prefix: str, side: str, dataset_name: str, dataset: dict | None, columns: object, missing: list[str] +) -> ValidationWarning | None: + """Return a warning if a one side's fields cover no declared key of its dataset. + + Coverage (superset of a key) still guarantees that this side matches at + most one row. primary_key and unique_keys are optional, so skip datasets + that declare no usable keys. Keys whose names are not fields are not + usable; columns that already failed the field check are not + coverage-checked. Shape guards keep semantic checks from crashing on + documents that already fail schema validation. + """ + if dataset is None or not isinstance(columns, list) or not columns or missing: + return None + declared = dataset_field_names(dataset) + candidate_keys = [dataset.get("primary_key")] + list(dataset.get("unique_keys") or []) + declared_keys = [] + for key in candidate_keys: + if not isinstance(key, list) or not key: + continue + folded = [name.casefold() for name in key if isinstance(name, str) and name] + if len(folded) == len(key) and all(name in declared for name in folded): + declared_keys.append(set(folded)) + column_set = {name.casefold() for name in columns if isinstance(name, str) and name} + if declared_keys and not any(key <= column_set for key in declared_keys): + return ValidationWarning( + f"[Reference] Warning: {prefix}: {side}_columns {columns} does not cover the primary key or a unique key of dataset '{dataset_name}'" + ) + return None + + def validate_references(data: dict) -> list[str]: """Validate relationship and key names against declared fields. Unknown from/to datasets are errors. from_columns, to_columns, primary_key and unique_keys must name fields of those datasets (spec.md Name Resolution); missing names are errors. JSON Schema cannot express that. - to_columns that does not cover a declared key of the to dataset is a - warning. Coverage uses only keys whose names are themselves declared - fields, compared case-insensitively. + Fields on a one side of the cardinality (to for ManyToOne, the default; + from for OneToMany; both for OneToOne) that do not cover a declared key of + their dataset are a warning. Coverage uses only keys whose names are + themselves declared fields, compared case-insensitively. """ if not isinstance(data, dict) or "datasets" not in data: return [] @@ -893,6 +929,7 @@ def validate_references(data: dict) -> list[str]: from_dataset = datasets.get(from_ds) from_columns = rel.get("from_columns") + missing_from: list[str] = [] if from_dataset is not None and isinstance(from_columns, list): missing_from = undeclared_field_names( from_columns, dataset_field_names(from_dataset) @@ -924,42 +961,15 @@ def validate_references(data: dict) -> list[str]: ) ) - # Coverage (superset of a key) still guarantees the many-to-one join. - # primary_key and unique_keys are optional, so skip datasets that - # declare no usable keys. Keys whose names are not fields are not - # usable; to_columns that already failed the field check is not - # coverage-checked. Shape guards keep semantic checks from crashing - # on documents that already fail schema validation. - if ( - to_dataset is not None - and isinstance(to_columns, list) - and to_columns - and not missing_to - ): - declared = dataset_field_names(to_dataset) - candidate_keys = [to_dataset.get("primary_key")] + list( - to_dataset.get("unique_keys") or [] - ) - declared_keys = [] - for key in candidate_keys: - if not isinstance(key, list) or not key: - continue - folded = [ - name.casefold() - for name in key - if isinstance(name, str) and name - ] - if len(folded) == len(key) and all(name in declared for name in folded): - declared_keys.append(set(folded)) - to_column_set = { - name.casefold() - for name in to_columns - if isinstance(name, str) and name - } - if declared_keys and not any(key <= to_column_set for key in declared_keys): - errors.append(ValidationWarning( - f"[Reference] Warning: {prefix}: to_columns {to_columns} does not cover the primary key or a unique key of dataset '{to_ds}'" - )) + # An unknown cardinality already failed schema validation, so it is skipped. + sides = { + "from": (from_ds, from_dataset, from_columns, missing_from), + "to": (to_ds, to_dataset, to_columns, missing_to), + } + for side in _ONE_SIDES.get(rel.get("cardinality", "ManyToOne"), ()): + warning = _key_coverage_warning(prefix, side, *sides[side]) + if warning is not None: + errors.append(warning) return errors