From 403d34b35398a01db332f3a0f68f575f2724db8c Mon Sep 17 00:00:00 2001 From: ContractGate Lead Date: Thu, 26 Nov 2026 08:14:41 -0500 Subject: [PATCH 1/2] fix: accept ODCS v3.x contracts without an ontology (validate, synth, API, Python SDK) Root cause: validate/synth/enforce/test/push/deploy and the API parsed contract YAML straight into the native Contract struct, where ontology was required and description had to be a string. ODCS documents never reach the existing ODCS importer outside POST /contracts/import. - ontology and ontology.entities now default to empty; description accepts a map - odcs::parse_contract_yaml / normalize_contract_yaml detect ODCS (no ontology plus apiVersion v3.x, kind DataContract, or a schema list) and map it through the existing importer; native YAML is untouched - used by the CLI, POST /contracts/synth, playground, contract create/version/draft/ deploy (stored as native YAML), impact and diff - importer: physicalType fallback, map type, primaryKey implies required and unique (single column), note for extra schema objects, numeric version, clear errors (Data Contract Specification, no schema, no properties, bad apiVersion) - Python SDK Contract.from_yaml reads ODCS and no longer requires ontology - fixtures: official full example and a minimal contract; docs/odcs/using-odcs-directly.md --- docs/odcs/using-odcs-directly.md | 54 +++ docs/synthetic-data-reference.md | 5 + sdks/python/src/contractgate/contract.py | 152 +++++++- .../fixtures/contracts/odcs_full_example.yaml | 362 ++++++++++++++++++ .../fixtures/contracts/odcs_minimal.yaml | 24 ++ sdks/python/tests/test_odcs_input.py | 51 +++ src/cli/commands/deploy.rs | 2 +- src/cli/commands/enforce.rs | 4 +- src/cli/commands/push.rs | 4 +- src/cli/commands/synth.rs | 5 + src/cli/commands/test.rs | 4 +- src/cli/commands/validate.rs | 24 +- src/contract.rs | 28 +- src/impact.rs | 2 +- src/infer_diff.rs | 4 +- src/lib.rs | 1 + src/main.rs | 6 +- src/odcs.rs | 214 +++++++++-- src/storage/contracts.rs | 18 +- src/synth.rs | 2 +- tests/fixtures/odcs/full-example.odcs.yaml | 362 ++++++++++++++++++ .../odcs/minimal-no-ontology.odcs.yaml | 24 ++ tests/odcs_compat.rs | 234 +++++++++++ 23 files changed, 1531 insertions(+), 55 deletions(-) create mode 100644 docs/odcs/using-odcs-directly.md create mode 100644 sdks/python/tests/fixtures/contracts/odcs_full_example.yaml create mode 100644 sdks/python/tests/fixtures/contracts/odcs_minimal.yaml create mode 100644 sdks/python/tests/test_odcs_input.py create mode 100644 tests/fixtures/odcs/full-example.odcs.yaml create mode 100644 tests/fixtures/odcs/minimal-no-ontology.odcs.yaml create mode 100644 tests/odcs_compat.rs diff --git a/docs/odcs/using-odcs-directly.md b/docs/odcs/using-odcs-directly.md new file mode 100644 index 00000000..fd42e0f4 --- /dev/null +++ b/docs/odcs/using-odcs-directly.md @@ -0,0 +1,54 @@ +# Using an ODCS v3.x contract directly + +DataContractGate reads Open Data Contract Standard (ODCS) v3.x documents as +they are. No `ontology` block is needed. These all accept an ODCS file: + +- CLI: `contractgate validate`, `synth`, `test`, `enforce`, `push`, `deploy` +- API: `POST /contracts` (create), `POST /contracts/{id}/versions`, draft + edits, `POST /contracts/deploy`, `POST /contracts/synth`, + `POST /playground/validate`, `POST /contracts/import` +- Python: `Contract.from_yaml(...)` in `contractgate-py` + +A document counts as ODCS when it has no `ontology` and carries +`apiVersion: v3.x`, `kind: DataContract`, or a `schema` list. Native +DataContractGate YAML is read exactly as before. A stored contract is always +kept as native YAML; an ODCS document is converted once, on the way in. + +## How it maps + +| ODCS | DataContractGate | +| --- | --- | +| `dataProduct`, then `schema[0].name`, then root `name` | contract name | +| `version` (string or number) | version | +| `description` as text or `{purpose, usage, limitations}` | description | +| `schema[0].properties[]` | fields | +| `logicalType` (or `physicalType` when absent: `varchar(20)`, `BIGINT`, `NUMERIC(10,2)`) | field type; `map` becomes an object | +| `required`, `primaryKey` | required | +| `unique`, single-column `primaryKey` | batch uniqueness rule | +| `logicalTypeOptions` `pattern`, `format`, `minLength`, `maxLength`, `minimum`, `maximum` | the matching field rules | +| property `enum` (plain values or `{value: ...}` items) | allowed values | +| property `quality` library metrics `nullValues`, `missingValues`, `duplicateValues`, `invalidValues` | quality rules | +| nested names (`a.b`) and `items` | nested objects and array items | + +Unknown ODCS fields are ignored. + +## What does not map + +- Only `schema[0]` is read. Other schema objects are reported as a note + (`contractgate validate` prints it) and skipped. +- `relationships` and foreign keys, composite primary key uniqueness. +- Dataset-level `quality` (for example `rowCount`), `sql` and `custom` quality + checks from other engines. +- `servers`, `team`, `roles`, `slaProperties`, `support`, `price`, + `customProperties` (except the `x-cg-*` ones DataContractGate writes), + `authoritativeDefinitions`, `classification`, `tags`, `examples`. +- Map key and value types (a `map` field accepts any object). + +## Errors + +- A Data Contract Specification (datacontract.com, `dataContractSpecification:`) + file is a different format: convert it first, for example with + `datacontract export --format odcs`. +- `apiVersion` other than `v3.*` is rejected with the supported range. +- Missing `version`, a missing `schema` array, or a `schema[0]` with no + properties each get a message naming the problem. diff --git a/docs/synthetic-data-reference.md b/docs/synthetic-data-reference.md index 1b0513ae..d0164d21 100644 --- a/docs/synthetic-data-reference.md +++ b/docs/synthetic-data-reference.md @@ -150,3 +150,8 @@ python -m contractgate synth contracts/orders.yaml --rows 10 ``` It takes the same options as the Rust CLI plus `--contract-id`, `--version`, `--api-key` (default `$CONTRACTGATE_API_KEY`) and `--base-url` (default `$CONTRACTGATE_BASE_URL`, then `https://api.datacontractgate.com`). Exit codes: 0 rows written, 1 a rule cannot be met, 2 any other error. The command is named `contractgate-py` so it never shadows the Rust `contractgate` binary: both can be installed side by side. `contractgate` runs locally, `contractgate-py` calls the API. + +## ODCS input + +`contractgate synth` and `POST /contracts/synth` accept an ODCS v3.x document +with no `ontology`. See [`odcs/using-odcs-directly.md`](odcs/using-odcs-directly.md). diff --git a/sdks/python/src/contractgate/contract.py b/sdks/python/src/contractgate/contract.py index 46bf3a35..685c2df6 100644 --- a/sdks/python/src/contractgate/contract.py +++ b/sdks/python/src/contractgate/contract.py @@ -241,6 +241,146 @@ def from_yaml(cls, raw: Any) -> "GlossaryEntry": ) +# --------------------------------------------------------------------------- +# ODCS v3.x input +# --------------------------------------------------------------------------- + +_ODCS_LOGICAL = { + "integer": "integer", "long": "integer", "int": "integer", + "number": "number", "double": "number", "float": "number", "decimal": "number", + "boolean": "boolean", "bool": "boolean", + "object": "object", "record": "object", "struct": "object", "map": "object", + "array": "array", "list": "array", + "date": "date", "date32": "date", + "timestamp": "timestamp", "datetime": "timestamp", "timestamptz": "timestamp", + "any": "any", +} +_ODCS_PHYSICAL = { + "int": "integer", "integer": "integer", "bigint": "integer", "smallint": "integer", + "tinyint": "integer", "long": "integer", "short": "integer", + "float": "number", "double": "number", "real": "number", "decimal": "number", + "numeric": "number", "number": "number", + "boolean": "boolean", "bool": "boolean", + "date": "date", + "timestamp": "timestamp", "timestamptz": "timestamp", "datetime": "timestamp", + "struct": "object", "record": "object", "object": "object", "map": "object", + "json": "object", "jsonb": "object", "variant": "object", + "array": "array", "list": "array", +} + + +def _is_odcs(raw: Dict[str, Any]) -> bool: + """An ODCS document: no ``ontology`` and an ``apiVersion: v3*``, + ``kind: DataContract`` or a ``schema`` list.""" + if "ontology" in raw: + return False + api = raw.get("apiVersion") + return ( + (isinstance(api, str) and api.startswith("v3")) + or raw.get("kind") == "DataContract" + or isinstance(raw.get("schema"), list) + ) + + +def _odcs_description(v: Any) -> Optional[str]: + if isinstance(v, str): + return v + if isinstance(v, dict): + for k in ("purpose", "usage", "limitations"): + if isinstance(v.get(k), str): + return v[k] + return None + + +def _odcs_enum(v: Any) -> Optional[List[Any]]: + if not isinstance(v, list): + return None + out = [i.get("value") if isinstance(i, dict) else i for i in v] + out = [i for i in out if isinstance(i, (str, int, float, bool))] + return out or None + + +def _odcs_prop(p: Dict[str, Any]) -> Dict[str, Any]: + logical = p.get("logicalType") + if isinstance(logical, str): + ftype = _ODCS_LOGICAL.get(logical, "string") + else: + base = str(p.get("physicalType") or "").lower() + for sep in ("(", "<", " "): + base = base.split(sep)[0] + ftype = _ODCS_PHYSICAL.get(base, "string") + opts = p.get("logicalTypeOptions") if isinstance(p.get("logicalTypeOptions"), dict) else {} + ent: Dict[str, Any] = { + "name": str(p.get("name")), + "type": ftype, + "required": bool(p.get("required", False)) or p.get("primaryKey") is True, + } + enum = _odcs_enum(p.get("enum")) or _odcs_enum(opts.get("enum")) + if enum: + ent["enum"] = enum + for src, dst in ( + ("pattern", "pattern"), ("minLength", "min_length"), ("maxLength", "max_length"), + ("format", "format"), + ): + if opts.get(src) is not None: + ent[dst] = opts[src] + for src, dst in (("minimum", "min"), ("maximum", "max")): + if isinstance(opts.get(src), (int, float)) and not isinstance(opts.get(src), bool): + ent[dst] = opts[src] + return ent + + +def _odcs_to_native(raw: Dict[str, Any]) -> Dict[str, Any]: + """Map an ODCS v3.x document (schema[0].properties[]) to the native + contract mapping. Unknown ODCS fields are ignored.""" + api = raw.get("apiVersion") + if isinstance(api, str) and not api.startswith("v3"): + raise ContractCompileError(f"unsupported ODCS apiVersion {api!r}; supported: v3.x") + version = raw.get("version") + if isinstance(version, (int, float)) and not isinstance(version, bool): + version = str(version) + if not isinstance(version, str) or not version: + raise ContractCompileError("ODCS document is missing the required 'version' field") + schema = raw.get("schema") + if not isinstance(schema, list) or not schema or not isinstance(schema[0], dict): + raise ContractCompileError( + "ODCS document has no 'schema' array; fields are read from schema[].properties[]" + ) + s0 = schema[0] + props = s0.get("properties") + if not isinstance(props, list) or not props: + raise ContractCompileError( + f"ODCS schema[0] ({s0.get('name')!r}) has no properties; nothing to validate" + ) + # Same order as the Rust importer: dataProduct, schema[0].name, root name. + name = next( + ( + v + for v in (raw.get("dataProduct"), s0.get("name"), raw.get("name")) + if isinstance(v, str) and v.strip() + ), + "imported_contract", + ) + entities = [_odcs_prop(p) for p in props if isinstance(p, dict) and p.get("name")] + pk = [p for p in props if isinstance(p, dict) and p.get("primaryKey") is True] + quality = [] + for p in props: + if not isinstance(p, dict) or not p.get("name"): + continue + if p.get("unique") is True or (p.get("primaryKey") is True and len(pk) == 1): + quality.append({"field": str(p["name"]), "type": "uniqueness"}) + native: Dict[str, Any] = { + "version": version, + "name": name, + "ontology": {"entities": entities}, + "quality": quality, + } + desc = _odcs_description(raw.get("description")) or _odcs_description(s0.get("description")) + if desc: + native["description"] = desc + return native + + # --------------------------------------------------------------------------- # Top-level Contract # --------------------------------------------------------------------------- @@ -271,6 +411,9 @@ def from_yaml(cls, source: str) -> "Contract": if not isinstance(raw, dict): raise ContractCompileError("contract YAML must be a mapping at the top level") + if _is_odcs(raw): + raw = _odcs_to_native(raw) + version = raw.get("version") name = raw.get("name") if not isinstance(version, str) or not version: @@ -278,10 +421,11 @@ def from_yaml(cls, source: str) -> "Contract": if not isinstance(name, str) or not name: raise ContractCompileError("contract.name is required") - ontology_raw = raw.get("ontology") + # `ontology` is optional; a contract may carry only quality rules. + ontology_raw = raw.get("ontology") if raw.get("ontology") is not None else {} if not isinstance(ontology_raw, dict): - raise ContractCompileError("contract.ontology is required and must be a mapping") - entities_raw = ontology_raw.get("entities") + raise ContractCompileError("contract.ontology must be a mapping") + entities_raw = ontology_raw.get("entities") if ontology_raw.get("entities") is not None else [] if not isinstance(entities_raw, list): raise ContractCompileError("contract.ontology.entities must be a list") entities = [FieldDefinition.from_yaml(e) for e in entities_raw] @@ -294,7 +438,7 @@ def from_yaml(cls, source: str) -> "Contract": return cls( version=version, name=name, - description=_opt_str(raw.get("description")), + description=_opt_str(_odcs_description(raw.get("description"))), compliance_mode=bool(raw.get("compliance_mode", False)), entities=entities, glossary=glossary, diff --git a/sdks/python/tests/fixtures/contracts/odcs_full_example.yaml b/sdks/python/tests/fixtures/contracts/odcs_full_example.yaml new file mode 100644 index 00000000..f1c072bd --- /dev/null +++ b/sdks/python/tests/fixtures/contracts/odcs_full_example.yaml @@ -0,0 +1,362 @@ +# Copyright 2026 The Bitol Contributors +# SPDX-License-Identifier: Apache-2.0 + +# What's this data contract about? +domain: seller # Domain +dataProduct: my quantum # Data product name +version: 1.1.0 # Version (follows semantic versioning) +status: active +id: 53581432-6c55-4ba2-a65f-72344a91553a + +authoritativeDefinitions: +- type: canonical + url: https://github.com/bitol-io/open-data-contract-standard/blob/main/docs/examples/all/full-example.odcs.yaml + description: Canonical URL to the latest version of the contract. + +# Lots of information +description: + purpose: Views built on top of the seller tables. + limitations: Data based on seller perspective, no buyer information + usage: Predict sales over time + authoritativeDefinitions: + - type: privacy-statement + url: https://example.com/gdpr.pdf +tenant: ClimateQuantumInc + +kind: DataContract +apiVersion: v3.2.0 # Standard version (follows semantic versioning) + +# Infrastructure & servers +servers: + - server: my-postgres + type: postgres + host: localhost + port: 5432 + database: pypl-edw + schema: pp_access_views + +# Dataset, schema, and quality +schema: + - id: tbl_obj + name: tbl + physicalName: tbl_1 + physicalType: table + businessName: Core Payment Metrics + description: Provides core payment metrics + authoritativeDefinitions: + - url: https://catalog.data.gov/dataset/air-quality + type: businessDefinition + - url: https://youtu.be/jbY1BKFj9ec + type: videoTutorial + tags: [ 'finance', 'payments'] + dataGranularityDescription: Aggregation on columns txn_ref_dt, pmt_txn_id + # Schema-level relationships (for composite keys) + relationships: + - type: foreignKey + from: + - tbl.rcvr_id + - tbl.rcvr_cntry_code + to: + - receivers.id + - receivers.country_code + customProperties: + - property: description + value: "Composite key linking to receivers table" + - property: cardinality + value: "many-to-one" + properties: + - id: txn_ref_dt_prop + name: transaction_reference_date + physicalName: txn_ref_dt + primaryKey: false + primaryKeyPosition: -1 + businessName: transaction reference date + logicalType: date + physicalType: date + required: false + description: Reference date for transaction + partitioned: true + partitionKeyPosition: 1 + criticalDataElement: false + tags: [ ] + classification: public + transformSourceObjects: + - table_name_1 + - table_name_2 + - table_name_3 + transformLogic: sel t1.txn_dt as txn_ref_dt from table_name_1 as t1, table_name_2 as t2, table_name_3 as t3 where t1.txn_dt=date-3 + transformDescription: defines the logic in business terms; logic for dummies + examples: + - "2022-10-03" + - "2020-01-28" + customProperties: + - property: anonymizationStrategy + value: none + - id: rcvr_id_prop + name: rcvr_id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver id + logicalType: string + physicalType: varchar(18) + required: false + description: A description for column rcvr_id. + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ 'uid' ] + classification: restricted + # Property-level relationship (from is implicit) + relationships: + - to: receivers.id + type: foreignKey + customProperties: + - property: description + value: "Links to receiver master data" + - id: rcvr_cntry_code_prop + name: rcvr_cntry_code + primaryKey: false + primaryKeyPosition: -1 + businessName: receiver country code + logicalType: string + physicalType: varchar(2) + required: false + description: Country code + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ ] + classification: public + # Enumeration of allowed values (RFC 0033, ODCS v3.2.0+) + enum: + - value: US + label: United States + description: ISO 3166-1 alpha-2 code for the United States. + - value: CA + label: Canada + - value: MX + label: Mexico + customProperties: + - property: languageEs + value: México + authoritativeDefinitions: + - url: https://collibra.com/asset/742b358f-71a5-4ab1-bda4-dcdba9418c25 + type: businessDefinition + - url: https://github.com/myorg/myrepo + type: transformationImplementation + - url: jdbc:postgresql://localhost:5432/adventureworks/tbl_1/rcvr_cntry_code + type: implementation + encryptedName: rcvr_cntry_code_encrypted + quality: + - metric: nullValues + mustBe: 0 + description: column should not contain null values + dimension: completeness + type: library + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: FIELD_NAME + value: + - property: COMPARE_TO + value: + - property: COMPARISON_TYPE + value: Greater than + quality: + - metric: rowCount + mustBeGreaterThan: 1000000 + type: library + description: Ensure row count is within expected volume range + dimension: completeness + method: reconciliation + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: business-key + value: + - txn_ref_dt + - rcvr_id + + # Receivers master table + - id: receivers_obj + name: receivers + physicalName: receivers_master + physicalType: table + businessName: Receivers Master Data + description: Master data for all receivers + tags: [ 'master-data', 'receivers' ] + properties: + - id: receiver_id_prop + name: id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver identifier + logicalType: string + physicalType: varchar(18) + required: true + description: Unique identifier for receiver + unique: true + classification: restricted + - id: country_code_prop + name: country_code + primaryKey: true + primaryKeyPosition: 2 + businessName: receiver country + logicalType: string + physicalType: varchar(2) + required: true + description: Country code of the receiver + classification: public + - id: receiver_name_prop + name: receiver_name + businessName: receiver name + logicalType: string + physicalType: varchar(255) + required: true + description: Name of the receiver + classification: restricted + - id: receiver_type_prop + name: receiver_type + businessName: receiver type + logicalType: string + physicalType: varchar(20) + required: false + description: Type of receiver (individual, business, etc.) + classification: public + # Example of nested reference + relationships: + - to: receiver_types.type_code + customProperties: + - property: description + value: "Links to receiver type definitions" + # Map-typed property (RFC 0030, ODCS v3.2.0+) + - id: receiver_attributes_prop + name: receiver_attributes + businessName: receiver attributes + logicalType: map + physicalType: "MAP" + required: false + description: Free-form attributes attached to a receiver, keyed by attribute name. + classification: restricted + map: + key: + logicalType: string + description: Attribute name. + value: + logicalType: string + description: Attribute value. + + +# Pricing +price: + priceAmount: 9.95 + priceCurrency: USD + priceUnit: megabyte + + +# Team +team: + name: my-team + description: The team owning the data contract + members: + - username: ceastwood + role: Data Scientist + dateIn: "2022-08-02" + dateOut: "2022-10-01" + replacedByUsername: mhopper + - username: mhopper + role: Data Scientist + dateIn: "2022-10-01" + - username: daustin + role: Owner + description: Keeper of the grail + dateIn: "2022-10-01" + + +# Roles +roles: + - role: microstrategy_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mandolorian' + - role: bq_queryman_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: na + - role: risk_data_access_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'dathvador' + - role: bq_unica_user_opr + access: write + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mickey' + +# SLA +slaProperties: + - property: latency # Property, see list of values in DP QoS + value: 4 + unit: d # d, day, days for days; y, yr, years for years + element: tab1.txn_ref_dt # This would not be needed as it is the same table.column as the default one + - property: generalAvailability + value: "2022-05-12T09:30:10-08:00" + - property: endOfSupport + value: "2032-05-12T09:30:10-08:00" + - property: endOfLife + value: "2042-05-12T09:30:10-08:00" + - property: retention + value: 3 + unit: y + element: tab1.txn_ref_dt + - property: frequency + value: 1 + valueExt: 1 + unit: d + element: tab1.txn_ref_dt + - property: timeOfAvailability + value: 09:00-08:00 + element: tab1.txn_ref_dt + driver: regulatory # Describes the importance of the SLA: [regulatory|analytics|operational|...] + - property: timeOfAvailability + value: 08:00-08:00 + element: tab1.txn_ref_dt + driver: analytics + + +# Support +support: + - channel: '#product-help' # Simple Slack communication channel + tool: slack + - channel: datacontract-ann # Simple distribution list + tool: email + url: mailto:datacontract-ann@bitol.io + - channel: Feedback # Product Feedback + description: General Product Feedback (Public) + url: https://product-feedback.com + - channel: 'product-issues' + tool: teams + scope: issues + customProperties: + - property: servicehours + value: 9-5 CET + + +# Tags +tags: + - transactions + + +# Custom properties +customProperties: + - property: refRulesetName + value: gcsc.ruleset.name + - property: somePropertyName + value: property.value + - property: dataprocClusterName # Used for specific applications like Elevate + value: [ cluster name ] + +contractCreatedTs: "2022-11-15T02:59:43+00:00" diff --git a/sdks/python/tests/fixtures/contracts/odcs_minimal.yaml b/sdks/python/tests/fixtures/contracts/odcs_minimal.yaml new file mode 100644 index 00000000..87ce5996 --- /dev/null +++ b/sdks/python/tests/fixtures/contracts/odcs_minimal.yaml @@ -0,0 +1,24 @@ +apiVersion: v3.2.0 +kind: DataContract +id: 11111111-2222-3333-4444-555555555555 +name: orders +version: 1.0.0 +status: active +description: + purpose: Minimal orders contract +schema: + - name: orders + physicalType: table + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: amount + logicalType: number + required: true + logicalTypeOptions: + minimum: 0 + - name: status + logicalType: string + enum: [open, closed] diff --git a/sdks/python/tests/test_odcs_input.py b/sdks/python/tests/test_odcs_input.py new file mode 100644 index 00000000..e2bfc57e --- /dev/null +++ b/sdks/python/tests/test_odcs_input.py @@ -0,0 +1,51 @@ +"""ODCS v3.x documents (no ``ontology``) parse with ``Contract.from_yaml``.""" + +from __future__ import annotations + +import pathlib + +import pytest + +from contractgate import Contract, ContractCompileError, FieldType + +FIXTURES = pathlib.Path(__file__).parent / "fixtures" / "contracts" + + +def _load(name: str) -> str: + return (FIXTURES / name).read_text() + + +def test_minimal_odcs_parses_and_validates_events(): + c = Contract.from_yaml(_load("odcs_minimal.yaml")) + assert c.name == "orders" + assert c.description == "Minimal orders contract" + assert [e.name for e in c.entities] == ["order_id", "amount", "status"] + assert c.entities[1].field_type == FieldType.FLOAT + compiled = c.compile() + assert compiled.validate({"order_id": "a", "amount": 2.5, "status": "open"}).passed + assert not compiled.validate({"order_id": "a", "amount": -1, "status": "open"}).passed + assert not compiled.validate({"order_id": "a", "amount": 1, "status": "nope"}).passed + + +def test_official_full_example_parses(): + c = Contract.from_yaml(_load("odcs_full_example.yaml")) + # description is a map in ODCS 3.x + assert c.description == "Views built on top of the seller tables." + names = {e.name: e for e in c.entities} + assert names["rcvr_cntry_code"].allowed_values == ["US", "CA", "MX"] + assert names["transaction_reference_date"].field_type == FieldType.DATE + assert names["rcvr_id"].required is True # primaryKey + compiled = c.compile() + assert compiled.validate({"rcvr_id": "x", "rcvr_cntry_code": "US"}).passed + + +def test_ontology_is_optional_for_native_contracts(): + c = Contract.from_yaml('version: "1.0"\nname: bare\n') + assert c.entities == [] + + +def test_unsupported_odcs_errors_are_clear(): + with pytest.raises(ContractCompileError, match="no 'schema' array"): + Contract.from_yaml("apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\n") + with pytest.raises(ContractCompileError, match="unsupported ODCS apiVersion"): + Contract.from_yaml("apiVersion: v2.2.2\nkind: DataContract\nname: n\nversion: 1\nschema: []\n") diff --git a/src/cli/commands/deploy.rs b/src/cli/commands/deploy.rs index 0c049d86..eb825628 100644 --- a/src/cli/commands/deploy.rs +++ b/src/cli/commands/deploy.rs @@ -98,7 +98,7 @@ pub fn run(args: &DeployArgs, cfg: &CliConfig, api_key: &str) -> Result { } }; - let contract: Contract = match serde_yaml::from_str(&yaml) { + let contract: Contract = match crate::odcs::parse_contract_yaml(&yaml) { Ok(c) => c, Err(e) => { let msg = format!("YAML parse error: {e}"); diff --git a/src/cli/commands/enforce.rs b/src/cli/commands/enforce.rs index 7598dd93..86f80758 100644 --- a/src/cli/commands/enforce.rs +++ b/src/cli/commands/enforce.rs @@ -139,8 +139,8 @@ fn load_contract(spec: &str) -> anyhow::Result<(String, CompiledContract)> { } let yaml = std::fs::read_to_string(spec).map_err(|e| anyhow::anyhow!("cannot read {spec}: {e}"))?; - let contract: Contract = - serde_yaml::from_str(&yaml).map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/push.rs b/src/cli/commands/push.rs index 2530721a..8b846051 100644 --- a/src/cli/commands/push.rs +++ b/src/cli/commands/push.rs @@ -149,8 +149,8 @@ fn dry_run_files(files: &[PathBuf], mode: output::Mode) -> Result { fn parse_file(path: &Path) -> Result<(String, String, String)> { let yaml = std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("cannot read file: {e}"))?; - let contract: Contract = - serde_yaml::from_str(&yaml).map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; + let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) + .map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; Ok((yaml, contract.name.clone(), contract.version.clone())) } diff --git a/src/cli/commands/synth.rs b/src/cli/commands/synth.rs index eee4a455..eba0e022 100644 --- a/src/cli/commands/synth.rs +++ b/src/cli/commands/synth.rs @@ -66,6 +66,11 @@ pub fn run(args: &SynthArgs) -> Result { return Ok(2); } }; + if let Ok((_, notes)) = crate::odcs::normalize_contract_yaml(&yaml) { + for n in notes { + eprintln!("note: {n}"); + } + } let compiled = match synth::compile_yaml(&yaml) { Ok(c) => c, Err(e) => { diff --git a/src/cli/commands/test.rs b/src/cli/commands/test.rs index 319029d5..a6a67354 100644 --- a/src/cli/commands/test.rs +++ b/src/cli/commands/test.rs @@ -219,8 +219,8 @@ impl Format { fn load_contract(path: &PathBuf) -> anyhow::Result<(String, CompiledContract)> { let yaml = std::fs::read_to_string(path) .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?; - let contract: Contract = - serde_yaml::from_str(&yaml).map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/validate.rs b/src/cli/commands/validate.rs index 8a909349..fba95467 100644 --- a/src/cli/commands/validate.rs +++ b/src/cli/commands/validate.rs @@ -24,6 +24,9 @@ struct FileResult { status: &'static str, #[serde(skip_serializing_if = "Option::is_none")] error: Option, + /// ODCS parts that did not map (extra schema objects, ...). + #[serde(skip_serializing_if = "Vec::is_empty")] + notes: Vec, } /// Parse + compile each contract YAML locally. No network. Per-file pass/fail. @@ -56,15 +59,20 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { for path in &files { let result = validate_file(path); match result { - Ok(()) => { + Ok(notes) => { let name = path.display().to_string(); + let mut text = format!("PASS {name}"); + for n in ¬es { + text.push_str(&format!("\n note: {n}")); + } output::ok( mode, - &format!("PASS {name}"), + &text, &FileResult { file: name, status: "pass", error: None, + notes, }, ); } @@ -79,6 +87,7 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { file: name, status: "fail", error: Some(msg), + notes: Vec::new(), }, ); } @@ -88,11 +97,14 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { Ok(if any_failure { 1 } else { 0 }) } -fn validate_file(path: &Path) -> Result<()> { +/// Native or ODCS v3.x YAML. Returns notes for anything in an ODCS document +/// that did not map. +fn validate_file(path: &Path) -> Result> { let src = std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("cannot read file: {e}"))?; - let contract: Contract = - serde_yaml::from_str(&src).map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; + let (contract, notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with_notes(&src) + .map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; CompiledContract::compile(contract).map_err(|e| anyhow::anyhow!("compile error: {e}"))?; - Ok(()) + Ok(notes) } diff --git a/src/contract.rs b/src/contract.rs index a929ca7a..3941cd8d 100644 --- a/src/contract.rs +++ b/src/contract.rs @@ -54,7 +54,8 @@ pub struct Contract { /// Human-readable name for the contract pub name: String, /// Optional description of what data this contract covers - #[serde(default)] + /// Accepts a string or an ODCS v3 description object. + #[serde(default, deserialize_with = "lenient_description")] pub description: Option, /// RFC-004: when true, events containing fields not declared in /// `ontology.entities` are rejected as per-event `UNDECLARED_FIELD` @@ -62,7 +63,10 @@ pub struct Contract { /// (undeclared fields pass through untouched). #[serde(default)] pub compliance_mode: bool, - /// Field-level ontology (structure + constraints) + /// Field-level ontology (structure + constraints). Optional so a contract + /// that only carries quality rules still parses; ODCS documents are + /// mapped into this by `odcs::parse_contract_yaml`. + #[serde(default)] pub ontology: Ontology, /// Business glossary entries #[serde(default)] @@ -272,11 +276,29 @@ fn is_false(value: &bool) -> bool { // --------------------------------------------------------------------------- /// The structural schema — a list of field (entity) definitions. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Ontology { + #[serde(default)] pub entities: Vec, } +/// `description` as a string, or the ODCS v3 object form +/// (`purpose`, then `usage`, then `limitations`). Other shapes read as absent. +fn lenient_description<'de, D>(d: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let v = serde_yaml::Value::deserialize(d)?; + Ok(match v { + serde_yaml::Value::String(s) => Some(s), + serde_yaml::Value::Mapping(m) => ["purpose", "usage", "limitations"] + .iter() + .find_map(|k| m.get(*k).and_then(|v| v.as_str())) + .map(String::from), + _ => None, + }) +} + /// Defines a single field (entity attribute) inside a data event. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FieldDefinition { diff --git a/src/impact.rs b/src/impact.rs index 82c620c9..ec92c905 100644 --- a/src/impact.rs +++ b/src/impact.rs @@ -143,7 +143,7 @@ pub fn classify_yaml(before: Option<&str>, after: &str) -> Result Result { - serde_yaml::from_str(yaml).map_err(|e| format!("invalid contract YAML: {e}")) + crate::odcs::parse_contract_yaml(yaml).map_err(|e| format!("invalid contract YAML: {e}")) } fn collect_renames(yaml: &str) -> HashMap { diff --git a/src/infer_diff.rs b/src/infer_diff.rs index ec1718ba..f3a669a8 100644 --- a/src/infer_diff.rs +++ b/src/infer_diff.rs @@ -140,10 +140,10 @@ impl DiffSummarizer for RuleBasedSummarizer { // --------------------------------------------------------------------------- pub async fn diff_handler(Json(req): Json) -> AppResult> { - let contract_a: Contract = serde_yaml::from_str(&req.contract_yaml_a) + let contract_a: Contract = crate::odcs::parse_contract_yaml(&req.contract_yaml_a) .map_err(|e| AppError::BadRequest(format!("invalid contract_yaml_a: {e}")))?; - let contract_b: Contract = serde_yaml::from_str(&req.contract_yaml_b) + let contract_b: Contract = crate::odcs::parse_contract_yaml(&req.contract_yaml_b) .map_err(|e| AppError::BadRequest(format!("invalid contract_yaml_b: {e}")))?; let changes = diff_contracts(&contract_a, &contract_b); diff --git a/src/lib.rs b/src/lib.rs index d96c491c..d4c62cd2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,6 +21,7 @@ pub mod error; pub mod infer; pub mod infer_avro; pub mod infer_proto; +pub mod odcs; pub mod payload_redaction; pub mod rate_limit; pub mod request_limits; diff --git a/src/main.rs b/src/main.rs index ad356eda..87862ea8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -79,7 +79,7 @@ mod kinesis_ingress; mod me; mod metering; pub mod observability; -mod odcs; +use contractgate::odcs; mod passed_events; mod plan; mod public_catalog; @@ -1579,8 +1579,8 @@ fn playground_disposition(passed: bool, on_fail: contract::OnFailMode) -> &'stat /// audit or quarantine write. The authenticated route and the anonymous /// route both call this. fn run_playground(req: PlaygroundRequest) -> AppResult { - let contract: contract::Contract = serde_yaml::from_str(&req.yaml_content) - .map_err(|e| AppError::InvalidContractYaml(e.to_string()))?; + let contract: contract::Contract = + odcs::parse_contract_yaml(&req.yaml_content).map_err(AppError::InvalidContractYaml)?; // Copied before `compile` moves the contract. `OnFailMode` is `Copy`. let on_fail = contract.on_fail; diff --git a/src/odcs.rs b/src/odcs.rs index a8853e03..b4dffb89 100644 --- a/src/odcs.rs +++ b/src/odcs.rs @@ -86,7 +86,8 @@ fn logical_to_field_type(s: &str) -> FieldType { "integer" | "long" | "int" => FieldType::Integer, "double" | "float" | "decimal" | "number" => FieldType::Float, "boolean" | "bool" => FieldType::Boolean, - "object" | "record" | "struct" => FieldType::Object, + // ODCS v3.2 `map` is a free-form key/value object. + "object" | "record" | "struct" | "map" => FieldType::Object, "array" | "list" => FieldType::Array, // RFC-044: date32 is the Arrow/Iceberg alias "date" | "date32" => FieldType::Date, @@ -96,6 +97,27 @@ fn logical_to_field_type(s: &str) -> FieldType { } } +/// Best-effort type from an ODCS `physicalType` such as `varchar(18)`, +/// `BIGINT`, `NUMERIC(10,2)` or `MAP`, used only when a +/// property has no `logicalType`. +fn physical_to_field_type(s: &str) -> FieldType { + let t = s.trim().to_ascii_lowercase(); + let base = t.split(['(', '<', ' ']).next().unwrap_or(""); + match base { + "int" | "integer" | "bigint" | "smallint" | "tinyint" | "long" | "short" | "int2" + | "int4" | "int8" | "serial" | "bigserial" => FieldType::Integer, + "float" | "double" | "real" | "decimal" | "numeric" | "number" | "float4" | "float8" + | "money" => FieldType::Float, + "boolean" | "bool" | "bit" => FieldType::Boolean, + "date" => FieldType::Date, + "timestamp" | "timestamptz" | "datetime" | "datetime2" | "timestamp_ntz" + | "timestamp_ltz" => FieldType::Timestamp, + "struct" | "record" | "object" | "map" | "json" | "jsonb" | "variant" => FieldType::Object, + "array" | "list" => FieldType::Array, + _ => FieldType::String, + } +} + // --------------------------------------------------------------------------- // Property flattening (D-001) // --------------------------------------------------------------------------- @@ -637,6 +659,9 @@ pub struct ImportResult { pub yaml_content: String, /// Fidelity level — `Odcs` (lossless) or `OdcsStripped` (best-effort). pub import_source: ImportSource, + /// Parts of the document that did not map (extra schema objects, ...). + /// Empty for a lossless import. + pub warnings: Vec, } /// Look up a top-level `x-contractgate-*` extension in either location: @@ -680,15 +705,31 @@ pub fn import_odcs(yaml: &str) -> Result { .as_mapping() .ok_or_else(|| "ODCS document must be a YAML mapping".to_string())?; - // Extract the mandatory `version` field. - let version = mapping - .get("version") - .and_then(|v| v.as_str()) - .ok_or_else(|| "ODCS document missing required 'version' field".to_string())? - .to_string(); + // A Data Contract Specification (datacontract.com, pre-ODCS) document is + // a different format; say so instead of failing on a missing field. + if mapping.contains_key("dataContractSpecification") { + return Err( + "this is a Data Contract Specification (datacontract.com) document, \ + not ODCS; convert it first, e.g. `datacontract export --format odcs`" + .to_string(), + ); + } check_api_version(mapping)?; + // The mandatory `version` field. A bare number (`version: 1.0`) is read + // as its text. + let version = match mapping.get("version") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + Some(Value::Number(n)) => n.to_string(), + _ => { + return Err( + "ODCS document is missing the required 'version' field (e.g. version: 1.0.0)" + .to_string(), + ) + } + }; + if root_extension(mapping, "x-contractgate-version").is_some() { import_mode_a(mapping, version) } else { @@ -696,6 +737,67 @@ pub fn import_odcs(yaml: &str) -> Result { } } +/// True when a parsed YAML document is an ODCS data contract rather than a +/// native DataContractGate contract: no `ontology`, and an `apiVersion: v3.x`, +/// `kind: DataContract`, or a `schema` list. +pub fn looks_like_odcs(doc: &Value) -> bool { + let Some(m) = doc.as_mapping() else { + return false; + }; + if m.contains_key("ontology") { + return false; + } + let api_v3 = m + .get("apiVersion") + .and_then(|v| v.as_str()) + .is_some_and(|v| v.starts_with("v3")); + let kind = m.get("kind").and_then(|v| v.as_str()) == Some("DataContract"); + let schema = m.get("schema").is_some_and(|v| v.is_sequence()); + api_v3 || kind || schema +} + +/// Accept native DataContractGate YAML or an ODCS v3.x document and return +/// the native contract YAML. Native input comes back unchanged. The second +/// value lists anything in an ODCS document that did not map. +pub fn normalize_contract_yaml( + yaml: &str, +) -> Result<(std::borrow::Cow<'_, str>, Vec), String> { + // Cheap pre-check so native YAML on hot paths is not parsed twice. + let maybe_odcs = yaml.contains("apiVersion") + || yaml.contains("DataContract") + || yaml.contains("schema:") + || yaml.contains("dataContractSpecification"); + if !maybe_odcs { + return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); + } + let doc: Value = match serde_yaml::from_str(yaml) { + Ok(d) => d, + // Leave YAML syntax errors to the caller's native parse so the + // message and line numbers stay what they were. + Err(_) => return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())), + }; + let spec = doc.as_mapping().is_some_and(|m| { + m.contains_key("dataContractSpecification") && !m.contains_key("ontology") + }); + if !looks_like_odcs(&doc) && !spec { + return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); + } + let r = import_odcs(yaml).map_err(|e| format!("ODCS import: {e}"))?; + Ok((std::borrow::Cow::Owned(r.yaml_content), r.warnings)) +} + +/// Parse contract YAML (native or ODCS v3.x) into a [`Contract`]. +pub fn parse_contract_yaml(yaml: &str) -> Result { + parse_contract_yaml_with_notes(yaml).map(|(c, _)| c) +} + +/// Like [`parse_contract_yaml`], also returning ODCS import notes. +pub fn parse_contract_yaml_with_notes(yaml: &str) -> Result<(Contract, Vec), String> { + let (native, notes) = normalize_contract_yaml(yaml)?; + let contract: Contract = serde_yaml::from_str(&native).map_err(|e| e.to_string())?; + Ok((contract, notes)) +} + /// Accept `v3.1.0` and `v3.2.0`, and any other `v3.*` string, so a document /// that imported before property-level enums landed still imports. A missing /// `apiVersion` is allowed. A non-string value is rejected. Non-3.x versions @@ -733,13 +835,16 @@ fn import_mode_a(doc: &Mapping, version: String) -> Result other => other, }; + // The ODCS document's top-level `version` is the version row (export + // writes it from the row); make the embedded contract agree with it. + let mut ontology = ontology; + if let Value::Mapping(m) = &mut ontology { + m.insert(v_str("version"), v_str(version.clone())); + } // Re-serialize the ontology subtree to a YAML string. Key ordering may // differ from the original, but the Contract is semantically identical. let yaml_content = serde_yaml::to_string(&ontology) .map_err(|e| format!("failed to serialize x-contractgate-ontology: {e}"))?; - // The ODCS document's top-level `version` is the version row (export - // writes it from the row); make the embedded contract agree with it. - let yaml_content = crate::version_pin::set_yaml_version(&yaml_content, &version); let _: Contract = serde_yaml::from_str(&yaml_content) .map_err(|e| format!("x-contractgate-ontology is not a valid Contract: {e}"))?; @@ -748,6 +853,7 @@ fn import_mode_a(doc: &Mapping, version: String) -> Result version, yaml_content, import_source: ImportSource::Odcs, + warnings: Vec::new(), }) } @@ -757,17 +863,25 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result let schema_seq = doc .get("schema") .and_then(|v| v.as_sequence()) - .ok_or_else(|| "ODCS document missing 'schema' array".to_string())?; + .ok_or_else(|| { + "ODCS document has no 'schema' array; DataContractGate reads fields from \ + schema[].properties[]" + .to_string() + })?; let schema0 = schema_seq .first() .and_then(|v| v.as_mapping()) - .ok_or_else(|| "ODCS 'schema' array is empty or not a mapping".to_string())?; + .ok_or_else(|| { + "ODCS 'schema' array is empty or its first entry is not a mapping".to_string() + })?; - // Contract name: dataProduct › schema[0].name › root name. + // Contract name: dataProduct › schema[0].name › root name (the order + // existing imports already use). let name = doc .get("dataProduct") .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) .or_else(|| schema0.get("name").and_then(|v| v.as_str())) .or_else(|| doc.get("name").and_then(|v| v.as_str())) .unwrap_or("imported_contract") @@ -776,14 +890,43 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result let description = description_text(doc.get("description")) .or_else(|| description_text(schema0.get("description"))); - let (entities, quality) = - if let Some(props) = schema0.get("properties").and_then(|v| v.as_sequence()) { - let fields = unflatten_odcs_properties(props)?; - let rules = extract_quality_rules_from_props(props); - (fields, rules) - } else { - (vec![], vec![]) - }; + let props = schema0 + .get("properties") + .and_then(|v| v.as_sequence()) + .filter(|p| !p.is_empty()) + .ok_or_else(|| { + format!( + "ODCS schema[0] ('{}') has no properties; nothing to validate. \ + Add schema[0].properties[] with a name and logicalType per field", + schema0.get("name").and_then(|v| v.as_str()).unwrap_or("?") + ) + })?; + let entities = unflatten_odcs_properties(props)?; + let quality = extract_quality_rules_from_props(props); + + let mut warnings = Vec::new(); + if schema_seq.len() > 1 { + let used = schema0 + .get("name") + .and_then(|v| v.as_str()) + .unwrap_or("schema[0]"); + let skipped: Vec<&str> = schema_seq + .iter() + .skip(1) + .map(|s| { + s.as_mapping() + .and_then(|m| m.get("name")) + .and_then(|v| v.as_str()) + .unwrap_or("?") + }) + .collect(); + warnings.push(format!( + "ODCS schema has {} objects; imported '{}' (schema[0]) and ignored: {}", + schema_seq.len(), + used, + skipped.join(", ") + )); + } let compliance_mode = root_extension(doc, "x-contractgate-compliance-mode") .and_then(|v| v.as_bool()) @@ -814,6 +957,7 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result version, yaml_content, import_source: ImportSource::OdcsStripped, + warnings, }) } @@ -822,6 +966,11 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result /// uniqueness rule when `quality[]` didn't already declare one. fn extract_quality_rules_from_props(props: &[Value]) -> Vec { let mut all_rules: Vec = Vec::new(); + let pk_count = props + .iter() + .filter_map(|p| p.as_mapping()) + .filter(|m| m.get("primaryKey").and_then(|v| v.as_bool()) == Some(true)) + .count(); for p in props { let Some(m) = p.as_mapping() else { continue }; let Some(name) = m.get("name").and_then(|v| v.as_str()) else { @@ -832,7 +981,10 @@ fn extract_quality_rules_from_props(props: &[Value]) -> Vec { .and_then(|v| v.as_sequence()) .map(|q| odcs_quality_to_rules(name, q)) .unwrap_or_default(); - let unique = m.get("unique").and_then(|v| v.as_bool()) == Some(true); + // `primaryKey` on its own implies unique when it is the only key + // column; a composite key has no single-column uniqueness. + let unique = m.get("unique").and_then(|v| v.as_bool()) == Some(true) + || (m.get("primaryKey").and_then(|v| v.as_bool()) == Some(true) && pk_count == 1); if unique && !rules .iter() @@ -996,11 +1148,21 @@ fn odcs_prop_to_field(m: &Mapping, full_name: &str) -> Result logical_to_field_type(l), + None => m + .get("physicalType") + .and_then(|v| v.as_str()) + .map(physical_to_field_type) + .unwrap_or(FieldType::String), + }; - let required = m.get("required").and_then(|v| v.as_bool()).unwrap_or(false); + // A primary key column is never null. + let required = m.get("required").and_then(|v| v.as_bool()).unwrap_or(false) + || m.get("primaryKey").and_then(|v| v.as_bool()) == Some(true); // ── ODCS-native constraints ────────────────────────────────────────────── let opts = m.get("logicalTypeOptions").and_then(|v| v.as_mapping()); diff --git a/src/storage/contracts.rs b/src/storage/contracts.rs index 8eac0d14..9c357824 100644 --- a/src/storage/contracts.rs +++ b/src/storage/contracts.rs @@ -336,7 +336,10 @@ pub async fn create_contract_in( // (RFC-004: YAML is authoritative; column is a denormalization for // SQL-level filtering). // The first version row is always 1.0.0; the stored YAML says the same. - let yaml_owned = crate::version_pin::set_yaml_version(yaml_content, "1.0.0"); + // ODCS v3.x input is converted to native contract YAML before it is stored. + let (yaml_native, _odcs_notes) = crate::odcs::normalize_contract_yaml(yaml_content) + .map_err(AppError::InvalidContractYaml)?; + let yaml_owned = crate::version_pin::set_yaml_version(&yaml_native, "1.0.0"); let yaml_content = yaml_owned.as_str(); let parsed: Contract = serde_yaml::from_str(yaml_content) .map_err(|e| AppError::InvalidContractYaml(e.to_string()))?; @@ -708,8 +711,11 @@ pub async fn create_version_in( org_id: Option, self_hosted: bool, ) -> AppResult { + // ODCS v3.x input is converted to native contract YAML before it is stored. + let (yaml_native, _odcs_notes) = crate::odcs::normalize_contract_yaml(yaml_content) + .map_err(AppError::InvalidContractYaml)?; // The stored YAML's `version:` always matches the version row. - let yaml_owned = crate::version_pin::set_yaml_version(yaml_content, version); + let yaml_owned = crate::version_pin::set_yaml_version(&yaml_native, version); let yaml_content = yaml_owned.as_str(); let parsed: Contract = serde_yaml::from_str(yaml_content) .map_err(|e| AppError::InvalidContractYaml(e.to_string()))?; @@ -776,6 +782,10 @@ pub async fn patch_version_yaml( // DB trigger `contract_versions_compliance_mode_guard` will reject any // change to `compliance_mode` once the version leaves draft, so this is // safe to always bind (RFC-004). + // ODCS v3.x input is converted to native contract YAML before it is stored. + let (yaml_native, _odcs_notes) = crate::odcs::normalize_contract_yaml(yaml_content) + .map_err(AppError::InvalidContractYaml)?; + let yaml_content = yaml_native.as_ref(); let parsed: Contract = serde_yaml::from_str(yaml_content) .map_err(|e| AppError::InvalidContractYaml(e.to_string()))?; let compliance_mode = parsed.compliance_mode; @@ -936,6 +946,10 @@ pub async fn deploy_contract_version_in( self_hosted: bool, ) -> AppResult<(ContractVersion, i64)> { // Parse YAML and extract version — fail fast before touching the DB. + // ODCS v3.x input is converted to native contract YAML before it is stored. + let (yaml_native, _odcs_notes) = crate::odcs::normalize_contract_yaml(yaml_content) + .map_err(AppError::InvalidContractYaml)?; + let yaml_content = yaml_native.as_ref(); let parsed: crate::contract::Contract = serde_yaml::from_str(yaml_content) .map_err(|e| AppError::InvalidContractYaml(e.to_string()))?; let version = parsed.version.clone(); diff --git a/src/synth.rs b/src/synth.rs index 57ad188e..15102912 100644 --- a/src/synth.rs +++ b/src/synth.rs @@ -199,7 +199,7 @@ pub fn generate( /// Parse and compile contract YAML, mapping failures to a `contract` rule error. pub fn compile_yaml(yaml: &str) -> Result { - let contract: Contract = serde_yaml::from_str(yaml) + let contract: Contract = crate::odcs::parse_contract_yaml(yaml) .map_err(|e| SynthError::new("contract", None, format!("invalid contract YAML: {e}")))?; CompiledContract::compile(contract) .map_err(|e| SynthError::new("contract", None, format!("contract does not compile: {e}"))) diff --git a/tests/fixtures/odcs/full-example.odcs.yaml b/tests/fixtures/odcs/full-example.odcs.yaml new file mode 100644 index 00000000..f1c072bd --- /dev/null +++ b/tests/fixtures/odcs/full-example.odcs.yaml @@ -0,0 +1,362 @@ +# Copyright 2026 The Bitol Contributors +# SPDX-License-Identifier: Apache-2.0 + +# What's this data contract about? +domain: seller # Domain +dataProduct: my quantum # Data product name +version: 1.1.0 # Version (follows semantic versioning) +status: active +id: 53581432-6c55-4ba2-a65f-72344a91553a + +authoritativeDefinitions: +- type: canonical + url: https://github.com/bitol-io/open-data-contract-standard/blob/main/docs/examples/all/full-example.odcs.yaml + description: Canonical URL to the latest version of the contract. + +# Lots of information +description: + purpose: Views built on top of the seller tables. + limitations: Data based on seller perspective, no buyer information + usage: Predict sales over time + authoritativeDefinitions: + - type: privacy-statement + url: https://example.com/gdpr.pdf +tenant: ClimateQuantumInc + +kind: DataContract +apiVersion: v3.2.0 # Standard version (follows semantic versioning) + +# Infrastructure & servers +servers: + - server: my-postgres + type: postgres + host: localhost + port: 5432 + database: pypl-edw + schema: pp_access_views + +# Dataset, schema, and quality +schema: + - id: tbl_obj + name: tbl + physicalName: tbl_1 + physicalType: table + businessName: Core Payment Metrics + description: Provides core payment metrics + authoritativeDefinitions: + - url: https://catalog.data.gov/dataset/air-quality + type: businessDefinition + - url: https://youtu.be/jbY1BKFj9ec + type: videoTutorial + tags: [ 'finance', 'payments'] + dataGranularityDescription: Aggregation on columns txn_ref_dt, pmt_txn_id + # Schema-level relationships (for composite keys) + relationships: + - type: foreignKey + from: + - tbl.rcvr_id + - tbl.rcvr_cntry_code + to: + - receivers.id + - receivers.country_code + customProperties: + - property: description + value: "Composite key linking to receivers table" + - property: cardinality + value: "many-to-one" + properties: + - id: txn_ref_dt_prop + name: transaction_reference_date + physicalName: txn_ref_dt + primaryKey: false + primaryKeyPosition: -1 + businessName: transaction reference date + logicalType: date + physicalType: date + required: false + description: Reference date for transaction + partitioned: true + partitionKeyPosition: 1 + criticalDataElement: false + tags: [ ] + classification: public + transformSourceObjects: + - table_name_1 + - table_name_2 + - table_name_3 + transformLogic: sel t1.txn_dt as txn_ref_dt from table_name_1 as t1, table_name_2 as t2, table_name_3 as t3 where t1.txn_dt=date-3 + transformDescription: defines the logic in business terms; logic for dummies + examples: + - "2022-10-03" + - "2020-01-28" + customProperties: + - property: anonymizationStrategy + value: none + - id: rcvr_id_prop + name: rcvr_id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver id + logicalType: string + physicalType: varchar(18) + required: false + description: A description for column rcvr_id. + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ 'uid' ] + classification: restricted + # Property-level relationship (from is implicit) + relationships: + - to: receivers.id + type: foreignKey + customProperties: + - property: description + value: "Links to receiver master data" + - id: rcvr_cntry_code_prop + name: rcvr_cntry_code + primaryKey: false + primaryKeyPosition: -1 + businessName: receiver country code + logicalType: string + physicalType: varchar(2) + required: false + description: Country code + partitioned: false + partitionKeyPosition: -1 + criticalDataElement: false + tags: [ ] + classification: public + # Enumeration of allowed values (RFC 0033, ODCS v3.2.0+) + enum: + - value: US + label: United States + description: ISO 3166-1 alpha-2 code for the United States. + - value: CA + label: Canada + - value: MX + label: Mexico + customProperties: + - property: languageEs + value: México + authoritativeDefinitions: + - url: https://collibra.com/asset/742b358f-71a5-4ab1-bda4-dcdba9418c25 + type: businessDefinition + - url: https://github.com/myorg/myrepo + type: transformationImplementation + - url: jdbc:postgresql://localhost:5432/adventureworks/tbl_1/rcvr_cntry_code + type: implementation + encryptedName: rcvr_cntry_code_encrypted + quality: + - metric: nullValues + mustBe: 0 + description: column should not contain null values + dimension: completeness + type: library + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: FIELD_NAME + value: + - property: COMPARE_TO + value: + - property: COMPARISON_TYPE + value: Greater than + quality: + - metric: rowCount + mustBeGreaterThan: 1000000 + type: library + description: Ensure row count is within expected volume range + dimension: completeness + method: reconciliation + severity: error + businessImpact: operational + schedule: 0 20 * * * + scheduler: cron + customProperties: + - property: business-key + value: + - txn_ref_dt + - rcvr_id + + # Receivers master table + - id: receivers_obj + name: receivers + physicalName: receivers_master + physicalType: table + businessName: Receivers Master Data + description: Master data for all receivers + tags: [ 'master-data', 'receivers' ] + properties: + - id: receiver_id_prop + name: id + primaryKey: true + primaryKeyPosition: 1 + businessName: receiver identifier + logicalType: string + physicalType: varchar(18) + required: true + description: Unique identifier for receiver + unique: true + classification: restricted + - id: country_code_prop + name: country_code + primaryKey: true + primaryKeyPosition: 2 + businessName: receiver country + logicalType: string + physicalType: varchar(2) + required: true + description: Country code of the receiver + classification: public + - id: receiver_name_prop + name: receiver_name + businessName: receiver name + logicalType: string + physicalType: varchar(255) + required: true + description: Name of the receiver + classification: restricted + - id: receiver_type_prop + name: receiver_type + businessName: receiver type + logicalType: string + physicalType: varchar(20) + required: false + description: Type of receiver (individual, business, etc.) + classification: public + # Example of nested reference + relationships: + - to: receiver_types.type_code + customProperties: + - property: description + value: "Links to receiver type definitions" + # Map-typed property (RFC 0030, ODCS v3.2.0+) + - id: receiver_attributes_prop + name: receiver_attributes + businessName: receiver attributes + logicalType: map + physicalType: "MAP" + required: false + description: Free-form attributes attached to a receiver, keyed by attribute name. + classification: restricted + map: + key: + logicalType: string + description: Attribute name. + value: + logicalType: string + description: Attribute value. + + +# Pricing +price: + priceAmount: 9.95 + priceCurrency: USD + priceUnit: megabyte + + +# Team +team: + name: my-team + description: The team owning the data contract + members: + - username: ceastwood + role: Data Scientist + dateIn: "2022-08-02" + dateOut: "2022-10-01" + replacedByUsername: mhopper + - username: mhopper + role: Data Scientist + dateIn: "2022-10-01" + - username: daustin + role: Owner + description: Keeper of the grail + dateIn: "2022-10-01" + + +# Roles +roles: + - role: microstrategy_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mandolorian' + - role: bq_queryman_user_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: na + - role: risk_data_access_opr + access: read + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'dathvador' + - role: bq_unica_user_opr + access: write + firstLevelApprovers: Reporting Manager + secondLevelApprovers: 'mickey' + +# SLA +slaProperties: + - property: latency # Property, see list of values in DP QoS + value: 4 + unit: d # d, day, days for days; y, yr, years for years + element: tab1.txn_ref_dt # This would not be needed as it is the same table.column as the default one + - property: generalAvailability + value: "2022-05-12T09:30:10-08:00" + - property: endOfSupport + value: "2032-05-12T09:30:10-08:00" + - property: endOfLife + value: "2042-05-12T09:30:10-08:00" + - property: retention + value: 3 + unit: y + element: tab1.txn_ref_dt + - property: frequency + value: 1 + valueExt: 1 + unit: d + element: tab1.txn_ref_dt + - property: timeOfAvailability + value: 09:00-08:00 + element: tab1.txn_ref_dt + driver: regulatory # Describes the importance of the SLA: [regulatory|analytics|operational|...] + - property: timeOfAvailability + value: 08:00-08:00 + element: tab1.txn_ref_dt + driver: analytics + + +# Support +support: + - channel: '#product-help' # Simple Slack communication channel + tool: slack + - channel: datacontract-ann # Simple distribution list + tool: email + url: mailto:datacontract-ann@bitol.io + - channel: Feedback # Product Feedback + description: General Product Feedback (Public) + url: https://product-feedback.com + - channel: 'product-issues' + tool: teams + scope: issues + customProperties: + - property: servicehours + value: 9-5 CET + + +# Tags +tags: + - transactions + + +# Custom properties +customProperties: + - property: refRulesetName + value: gcsc.ruleset.name + - property: somePropertyName + value: property.value + - property: dataprocClusterName # Used for specific applications like Elevate + value: [ cluster name ] + +contractCreatedTs: "2022-11-15T02:59:43+00:00" diff --git a/tests/fixtures/odcs/minimal-no-ontology.odcs.yaml b/tests/fixtures/odcs/minimal-no-ontology.odcs.yaml new file mode 100644 index 00000000..87ce5996 --- /dev/null +++ b/tests/fixtures/odcs/minimal-no-ontology.odcs.yaml @@ -0,0 +1,24 @@ +apiVersion: v3.2.0 +kind: DataContract +id: 11111111-2222-3333-4444-555555555555 +name: orders +version: 1.0.0 +status: active +description: + purpose: Minimal orders contract +schema: + - name: orders + physicalType: table + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: amount + logicalType: number + required: true + logicalTypeOptions: + minimum: 0 + - name: status + logicalType: string + enum: [open, closed] diff --git a/tests/odcs_compat.rs b/tests/odcs_compat.rs new file mode 100644 index 00000000..bf2afe89 --- /dev/null +++ b/tests/odcs_compat.rs @@ -0,0 +1,234 @@ +//! ODCS v3.x documents work with `validate` and `synth` without an +//! `ontology` block (bug report from the Bitol community Slack). + +use contractgate::cli::{ + commands::validate::{run, ValidateArgs}, + config::CliConfig, +}; +use contractgate::contract::{Contract, FieldType}; +use contractgate::odcs::{ + normalize_contract_yaml, parse_contract_yaml, parse_contract_yaml_with_notes, +}; +use contractgate::synth::{self, SynthMode, SynthOptions}; +use contractgate::validation::{validate, CompiledContract}; + +const MINIMAL: &str = include_str!("fixtures/odcs/minimal-no-ontology.odcs.yaml"); +const FULL: &str = include_str!("fixtures/odcs/full-example.odcs.yaml"); + +fn opts(mode: SynthMode) -> SynthOptions { + SynthOptions { + rows: 25, + mode, + seed: 7, + now_unix: 1_780_000_000, + } +} + +/// Every valid row must pass the validator; every invalid row must fail. +fn assert_synth_round_trips(yaml: &str) -> usize { + let compiled = synth::compile_yaml(yaml).expect("compiles"); + let out = synth::generate(&compiled, &opts(SynthMode::Valid)).expect("valid rows"); + assert_eq!(out.rows.len(), 25); + for row in &out.rows { + let r = validate(&compiled, row); + assert!(r.passed, "row {row} failed: {:?}", r.violations); + } + let bad = synth::generate(&compiled, &opts(SynthMode::Invalid)).expect("invalid rows"); + assert!(!bad.invalid_rows.is_empty()); + for r in bad + .invalid_rows + .iter() + .filter(|r| r.broken_rule.rule != "uniqueness") + { + // (uniqueness is a batch rule; a single row cannot show it) + assert!( + !validate(&compiled, &r.record).passed, + "{:?}", + r.broken_rule + ); + } + out.rows.len() +} + +#[test] +fn minimal_odcs_without_ontology_parses_and_synths() { + let c = parse_contract_yaml(MINIMAL).expect("parses"); + assert_eq!(c.name, "orders"); + assert_eq!(c.version, "1.0.0"); + assert_eq!(c.description.as_deref(), Some("Minimal orders contract")); + let names: Vec<_> = c + .ontology + .entities + .iter() + .map(|f| f.name.as_str()) + .collect(); + assert_eq!(names, ["order_id", "amount", "status"]); + assert!(c.ontology.entities[0].required); + assert_eq!(c.ontology.entities[1].field_type, FieldType::Float); + assert_eq!(c.ontology.entities[1].min, Some(0.0)); + assert!(c.ontology.entities[2].allowed_values.is_some()); + assert_synth_round_trips(MINIMAL); +} + +#[test] +fn official_full_example_parses_and_synths() { + let (c, notes) = parse_contract_yaml_with_notes(FULL).expect("parses"); + // description is a map (purpose/limitations/usage) in ODCS 3.x. + assert_eq!( + c.description.as_deref(), + Some("Views built on top of the seller tables.") + ); + // schema[0] only; the second object is reported, not silently dropped. + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].contains("receivers"), "{notes:?}"); + let cc = c + .ontology + .entities + .iter() + .find(|f| f.name == "rcvr_cntry_code") + .expect("enum field"); + assert_eq!(cc.allowed_values.as_ref().map(Vec::len), Some(3)); + assert_eq!( + c.ontology + .entities + .iter() + .find(|f| f.name == "transaction_reference_date") + .map(|f| &f.field_type), + Some(&FieldType::Date) + ); + // primaryKey implies required. + assert!( + c.ontology + .entities + .iter() + .find(|f| f.name == "rcvr_id") + .unwrap() + .required + ); + assert_synth_round_trips(FULL); +} + +#[test] +fn native_yaml_is_returned_unchanged() { + let native = include_str!("../examples/contracts/api/user_events.yaml"); + let (out, notes) = normalize_contract_yaml(native).unwrap(); + assert!(matches!(out, std::borrow::Cow::Borrowed(_))); + assert!(notes.is_empty()); +} + +#[test] +fn native_contract_without_ontology_still_parses() { + let c: Contract = + serde_yaml::from_str("version: '1.0'\nname: bare\n").expect("ontology optional"); + assert!(c.ontology.entities.is_empty()); +} + +#[test] +fn native_description_may_be_a_map() { + let c: Contract = serde_yaml::from_str( + "version: '1.0'\nname: d\ndescription:\n purpose: why\n usage: how\nontology:\n entities: []\n", + ) + .unwrap(); + assert_eq!(c.description.as_deref(), Some("why")); +} + +#[test] +fn unknown_odcs_fields_are_ignored() { + let y = r#" +apiVersion: v3.1.0 +kind: DataContract +version: 2 +name: tolerant +someFutureKey: {a: 1} +team: {name: x} +schema: + - name: t + futureThing: true + properties: + - name: id + logicalType: integer + primaryKey: true + brandNew: [1, 2] + - name: attrs + logicalType: map + map: {key: {logicalType: string}, value: {logicalType: string}} + - name: price + physicalType: DECIMAL(10,2) + - name: label + physicalType: varchar(20) +"#; + let c = parse_contract_yaml(y).expect("parses"); + assert_eq!(c.version, "2"); + let t = |n: &str| { + c.ontology + .entities + .iter() + .find(|f| f.name == n) + .unwrap() + .field_type + .clone() + }; + assert_eq!(t("id"), FieldType::Integer); + assert_eq!(t("attrs"), FieldType::Object); + assert_eq!(t("price"), FieldType::Float); + assert_eq!(t("label"), FieldType::String); + // A single-column primary key is unique. + assert!(c + .quality + .iter() + .any(|q| q.field == "id" && format!("{:?}", q.rule_type) == "Uniqueness")); + assert_synth_round_trips(y); +} + +#[test] +fn unsupported_documents_get_clear_errors() { + let err = + parse_contract_yaml("apiVersion: v2.2.2\nkind: DataContract\nversion: 1\nschema: []\n") + .unwrap_err(); + assert!(err.contains("unsupported ODCS apiVersion"), "{err}"); + + let err = parse_contract_yaml( + "dataContractSpecification: 1.2.0\nid: x\ninfo: {title: t, version: 1.0.0}\nmodels: {}\n", + ) + .unwrap_err(); + assert!(err.contains("Data Contract Specification"), "{err}"); + + let err = + parse_contract_yaml("apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\n") + .unwrap_err(); + assert!(err.contains("no 'schema' array"), "{err}"); + + let err = parse_contract_yaml( + "apiVersion: v3.1.0\nkind: DataContract\nname: n\nversion: 1.0.0\nschema:\n - name: t\n", + ) + .unwrap_err(); + assert!(err.contains("no properties"), "{err}"); + + let err = parse_contract_yaml( + "apiVersion: v3.1.0\nkind: DataContract\nname: n\nschema:\n - name: t\n properties:\n - name: a\n", + ) + .unwrap_err(); + assert!(err.contains("'version'"), "{err}"); +} + +#[test] +fn validate_command_accepts_odcs_directory() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("datacontract.yaml"), MINIMAL).unwrap(); + std::fs::write(tmp.path().join("full.yaml"), FULL).unwrap(); + let args = ValidateArgs { + dir: Some(tmp.path().to_path_buf()), + json: false, + }; + assert_eq!(run(&args, &CliConfig::default()).unwrap(), 0); +} + +#[test] +fn compiled_odcs_contract_validates_events() { + let c = parse_contract_yaml(MINIMAL).unwrap(); + let compiled = CompiledContract::compile(c).unwrap(); + let good = serde_json::json!({"order_id": "a", "amount": 3.5, "status": "open"}); + assert!(validate(&compiled, &good).passed); + let bad = serde_json::json!({"order_id": "a", "amount": -1, "status": "weird"}); + assert!(!validate(&compiled, &bad).passed); +} From 807809301b68afe573d06b9d1bd61c383218f4f2 Mon Sep 17 00:00:00 2001 From: ContractGate Lead Date: Thu, 26 Nov 2026 08:24:55 -0500 Subject: [PATCH 2/2] fix: detect ODCS from top-level keys instead of a second YAML parse --- src/odcs.rs | 79 ++++++++++++++++++++++++++------------------ tests/odcs_compat.rs | 8 +++++ 2 files changed, 54 insertions(+), 33 deletions(-) diff --git a/src/odcs.rs b/src/odcs.rs index b4dffb89..08518e13 100644 --- a/src/odcs.rs +++ b/src/odcs.rs @@ -737,23 +737,53 @@ pub fn import_odcs(yaml: &str) -> Result { } } -/// True when a parsed YAML document is an ODCS data contract rather than a -/// native DataContractGate contract: no `ontology`, and an `apiVersion: v3.x`, -/// `kind: DataContract`, or a `schema` list. -pub fn looks_like_odcs(doc: &Value) -> bool { - let Some(m) = doc.as_mapping() else { - return false; - }; - if m.contains_key("ontology") { +/// Top-level (column 0) `key: value` pairs of a block-style YAML document. +/// A flow-style (`{...}`) document yields no keys here. +fn top_level_pairs(yaml: &str) -> Vec<(&str, &str)> { + yaml.lines() + .filter(|l| { + l.chars() + .next() + .is_some_and(|c| !c.is_whitespace() && c != '#' && c != '-') + }) + .filter_map(|l| { + let (k, v) = l.split_once(':')?; + let k = k.trim().trim_matches(['"', '\'']); + let v = v + .split(" #") + .next() + .unwrap_or("") + .trim() + .trim_matches(['"', '\'']); + Some((k, v)) + }) + .collect() +} + +/// True when the document is an ODCS data contract rather than a native +/// DataContractGate contract: no top-level `ontology`, and an `apiVersion: +/// v3.x`, `kind: DataContract`, a `schema` list or a Data Contract +/// Specification header. Read from the top-level keys, so native YAML on hot +/// paths is not parsed twice. +fn looks_like_odcs(yaml: &str) -> bool { + let flow = yaml.trim_start().starts_with('{'); + if flow { + // JSON-style document: look for the quoted keys. + return !yaml.contains("\"ontology\"") + && (yaml.contains("\"apiVersion\"") + || yaml.contains("\"schema\"") + || yaml.contains("\"dataContractSpecification\"")); + } + let pairs = top_level_pairs(yaml); + if pairs.iter().any(|(k, _)| *k == "ontology") { return false; } - let api_v3 = m - .get("apiVersion") - .and_then(|v| v.as_str()) - .is_some_and(|v| v.starts_with("v3")); - let kind = m.get("kind").and_then(|v| v.as_str()) == Some("DataContract"); - let schema = m.get("schema").is_some_and(|v| v.is_sequence()); - api_v3 || kind || schema + pairs.iter().any(|(k, v)| match *k { + "apiVersion" => v.starts_with("v3"), + "kind" => *v == "DataContract", + "schema" | "dataContractSpecification" => true, + _ => false, + }) } /// Accept native DataContractGate YAML or an ODCS v3.x document and return @@ -762,24 +792,7 @@ pub fn looks_like_odcs(doc: &Value) -> bool { pub fn normalize_contract_yaml( yaml: &str, ) -> Result<(std::borrow::Cow<'_, str>, Vec), String> { - // Cheap pre-check so native YAML on hot paths is not parsed twice. - let maybe_odcs = yaml.contains("apiVersion") - || yaml.contains("DataContract") - || yaml.contains("schema:") - || yaml.contains("dataContractSpecification"); - if !maybe_odcs { - return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); - } - let doc: Value = match serde_yaml::from_str(yaml) { - Ok(d) => d, - // Leave YAML syntax errors to the caller's native parse so the - // message and line numbers stay what they were. - Err(_) => return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())), - }; - let spec = doc.as_mapping().is_some_and(|m| { - m.contains_key("dataContractSpecification") && !m.contains_key("ontology") - }); - if !looks_like_odcs(&doc) && !spec { + if !looks_like_odcs(yaml) { return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); } let r = import_odcs(yaml).map_err(|e| format!("ODCS import: {e}"))?; diff --git a/tests/odcs_compat.rs b/tests/odcs_compat.rs index bf2afe89..3da98925 100644 --- a/tests/odcs_compat.rs +++ b/tests/odcs_compat.rs @@ -232,3 +232,11 @@ fn compiled_odcs_contract_validates_events() { let bad = serde_json::json!({"order_id": "a", "amount": -1, "status": "weird"}); assert!(!validate(&compiled, &bad).passed); } + +#[test] +fn json_style_odcs_is_detected() { + let y = r#"{"apiVersion":"v3.1.0","kind":"DataContract","version":"1.0.0","name":"j", + "schema":[{"name":"t","properties":[{"name":"id","logicalType":"integer","required":true}]}]}"#; + let c = parse_contract_yaml(y).expect("parses"); + assert_eq!(c.ontology.entities.len(), 1); +}