diff --git a/ROADMAP.md b/ROADMAP.md index c0b077c6..df5d426b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -352,12 +352,12 @@ Ossie standardizes structural and logical semantics well, but there is limited s **Roadmap Deliverables:** - [Extended Metadata Proposal for Ossie](https://github.com/apache/ossie/issues/100) — optional, backward-compatible metadata fields (e.g., `measurement`, `display_format`, `semantic_type`, `default_aggregation`, `desired_direction`, `default_sort`, `semantic_mappings`) -- Richer application-specific extension points beyond `custom_extensions` +- Richer application-specific extension points beyond `nonportable_extensions` - Sample value annotations for documentation and AI grounding **Key Discussions:** -- [Expand custom_extensions to be more suitable for application-specific metadata](https://github.com/apache/ossie/discussions/30) +- [Expand custom_extensions to be more suitable for application-specific metadata](https://github.com/apache/ossie/discussions/30) (discussion title; the field is now `nonportable_extensions`) - [Sample values](https://github.com/apache/ossie/discussions/7) - [Governance metadata hooks](https://github.com/apache/ossie/discussions/13) *(also informs strategic governance work)* - [Optional "positive direction" on metrics](https://github.com/apache/ossie/discussions/41) @@ -435,4 +435,4 @@ Broad ecosystem adoption depends on practical tools that let teams validate thei **Related Issues:** - [Issue #121 — Create converter/common module (for Java binding)](https://github.com/apache/ossie/issues/121) -- [Issue #111 — Follow up on Ossie ai_context and custom_extensions mapping in Snowflake YAML](https://github.com/apache/ossie/issues/111) +- [Issue #111 — Follow up on Ossie ai_context and custom_extensions mapping in Snowflake YAML](https://github.com/apache/ossie/issues/111) (issue title; the field is now `nonportable_extensions`) diff --git a/core-spec/ossie-schema.json b/core-spec/ossie-schema.json index 5c1fcf4d..ac157411 100644 --- a/core-spec/ossie-schema.json +++ b/core-spec/ossie-schema.json @@ -28,8 +28,8 @@ "metrics": { "$ref": "#/$defs/SemanticModel/properties/metrics" }, - "custom_extensions": { - "$ref": "#/$defs/SemanticModel/properties/custom_extensions" + "nonportable_extensions": { + "$ref": "#/$defs/SemanticModel/properties/nonportable_extensions" } }, "required": ["version", "name", "datasets"], @@ -45,7 +45,7 @@ "type": "string", "minLength": 1, "examples": ["BI_TOOL", "DB_VENDOR", "SEMANTIC_LAYER"], - "description": "Vendor name for custom extensions. Any non-empty string is accepted. See extensions/vendors.md." + "description": "Vendor name for non-portable extensions. Any non-empty string is accepted. See extensions/vendors.md." }, "AIContext": { "description": "Additional context for AI tools", @@ -79,16 +79,16 @@ } ] }, - "CustomExtension": { + "NonportableExtension": { "type": "object", - "description": "Vendor-specific attributes for extensibility", + "description": "Vendor-specific state that Ossie carries and does not interpret. Portable behavior does not depend on it.", "properties": { "vendor_name": { "$ref": "#/$defs/Vendor" }, "data": { - "type": "string", - "description": "Opaque string of vendor-specific data that Ossie carries but does not interpret" + "type": "object", + "description": "Vendor-specific data as a structured object. The core schema does not reference the structure under data: no reserved key and no common sub-key. Keys are entirely vendor-defined. Values must be JSON-representable. Ossie carries the object but does not interpret it. See core-spec/spec.md#non-portable-extensions." } }, "required": ["vendor_name", "data"], @@ -147,7 +147,7 @@ "DateTimeTz", "Opaque" ], - "description": "Logical data type for fields and metrics, independent of role (e.g. dimension vs fact) and physical representation. `Decimal` is exact base-10 with unspecified precision and scale; `Float` is approximate. `DateTime` has no timezone or offset, while `DateTimeTz` identifies an instant using offset or timezone context but does not guarantee preservation of a named timezone. Omit `datatype` when unknown; use `Opaque` plus `custom_extensions` for a known type outside the portable vocabulary." + "description": "Logical data type for fields and metrics, independent of role (e.g. dimension vs fact) and physical representation. `Decimal` is exact base-10 with unspecified precision and scale; `Float` is approximate. `DateTime` has no timezone or offset, while `DateTimeTz` identifies an instant using offset or timezone context but does not guarantee preservation of a named timezone. Omit `datatype` when unknown. `Opaque` means the type is outside the portable vocabulary. A vendor may record its own type name under `nonportable_extensions`; that record is not part of the portable type." }, "Dimension": { "type": "object", @@ -189,10 +189,10 @@ "ai_context": { "$ref": "#/$defs/AIContext" }, - "custom_extensions": { + "nonportable_extensions": { "type": "array", "items": { - "$ref": "#/$defs/CustomExtension" + "$ref": "#/$defs/NonportableExtension" } } }, @@ -254,10 +254,10 @@ }, "description": "Dataset-scoped metrics: aggregations evaluated at this dataset's row level, for measures that semantically belong to the dataset. The expression references this dataset's declared fields by single-part (unqualified) name, and columns of the dataset's source as source.column. It must resolve entirely within this dataset; an expression that must reference another dataset belongs in the model-scoped metrics instead. Within the dataset, field names and metric names share one namespace and must all be unique across the two." }, - "custom_extensions": { + "nonportable_extensions": { "type": "array", "items": { - "$ref": "#/$defs/CustomExtension" + "$ref": "#/$defs/NonportableExtension" } } }, @@ -302,10 +302,10 @@ "ai_context": { "$ref": "#/$defs/AIContext" }, - "custom_extensions": { + "nonportable_extensions": { "type": "array", "items": { - "$ref": "#/$defs/CustomExtension" + "$ref": "#/$defs/NonportableExtension" } } }, @@ -334,10 +334,10 @@ "ai_context": { "$ref": "#/$defs/AIContext" }, - "custom_extensions": { + "nonportable_extensions": { "type": "array", "items": { - "$ref": "#/$defs/CustomExtension" + "$ref": "#/$defs/NonportableExtension" } } }, @@ -382,10 +382,10 @@ }, "description": "Model-scoped metrics: aggregations that span datasets or need to be aware of cross-dataset concepts. Expressions reference fields by multi-part name (dataset.field) and may combine fields from more than one dataset. Names must be unique across the model. See core-spec/spec.md#metric-scoping." }, - "custom_extensions": { + "nonportable_extensions": { "type": "array", "items": { - "$ref": "#/$defs/CustomExtension" + "$ref": "#/$defs/NonportableExtension" } } }, diff --git a/core-spec/relational_semantics.md b/core-spec/relational_semantics.md index 86789aa7..90761650 100644 --- a/core-spec/relational_semantics.md +++ b/core-spec/relational_semantics.md @@ -249,7 +249,7 @@ SQL-native names. The correspondence: | join relationship (Section 11.3) | `relationship` (`from`/`to`, `from_columns`/`to_columns`) | `from`/`to` map to source/target and the columns to the join predicate (`from` many, `to` one); Section 11.3 adds cardinality, roles, and arbitrary `ON`. | | Layer 1 expression | `OSSIE_SQL_2026` expression (`expression.sql`, or an `OSSIE_SQL_2026` entry in `dialects`) | The portable form of an Ossie expression, in the Layer 1 language (Section 1.1). For the resolution rules, see [Expression Object](spec.md#expression-object). | -Ossie model metadata this interface does not natively surface (`ai_context`, `custom_extensions`, +Ossie model metadata this interface does not natively surface (`ai_context`, `nonportable_extensions`, and non-selected expression dialects) is addressed under discovery (Section 11) and out of scope (Section 13.2). A conforming engine MUST preserve metric semantics: a metric evaluated via `AGG()` is computed from the model's metric definition (its aggregate and source rows), so two @@ -974,7 +974,7 @@ other. ASOF and range relationships, and `RELY` optimization hints, are future e Human- and AI-facing descriptors that have standard SQL-metadata homes (a field's or measure's label / display name, its description / comment, and its synonyms) SHOULD be surfaced through the engine's normal column and table metadata so tools can present them. Ossie annotations without -such a home (`ai_context` instructions and examples, and `custom_extensions`) are out of scope +such a home (`ai_context` instructions and examples, and `nonportable_extensions`) are out of scope for this interface (Section 13.2); an engine MAY surface them out-of-band. --- @@ -1055,7 +1055,7 @@ Deferred query and modeling features: direction is carried as discoverable hints (Sections 10.2, 11.3); part of Ossie's broader hints effort. - **Ossie annotations without a SQL-native home.** Ossie `ai_context` instructions and - examples, `custom_extensions`, and expression dialects other than the one selected for a + examples, `nonportable_extensions`, and expression dialects other than the one selected for a measure or field have no required representation in this interface and do not affect query semantics; an engine MAY surface them out-of-band (synonyms, labels, and descriptions do have a metadata home; Section 11.4). diff --git a/core-spec/spec.md b/core-spec/spec.md index 014ae5ce..561c8fa9 100644 --- a/core-spec/spec.md +++ b/core-spec/spec.md @@ -37,7 +37,7 @@ 4. [Relationships](#relationships) 5. [Fields](#fields) 6. [Metrics](#metrics) -7. [Custom Extensions](#custom-extensions) +7. [Non-portable Extensions](#non-portable-extensions) 8. [Name Resolution](#name-resolution) 9. [Complete Example](#complete-example) 10. [AI Context Structure](#ai-context-structure) @@ -82,7 +82,7 @@ ontology specification's built-in value types; `Time`, `DateTimeTz`, and | `Time` | Time-of-day with no date or timezone. | | `DateTime` | Local/civil date and time with no timezone or offset. | | `DateTimeTz` | Date and time with sufficient offset or timezone context to identify an instant. Preservation of a named timezone identifier is not guaranteed. | -| `Opaque` | Known type outside the portable vocabulary; use `custom_extensions` for vendor-specific refinement. Omit `datatype` when the type is unknown or unspecified. | +| `Opaque` | Known type outside the portable vocabulary. Omit `datatype` when the type is unknown or unspecified. A vendor may record its own type name under `nonportable_extensions`; that record is not part of the portable type. | ## Semantic Model @@ -103,7 +103,7 @@ not define a bundle format or cross-model references. | `datasets` | array | Yes | Collection of logical datasets (fact and dimension tables) | | `relationships` | array | No | Defines how logical datasets are connected | | `metrics` | array | No | Model-scoped metrics: for aggregations that span datasets or need to be aware of cross-dataset concepts. See [Metric Scoping](#metric-scoping). | -| `custom_extensions` | array | No | Vendor-specific attributes for extensibility | +| `nonportable_extensions` | array | No | Vendor-specific attributes for extensibility | ### Example @@ -118,9 +118,11 @@ datasets: source: sales.public.orders relationships: [] metrics: [] -custom_extensions: +nonportable_extensions: - vendor_name: DBT - data: '{"project_name": "tpcds_analytics", "models_path": "models/semantic"}' + data: + project_name: tpcds_analytics + models_path: models/semantic ``` The same document structure in JSON: @@ -145,10 +147,10 @@ or an object-valued wrapper. To migrate a document containing one model, move that model's properties to the root and remove `semantic_model`. Use `version: 0.3.0.dev0` for the migrated document. Remove any root-level `dialects` and `vendors` declarations; preserve -per-expression dialects and vendor information in `custom_extensions`. For +per-expression dialects and vendor information in `nonportable_extensions`. For multiple models, create one document per model and validate each result. An empty model array cannot produce a valid model document. Preserve model contents and -custom extensions; never silently select only the first model or overwrite a file +non-portable extensions; never silently select only the first model or overwrite a file when splitting a document. For [ontology maps](../ontology/ontology.md#ontology-mappings), each embedded @@ -172,7 +174,7 @@ Logical datasets represent business entities or concepts (fact and dimension tab | `ai_context` | string/object | No | Additional context for AI tools (e.g., synonyms, common terms) | | `fields` | array | No | Row-level attributes for grouping, filtering, and metric expressions | | `metrics` | array | No | Dataset-scoped metrics that semantically belong to this dataset; expressions reference its declared fields by single-part name and its source columns as `source.column`, and resolve entirely within it. See [Metric Scoping](#metric-scoping). | -| `custom_extensions` | array | No | Vendor-specific attributes | +| `nonportable_extensions` | array | No | Vendor-specific attributes | ### Primary Key Examples @@ -215,9 +217,10 @@ datasets: - name: order_number expression: sql: order_number - custom_extensions: + nonportable_extensions: - vendor_name: DBT - data: '{"materialized": "table"}' + data: + materialized: table ``` --- @@ -236,7 +239,7 @@ Relationships define how logical datasets are connected through foreign key cons | `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) | | `ai_context` | string/object | No | Additional context for AI tools | -| `custom_extensions` | array | No | Vendor-specific attributes | +| `nonportable_extensions` | array | No | Vendor-specific attributes | ### Important Notes @@ -288,7 +291,7 @@ Within a dataset, field names and dataset-scoped metric names share one namespac | `description` | string | No | Human-readable description | | `datatype` | string (enum) | No | Logical data type for this field. See [Data types](#data-types). | | `ai_context` | string/object | No | Additional context for AI tools (e.g., synonyms) | -| `custom_extensions` | array | No | Vendor-specific attributes | +| `nonportable_extensions` | array | No | Vendor-specific attributes | ### Expression Object @@ -423,7 +426,7 @@ Model-scoped metric expressions refer to dataset fields. Dataset-scoped metric e | `description` | string | No | Human-readable description of what the metric measures | | `datatype` | string (enum) | No | Logical data type for this metric. See [Data types](#data-types). | | `ai_context` | string/object | No | Additional context for AI tools (e.g., synonyms) | -| `custom_extensions` | array | No | Vendor-specific attributes | +| `nonportable_extensions` | array | No | Vendor-specific attributes | ### Expression Object @@ -543,22 +546,73 @@ datasets: --- -## Custom Extensions +## Non-portable Extensions -Custom extensions allow vendors to add platform-specific metadata without breaking core compatibility. Each extension includes a vendor name and arbitrary JSON data. +`nonportable_extensions` carries vendor-specific state for a round trip. Each entry +has a vendor name and a structured `data` object. This area is not portable Ossie +behavior. + +### Portability + +Nothing defined in this specification relies on any property in the extension area. +Core semantics are standalone. + +1. Core semantics MUST NOT depend on extensions. The core specification, the schema, + and compliance tests MUST define and validate portable behavior with the extension + area ignored. A conforming implementation MUST NOT need to read + `nonportable_extensions` to produce the behavior this specification defines. +2. Behavior defined only through extensions is non-portable and MUST NOT be presented + as portable Ossie behavior. +3. Producers SHOULD use core constructs wherever they can express the intended + semantics, rather than duplicating those concepts in extensions. + +The core schema never references the structure under `data`. It defines no reserved +key and no common sub-key. Keys under `data` are entirely vendor-defined. Vendor +schemas live outside core-spec. A schema or validator can check that a payload is +JSON. It cannot decide whether that payload means what its author intended. + +Consumers MUST preserve `data` they do not understand and MAY ignore it. ### Schema ```yaml -custom_extensions: +nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string # JSON string containing vendor-specific data + data: object # Vendor-defined keys; values must be JSON ``` +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `vendor_name` | string | Yes | Free-form identifier for the vendor or organization that owns the extension | +| `data` | object | Yes | Vendor-specific key/value data. May be empty (`{}`) | + +Values may be any JSON value: strings, numbers, booleans, `null`, arrays, or nested +objects. A `null` inside `data` is preserved as written, unlike optional core fields, +which are omitted when they are `null`. + +### JSON representability + +`data` MUST be representable as JSON. Keys are strings. Values are JSON values. + +YAML has pitfalls for interoperability with JSON, so quote defensively: quote any +scalar YAML would otherwise read as a boolean, a number, or a date. This table is +not exhaustive. + +| Written | What a loader may produce | +|---------|---------------------------| +| `yes`, `NO` | a boolean, or the string that was written | +| `true`, `false` | a boolean in YAML 1.1 and YAML 1.2 | +| `010` | the integer 8, or the integer 10 | +| `1e3` | the number 1000, or the string `1e3` | +| `2024-01-01` | a date, not the string `2024-01-01` | + +Quoted and unquoted examples are in +[extensions/nonportable_extensions.md](../extensions/nonportable_extensions.md). + ### Vendor Names The `vendor_name` field is a free-form string, allowing any vendor or organization to -define custom extensions without requiring changes to the core specification. +define non-portable extensions without requiring changes to the core specification. For a non-normative catalog of `vendor_name` values well-known tools use, see [extensions/vendors.md](../extensions/vendors.md). @@ -567,12 +621,15 @@ For a non-normative catalog of `vendor_name` values well-known tools use, see ```yaml - vendor_name: DB_VENDOR - data: '{"some_setting": "value", "nested": {"option": true}}' + data: + some_setting: value + nested: + option: true ``` -The `data` payload is an opaque string that Ossie carries but does not -interpret. For the known-vendor catalog, see -[extensions/vendors.md](../extensions/vendors.md). +The `data` payload is a structured object that Ossie carries but does not +interpret. For vendor-specific extension examples and the known-vendor catalog, +see [extensions/vendors.md](../extensions/vendors.md). --- @@ -762,9 +819,10 @@ metrics: description: Average revenue per customer datatype: Decimal -custom_extensions: +nonportable_extensions: - vendor_name: SNOWFLAKE - data: '{"warehouse": "ANALYTICS_WH"}' + data: + warehouse: ANALYTICS_WH ``` --- @@ -811,6 +869,7 @@ including rationale and migration impact for consumers, see the - **0.3.0.dev0** (Unreleased): In-development next minor release. Schema is mutable; do not depend on this version in production. - Replaces `0.2.0.dev0`: there is no 0.2.0 release. Documents that declare `version: 0.2.0.dev0` must declare `0.3.0.dev0`. + - Breaking: `custom_extensions` is renamed to `nonportable_extensions`. The old name is not accepted. `data` is an object, not a JSON-encoded string. A date, a timestamp, or a non-finite float under `data` is a schema error. See [Non-portable Extensions](#non-portable-extensions). - Breaking: each standalone document contains one model directly at the root; the `semantic_model` array is removed. - Breaking: metric expressions, `primary_key`, `unique_keys`, and relationship `from_columns`/`to_columns` refer to dataset fields, not columns of the dataset's `source`. Model-scoped metric expressions must use qualified `dataset.field` references; dataset-scoped metric expressions use unqualified field names. Earlier versions did not specify this, and some converters read these names as source columns; those converters must now resolve them as fields. See [Name Resolution](#name-resolution). - Dataset-scoped metric expressions may reference columns of the dataset's `source`, written as `source.column`. See [Metric Scoping](#metric-scoping). diff --git a/core-spec/spec.yaml b/core-spec/spec.yaml index bc17bdf9..5dfd4ba4 100644 --- a/core-spec/spec.yaml +++ b/core-spec/spec.yaml @@ -45,7 +45,7 @@ datatypes: - "DateTimeTz" # Instant identified using offset or timezone context - "Opaque" # Known type outside the portable vocabulary -# Vendor name for custom extensions (free-form string). +# Vendor name for non-portable extensions (free-form string). # See the known-vendor catalog in extensions/vendors.md. vendor_name: string @@ -88,9 +88,9 @@ metrics: [] # Optional: Vendor-specific attributes for extensibility # Allows vendors to add custom metadata without breaking core compatibility -custom_extensions: +nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string + data: object # Structured vendor-specific data; keys are vendor-defined --- # Logical Dataset Schema @@ -160,9 +160,9 @@ datasets: metrics: [] # Optional: Vendor-specific attributes for extensibility - custom_extensions: + nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string + data: object # Structured vendor-specific data; keys are vendor-defined --- # Relationship Schema @@ -203,9 +203,9 @@ relationships: ai_context: {} # see AIContext in ossie-schema.json # Optional: Vendor-specific attributes for extensibility - custom_extensions: + nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string + data: object # Structured vendor-specific data; keys are vendor-defined --- # Fields Schema @@ -252,7 +252,7 @@ fields: # Must be one of the values from the 'datatypes' enum above. # Decimal is exact base-10 with unspecified precision and scale; # Float is approximate. Omit datatype when unknown or unspecified. - # Use Opaque + custom_extensions for a known type outside the + # Use Opaque + nonportable_extensions for a known type outside the # portable vocabulary. datatype: string @@ -261,9 +261,9 @@ fields: ai_context: {} # see AIContext in ossie-schema.json # Optional: Vendor-specific attributes for extensibility - custom_extensions: + nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string + data: object # Structured vendor-specific data; keys are vendor-defined --- # Metrics Schema @@ -300,7 +300,7 @@ metrics: # Must be one of the values from the 'datatypes' enum above. # Decimal is exact base-10 with unspecified precision and scale; # Float is approximate. Omit datatype when unknown or unspecified. - # Use Opaque + custom_extensions for a known type outside the + # Use Opaque + nonportable_extensions for a known type outside the # portable vocabulary. datatype: string @@ -309,6 +309,6 @@ metrics: ai_context: {} # see AIContext in ossie-schema.json # Optional: Vendor-specific attributes for extensibility - custom_extensions: + nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string + data: object # Structured vendor-specific data; keys are vendor-defined diff --git a/core-spec/wide_table_semantics.md b/core-spec/wide_table_semantics.md index 59c1fddf..68b5c5d1 100644 --- a/core-spec/wide_table_semantics.md +++ b/core-spec/wide_table_semantics.md @@ -398,7 +398,7 @@ Conformance is semantic: each query must produce the specified rows or error. Bi An engine conforms if it satisfies Sections 3, 4, 5, and 8 through every binding it offers. It need not generate SQL text, but SHOULD expose its lowering, for example through `EXPLAIN`. -An engine MAY answer a query that this version rejects only when the query or the model requests that behavior explicitly, for example through an engine-defined query property or a `custom_extensions` entry. Otherwise, the engine MUST raise the error that Section 8 specifies. +An engine MAY answer a query that this version rejects only when the query or the model requests that behavior explicitly, for example through an engine-defined query property or a `nonportable_extensions` entry. That answer is not portable behavior defined by this specification, and conformance to Sections 3, 4, 5, and 8 does not depend on it. Otherwise, the engine MUST raise the error that Section 8 specifies. --- diff --git a/docs/index.md b/docs/index.md index 573cf1f0..e0c134c6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -56,7 +56,7 @@ The Ossie core specification (current version: **0.3.0.dev0**, latest released: | **Fields** | Row-level attributes for grouping, filtering, and metric expressions. Fields support multiple SQL dialects for cross-platform compatibility. | | **Relationships** | Foreign key connections between datasets, supporting both simple and composite keys. | | **Metrics** | Quantitative measures (sums, averages, ratios, etc.). A model-scoped metric's expression may combine fields from several datasets; a dataset-scoped metric aggregates one dataset's own fields at its row level. | -| **Custom Extensions** | Vendor-specific metadata stored as JSON, allowing platforms to carry additional information without breaking core compatibility. | +| **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. | An expression carries a primary, portable form in `OSSIE_SQL_2026` and may also carry vendor-specific variants. The `dialect` label is a free-form string, so expressions can be tailored to any platform while maintaining a common model structure. @@ -181,7 +181,7 @@ With N vendors, a point-to-point strategy would require **N×(N-1)** converters. A typical Ossie-based workflow looks like this: 1. **Author**: A semantic model is authored in one tool (e.g., dbt) or directly in the Ossie YAML format. -2. **Import**: If authored in a vendor tool, the vendor's import converter translates it into an Ossie model, preserving vendor-specific metadata in `custom_extensions`. +2. **Import**: If authored in a vendor tool, the vendor's import converter translates it into an Ossie model, preserving vendor-specific metadata in `nonportable_extensions`. 3. **Validate**: The Ossie model is validated against the [JSON Schema](../core-spec/ossie-schema.json) and the [validation script](../validation/validate.py) to ensure correctness. 4. **Exchange**: The Ossie model is shared — via Git, a data catalog, or a sync API — with other teams and tools. 5. **Export**: Each consuming tool's export converter translates the Ossie model into its native format, selecting the appropriate SQL dialect and applying vendor-specific extensions. @@ -216,7 +216,7 @@ A semantic model is a structured description of business data that defines what Most existing standards focus on data formats (e.g., Parquet, Arrow), query interfaces (e.g., ODBC, JDBC), or catalog metadata (e.g., Hive Metastore, OpenMetadata). Ossie focuses specifically on the *semantic layer* — the business meaning, metric definitions, and relationships that sit on top of raw data. It is complementary to these other standards rather than a replacement. **Is Ossie tied to any specific vendor?** -No. Ossie is vendor-agnostic by design. The specification is developed and governed by a community of contributors from many organizations. While vendor-specific metadata can be carried via `custom_extensions`, the core specification is neutral. +No. Ossie is vendor-agnostic by design. The specification is developed and governed by a community of contributors from many organizations. While vendor-specific metadata can be carried via `nonportable_extensions`, the core specification is neutral. ### Adoption @@ -238,7 +238,7 @@ Use the [validation script](../validation/validate.py) included in the repositor YAML is more human-readable and easier to author by hand, which is important for a specification that teams may edit directly. The Ossie JSON Schema is available for programmatic validation, and converters can work with either format. **How does Ossie handle vendor-specific features?** -Through `custom_extensions`. Each vendor can store arbitrary JSON metadata in extension blocks tagged with their vendor name. This metadata is preserved during round-trip conversions and ignored by tools that don't understand it — ensuring that no information is lost. +Through `nonportable_extensions`. Each vendor can store structured metadata, with any keys it chooses, in extension blocks tagged with its vendor name. Nothing in the core specification relies on those keys. The metadata is preserved on a round trip and ignored by tools that do not understand it. Behavior that exists only there is not portable Ossie behavior. Quoting details for values under `data` are in the [specification](../core-spec/spec.md#json-representability) and [nonportable_extensions.md](../extensions/nonportable_extensions.md). **Can metrics reference multiple datasets?** In the expression, only a model-scoped metric can — it uses multi-part `dataset.field` references and combines datasets. A dataset-scoped metric's expression stays within its own dataset. See [Metric Scoping](https://github.com/apache/ossie/blob/main/core-spec/spec.md#metric-scoping). @@ -273,7 +273,7 @@ The community is committed to minimizing breaking changes. When backward-incompa ### Extension Compatibility -Custom extensions (`custom_extensions`) are explicitly outside the scope of core compatibility guarantees. Vendors are responsible for maintaining compatibility within their own extension schemas. However, the core specification guarantees that `custom_extensions` blocks are always preserved during round-trip conversions, even by tools that do not understand them. +Non-portable extensions (`nonportable_extensions`) are outside core compatibility guarantees. Core semantics do not depend on them, and a vendor schema for `data` lives outside core-spec. Vendors maintain compatibility inside their own extension schemas. The core specification still requires that `nonportable_extensions` blocks be preserved on a round trip, even by tools that do not understand them. --- @@ -319,11 +319,11 @@ A practical guide for organizations looking to adopt Ossie. | **Metric** | A quantitative measure computed by aggregating fields (e.g., total revenue, average order value). A dataset-scoped metric is defined on an individual dataset, for a measure that semantically belongs to it and is evaluated at the dataset's row level; a model-scoped metric is defined at the model root and may span datasets. | | **Relationship** | A foreign key connection between two datasets, defining how they can be joined. Relationships are always many-to-one (from the referencing dataset to the referenced dataset). | | **Dialect** | A SQL or expression language variant an expression is written in (e.g., `ANSI_SQL`). A free-form string; `OSSIE_SQL_2026` is the only dialect Ossie defines, and all others are opaque. | -| **Custom Extension** | Vendor-specific metadata attached to any Ossie construct as an opaque string. Extensions allow platforms to carry additional information without modifying the core specification. | +| **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. | | **Converter** | A tool that translates between the Ossie format and a specific vendor's semantic model format. Converters come in pairs: import (vendor → Ossie) and export (Ossie → vendor). | | **Hub-and-Spoke** | The architectural pattern used by Ossie, where the specification acts as the central format (hub) and vendor converters act as spokes, avoiding the need for point-to-point integrations. | -| **Round-Trip Fidelity** | The ability to convert a model from one format to Ossie and back without losing information. Achieved by preserving vendor-specific metadata in `custom_extensions`. | +| **Round-Trip Fidelity** | The ability to convert a model from one format to Ossie and back without losing information. Achieved by preserving vendor-specific metadata in `nonportable_extensions`. | | **Fact Table** | A dataset that records business events or transactions (e.g., sales, clicks, shipments). Fact tables typically contain numeric measures and foreign keys to dimension tables. | | **Dimension Table** | A dataset that describes business entities referenced by fact tables (e.g., customers, products, dates). Dimension tables provide the context for analyzing facts. | | **Semantic Layer** | The abstraction layer between raw data and business users/tools. It defines the business meaning of data, standardizes metric calculations, and provides a consistent query interface. | diff --git a/docs/spec_changes.md b/docs/spec_changes.md index 853be839..64eaf6ac 100644 --- a/docs/spec_changes.md +++ b/docs/spec_changes.md @@ -48,6 +48,7 @@ the [current core specification](../core-spec/spec.md) and | 2026-10-26 | Core [#617](https://github.com/apache/ossie/pull/617) | **Portable `expression.sql` and open vendor dialect tokens.** The Ossie-defined portable expression becomes primary, while vendor-specific dialects stay opaque and extensible. | Existing `expression.dialects` remains accepted; writers should prefer `expression.sql` for portable SQL, and readers should give it precedence over a duplicate `OSSIE_SQL_2026` dialect entry. Dialect names are no longer a closed enum; consumers must tolerate unknown values. | | 2026-11-01 | Ontology [#668](https://github.com/apache/ossie/pull/668) | **Non-empty ontology identifiers.** Validation now rejects empty names, IRIs, references, and mapping SQL expressions, matching existing restrictions elsewhere. | Authors should supply non-empty values for identifying strings. Some malformed documents that previously passed schema validation now fail earlier, with schema-layer errors. | | 2026-11-09 | Core / Ontology [#691](https://github.com/apache/ossie/pull/691) | **Move the in-development version to `0.3.0.dev0`.** The next planned release is `0.3.0-incubating`; no `0.2.0` release is planned. | **Breaking for development documents.** Version constants in the current schemas reject `0.2.0.dev0`; producers must declare `0.3.0.dev0` and coordinate schema/package/converter versions. This is a development-version change, not a release announcement. | +| 2026-11-10 | Core [#522](https://github.com/apache/ossie/pull/522) | **Object `nonportable_extensions` data.** Vendor extension payloads become objects, and the field is renamed from `custom_extensions` so portable core semantics stay separate from vendor state. The core schema does not describe keys under `data`. | **Breaking within unreleased `0.3.0.dev0`.** Rename the field to `nonportable_extensions` and write `data` as an object, not a JSON string. The old name does not validate. Quote scalars under `data` that YAML may read as a boolean, number, or date. See [nonportable extensions](../extensions/nonportable_extensions.md). | ## Semi-automated discovery and upkeep diff --git a/examples/tpcds_semantic_model.yaml b/examples/tpcds_semantic_model.yaml index 644a3404..86b8dda6 100644 --- a/examples/tpcds_semantic_model.yaml +++ b/examples/tpcds_semantic_model.yaml @@ -592,22 +592,20 @@ metrics: - "MoM sales" - "sales delta" -custom_extensions: +nonportable_extensions: - vendor_name: SALESFORCE - data: | - { - "tableau_workbook_id": "tpcds_retail_dashboard", - "einstein_enabled": true, - "crm_sync": { - "enabled": true, - "sync_frequency": "daily", - "customer_mapping": "customer.c_customer_id -> Account.AccountNumber" - }, - "tableau_semantics": { - "published": true, - "version": "0.1.1" - } - } + data: + tableau_workbook_id: tpcds_retail_dashboard + einstein_enabled: true + crm_sync: + enabled: true + sync_frequency: daily + customer_mapping: "customer.c_customer_id -> Account.AccountNumber" + tableau_semantics: + published: true + version: "0.1.1" - vendor_name: DBT - data: '{"project_name": "tpcds_analytics", "models_path": "models/semantic"}' + data: + project_name: tpcds_analytics + models_path: models/semantic diff --git a/extensions/README.md b/extensions/README.md index c6792413..1da94299 100644 --- a/extensions/README.md +++ b/extensions/README.md @@ -21,7 +21,7 @@ The core specification ([`core-spec/`](../core-spec/)) is vendor-neutral. It defines one expression language, `OSSIE_SQL_2026`, and treats every other dialect -and every `custom_extensions` vendor as extension metadata that Ossie carries but +and every `nonportable_extensions` vendor as extension metadata that Ossie carries but does not interpret. This folder is where the community aligns on the meaning of specific dialect and @@ -39,4 +39,5 @@ case-sensitive, so register the canonical upper-case form (`SNOWFLAKE`, not |------|---------| | [`dialects.md`](dialects.md) | Dialect tokens used to declare metric and field expressions. | | [`dialects/`](dialects/) | References for individual dialects, such as [`pyiceberg.md`](dialects/pyiceberg.md). | -| [`vendors.md`](vendors.md) | `vendor_name` tokens, and the payload convention, for `custom_extensions`. | +| [`vendors.md`](vendors.md) | `vendor_name` tokens, and the payload convention, for `nonportable_extensions`. | +| [`nonportable_extensions.md`](nonportable_extensions.md) | What `nonportable_extensions` is, and quoted versus unquoted `data` values. | diff --git a/extensions/nonportable_extensions.md b/extensions/nonportable_extensions.md new file mode 100644 index 00000000..f1ed87e3 --- /dev/null +++ b/extensions/nonportable_extensions.md @@ -0,0 +1,120 @@ + + +# Non-portable extensions + +`nonportable_extensions` carries vendor-specific state for a round trip. Each +entry has a `vendor_name` and a `data` object. The core specification does not +interpret `data`, and portable Ossie behavior does not depend on it. + +Normative rules: [Non-portable Extensions](../core-spec/spec.md#non-portable-extensions) +in `core-spec/spec.md`. Vendor name tokens: +[vendors.md](vendors.md). The check described below is +`validation/validate.py`. + +## Quote scalars under `data` + +`data` must be JSON. Producers write it through a dumper that quotes +defensively, or quote any scalar YAML would otherwise read as a boolean, a +number, or a date. The examples below are what this repository's PyYAML loader +does. Other loaders disagree on some of the same spellings. + +### Dates, timestamps, and non-finite floats + +`validate.py` rejects a value under `data` that is not a JSON value after YAML +loads it. An unquoted date or timestamp becomes a date or timestamp object. The +YAML forms `.inf`, `-.inf`, and `.nan` become non-finite floats. Those are +schema errors. The same characters inside quotes stay strings and pass. + +Rejected: + +```yaml +nonportable_extensions: + - vendor_name: DB_VENDOR + data: + released: 2024-01-01 + stamped: 2024-01-01T00:00:00Z + ratio: .inf + missing: .nan +``` + +Accepted, because each value is a string: + +```yaml +nonportable_extensions: + - vendor_name: DB_VENDOR + data: + released: "2024-01-01" + stamped: "2024-01-01T00:00:00Z" + ratio: ".inf" + missing: "NaN" +``` + +Under this loader, a bare `NaN` or `Infinity` (no leading dot) stays a string, +so it is not the case the check rejects. The non-finite spellings it rejects +are `.nan`, `.inf`, and `-.inf`. + +### Booleans and integers that are still valid JSON + +`yes`, `NO`, `true`, `false`, and `010` also pass when quoted. Left unquoted +they still pass validation, but not as the text that was written. `yes` and +`true` load as boolean true, `NO` and `false` as boolean false, and `010` as +the integer 8. Those are legal JSON values, so the validator cannot tell they +are not what was written. Quote them when the characters matter. + +Unquoted, accepted, and not the text that was written: + +```yaml +nonportable_extensions: + - vendor_name: DB_VENDOR + data: + yes_flag: yes + no_flag: NO + truth: true + falsehood: false + code: 010 +``` + +Quoted, accepted, and the text that was written: + +```yaml +nonportable_extensions: + - vendor_name: DB_VENDOR + data: + yes_flag: "yes" + no_flag: "NO" + truth: "true" + falsehood: "false" + code: "010" +``` + +### `1e3` + +Unquoted `1e3` stays the string `1e3` under this project's PyYAML, so +`validate.py` accepts it here. Other loaders may read it as the number 1000. +Quote it when the characters matter. Both of these pass this validator; only +the quoted form is the same text on every loader. + +```yaml +nonportable_extensions: + - vendor_name: DB_VENDOR + data: + scientific: 1e3 # string "1e3" under PyYAML; may be 1000 elsewhere + quoted: "1e3" # string "1e3" +``` diff --git a/extensions/vendors.md b/extensions/vendors.md index a01f34f2..eca77adf 100644 --- a/extensions/vendors.md +++ b/extensions/vendors.md @@ -19,26 +19,30 @@ # Vendor Extensions Catalog -Custom extensions attach platform-specific metadata to a model (see -[`core-spec/spec.md`](../core-spec/spec.md#custom-extensions)): +Non-portable extensions attach platform-specific metadata to a model (see +[`core-spec/spec.md`](../core-spec/spec.md#non-portable-extensions)): ```yaml -custom_extensions: +nonportable_extensions: - vendor_name: string # Free-form string identifying the vendor - data: string # JSON string containing vendor-specific data + data: object # Vendor-defined keys; values must be JSON ``` -`vendor_name` is a free-form string and `data` is an opaque string that Ossie -carries but does not interpret; for the precise extensions a given vendor emits -and consumes, see the +`vendor_name` is a free-form string and `data` is a structured object that Ossie +carries but does not interpret. The core schema does not describe keys under +`data`. Vendor schemas live outside core-spec. For the precise extensions a given +vendor emits and consumes, see the [apache/ossie-converters](https://github.com/apache/ossie-converters) repository. This is a registry of `vendor_name` tokens the community uses (see [`README.md`](README.md) for how these lists are used). Each token identifies one vendor or tool. The registry has no shared, cross-vendor token. Metadata that more than one vendor needs belongs in the -core specification, where it has defined semantics, and not in an opaque -extension payload. +core specification, where it has defined semantics, and not in an extension +payload. Behavior defined only in `data` is non-portable. + +Quoted and unquoted values under `data` are shown in +[`nonportable_extensions.md`](nonportable_extensions.md). ## Known vendors diff --git a/ontology/mapping.json b/ontology/mapping.json index 09070f6a..b0471cf4 100644 --- a/ontology/mapping.json +++ b/ontology/mapping.json @@ -34,8 +34,8 @@ }, "description": "Maps logical model constructs to some concept and its relationships in the referenced ontology" }, - "custom_extensions": { - "$ref": "https://raw.githubusercontent.com/apache/ossie/main/core-spec/ossie-schema.json#/$defs/SemanticModel/properties/custom_extensions" + "nonportable_extensions": { + "$ref": "https://raw.githubusercontent.com/apache/ossie/main/core-spec/ossie-schema.json#/$defs/SemanticModel/properties/nonportable_extensions" } }, "required": ["version", "name", "ontology_ref", "semantic_model_ref", "concept_mappings"], diff --git a/ontology/ontology.md b/ontology/ontology.md index f2763453..94bc0cc6 100644 --- a/ontology/ontology.md +++ b/ontology/ontology.md @@ -463,7 +463,7 @@ either: | `ontology_ref` | object | Yes | Reference to the ontology document this mapping targets (see below) | | `semantic_model_ref` | object | Yes | Reference to the semantic model document this mapping draws from (see below) | | `concept_mappings` | list | Yes | Maps logical model constructs to concepts and relationships in the referenced ontology | -| `custom_extensions` | list | No | Vendor-specific attributes for extensibility, matching the core specification's mechanism | +| `nonportable_extensions` | list | No | Vendor-specific attributes for extensibility, matching the core specification's mechanism | Both `ontology_ref` and `semantic_model_ref` are references with the following schema, mirroring `DocumentReference` in `mapping.json`: diff --git a/python/src/ossie/__init__.py b/python/src/ossie/__init__.py index d9c48762..74003851 100644 --- a/python/src/ossie/__init__.py +++ b/python/src/ossie/__init__.py @@ -25,7 +25,7 @@ from ossie.models import ( OssieAIContext, OssieAIContextObject, - OssieCustomExtension, + OssieNonportableExtension, OssieDataset, OssieDataType, OssieDialect, @@ -43,7 +43,7 @@ __all__ = [ "OssieAIContext", "OssieAIContextObject", - "OssieCustomExtension", + "OssieNonportableExtension", "OssieDataset", "OssieDataType", "OssieDialect", diff --git a/python/src/ossie/models.py b/python/src/ossie/models.py index 021245fe..dc2d430d 100644 --- a/python/src/ossie/models.py +++ b/python/src/ossie/models.py @@ -99,8 +99,16 @@ def _invalid_below( if not legal_null: found.append((where, _NULL)) else: + # Null is legal inside nonportable_extensions data. The data + # property itself stays required; only values under that object + # may be null. A non-finite number is still rejected. found += _invalid_below( - value, where, inner, walked, legal_null, key == "ai_context" + value, + where, + inner, + walked, + legal_null or key == "data", + key == "ai_context", ) else: for index, item in enumerate(node): @@ -214,13 +222,13 @@ def _serialize_context(self, handler: SerializerFunctionWrapHandler, info: Seria OssieAIContext = Union[str, OssieAIContextObject] -class OssieCustomExtension(BaseModel): - """Vendor-specific metadata carried as an opaque string.""" +class OssieNonportableExtension(BaseModel): + """Vendor-specific metadata as a structured object with vendor-defined keys.""" model_config = ConfigDict(frozen=True, extra="forbid") vendor_name: str = Field(min_length=1) - data: str + data: dict[str, Any] class OssieDialectExpression(BaseModel): @@ -273,7 +281,7 @@ class OssieField(BaseModel): description: Optional[str] = None datatype: Optional[OssieDataType] = None ai_context: Optional[OssieAIContext] = None - custom_extensions: Optional[list[OssieCustomExtension]] = None + nonportable_extensions: Optional[list[OssieNonportableExtension]] = None def is_time_dimension(self) -> bool: """Return the field's effective temporal-dimension role. @@ -299,7 +307,7 @@ class OssieMetric(BaseModel): description: Optional[str] = None datatype: Optional[OssieDataType] = None ai_context: Optional[OssieAIContext] = None - custom_extensions: Optional[list[OssieCustomExtension]] = None + nonportable_extensions: Optional[list[OssieNonportableExtension]] = None class OssieDataset(BaseModel): @@ -321,7 +329,7 @@ class OssieDataset(BaseModel): # Dataset-scoped: expressions reference this dataset's declared fields by single-part # (unqualified) name and its source columns as source.column. metrics: Optional[list[OssieMetric]] = None - custom_extensions: Optional[list[OssieCustomExtension]] = None + nonportable_extensions: Optional[list[OssieNonportableExtension]] = None class OssieRelationship(BaseModel): @@ -335,7 +343,7 @@ class OssieRelationship(BaseModel): from_columns: list[str] = Field(..., min_length=1) to_columns: list[str] = Field(..., min_length=1) ai_context: Optional[OssieAIContext] = None - custom_extensions: Optional[list[OssieCustomExtension]] = None + nonportable_extensions: Optional[list[OssieNonportableExtension]] = None class OssieSemanticModel(BaseModel): @@ -350,7 +358,7 @@ class OssieSemanticModel(BaseModel): relationships: Optional[list[OssieRelationship]] = None # Model-scoped: expressions reference fields by multi-part name (dataset.field) and may span datasets. metrics: Optional[list[OssieMetric]] = None - custom_extensions: Optional[list[OssieCustomExtension]] = None + nonportable_extensions: Optional[list[OssieNonportableExtension]] = None class OssieDocument(OssieSemanticModel): @@ -404,8 +412,10 @@ def from_ossie_yaml(cls, text: str) -> "OssieDocument": and not to the models. Rejected here: a duplicate mapping key, a property set to null, a missing - ``version``, a non-finite number, and a cyclic alias. YAML merge overrides - remain supported. The field types reject the rest of the schema. + ``version``, a non-finite number, and a cyclic alias. A null inside + ``nonportable_extensions`` ``data`` is kept; that object is vendor-defined + JSON. YAML merge overrides remain supported. The field types reject the + rest of the schema. A diagnostic lists at most :data:`_MAX_REPORTED` paths and counts the rest, so fixing the ones named can reveal more on the next run. diff --git a/python/tests/test_models.py b/python/tests/test_models.py index f36bb9e3..fa79420f 100644 --- a/python/tests/test_models.py +++ b/python/tests/test_models.py @@ -26,7 +26,7 @@ from ossie import ( OssieAIContextObject, - OssieCustomExtension, + OssieNonportableExtension, OssieDataset, OssieDataType, OssieDialect, @@ -203,7 +203,7 @@ def test_document_serialization_preserves_flat_model_and_metadata( data.update( description="A portable model", ai_context="Use the event timestamp", - custom_extensions=[{"vendor_name": "SIGMA", "data": '{"id":"model-1"}'}], + nonportable_extensions=[{"vendor_name": "SIGMA", "data": {"id": "model-1"}}], relationships=[ { "name": "event_link", @@ -444,16 +444,16 @@ def test_relationship_rejects_unknown_fields(document_data: dict) -> None: ) -def test_custom_extension_rejects_unknown_fields(document_data: dict) -> None: - document_data["custom_extensions"] = [ - {"vendor_name": "DBT", "data": "{}", "datta": "typo"} +def test_nonportable_extension_rejects_unknown_fields(document_data: dict) -> None: + document_data["nonportable_extensions"] = [ + {"vendor_name": "DBT", "data": {}, "datta": "typo"} ] with pytest.raises(ValidationError) as error: OssieDocument.model_validate(document_data) assert any( - item["loc"] == ("custom_extensions", 0, "datta") + item["loc"] == ("nonportable_extensions", 0, "datta") and item["type"] == "extra_forbidden" for item in error.value.errors() ) @@ -481,7 +481,7 @@ def test_unknown_field_names_match_the_schema_allowlist() -> None: schema = json.loads(schema_path.read_text()) models = { - "CustomExtension": OssieCustomExtension, + "NonportableExtension": OssieNonportableExtension, "DialectExpression": OssieDialectExpression, "Expression": OssieExpression, "Dimension": OssieDimension, diff --git a/python/tests/test_serialization.py b/python/tests/test_serialization.py index 20093961..3516372a 100644 --- a/python/tests/test_serialization.py +++ b/python/tests/test_serialization.py @@ -79,17 +79,50 @@ def test_to_ossie_yaml_includes_all_dialects(document_data: dict) -> None: ] -def test_to_ossie_yaml_includes_custom_extension_vendor(document_data: dict) -> None: - document_data["custom_extensions"] = [ - {"vendor_name": "DATABRICKS", "data": '{"id":"model-1"}'} +def test_to_ossie_yaml_includes_nonportable_extension_vendor(document_data: dict) -> None: + document_data["nonportable_extensions"] = [ + {"vendor_name": "DATABRICKS", "data": {"id": "model-1"}} ] document = OssieDocument.model_validate(document_data) parsed = yaml.safe_load(document.to_ossie_yaml()) - assert parsed["custom_extensions"] == [ - {"vendor_name": "DATABRICKS", "data": '{"id":"model-1"}'} + assert parsed["nonportable_extensions"] == [ + {"vendor_name": "DATABRICKS", "data": {"id": "model-1"}} ] +def test_nonportable_extension_data_round_trips_nested_values(document_data: dict) -> None: + data = { + "text": '{"legacy": true}', + "warehouse": "ANALYTICS_WH", + "some_unmapped_flag": True, + "retries": 3, + "unset": None, + "tags": ["daily", None], + "nested": {"enabled": True, "inner": {"value": None}}, + } + document_data["nonportable_extensions"] = [{"vendor_name": "SNOWFLAKE", "data": data}] + document = OssieDocument.model_validate(document_data) + + from_yaml = yaml.safe_load(document.to_ossie_yaml()) + from_json = json.loads(document.to_ossie_json()) + + assert from_yaml["nonportable_extensions"][0]["data"] == data + assert from_json["nonportable_extensions"][0]["data"] == data + + +def test_from_ossie_yaml_preserves_null_inside_extension_data(document_data: dict) -> None: + document_data["nonportable_extensions"] = [ + {"vendor_name": "DB_VENDOR", "data": {"unset": None, "nested": {"inner": None}}} + ] + + document = OssieDocument.from_ossie_yaml(yaml.safe_dump(document_data)) + + assert document.nonportable_extensions[0].data == { + "unset": None, + "nested": {"inner": None}, + } + + def test_to_ossie_yaml_excludes_none(document_data: dict) -> None: document = OssieDocument.model_validate(document_data) output = document.to_ossie_yaml() @@ -295,7 +328,7 @@ def _fully_populated_document() -> dict: "name": "m", "description": "d", "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), "datasets": [ { "name": "orders", @@ -304,7 +337,7 @@ def _fully_populated_document() -> dict: "primary_key": ["id"], "unique_keys": [["id"]], "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), "fields": [ { "name": "amount", @@ -314,7 +347,7 @@ def _fully_populated_document() -> dict: "description": "d", "datatype": "Decimal", "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), } ], "metrics": [ @@ -324,7 +357,7 @@ def _fully_populated_document() -> dict: "description": "d", "datatype": "Decimal", "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), } ], } @@ -337,7 +370,7 @@ def _fully_populated_document() -> dict: "from_columns": ["id"], "to_columns": ["id"], "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), } ], "metrics": [ @@ -347,7 +380,7 @@ def _fully_populated_document() -> dict: "description": "d", "datatype": "Decimal", "ai_context": dict(ai_context), - "custom_extensions": list(extensions), + "nonportable_extensions": list(extensions), } ], } diff --git a/python/tests/test_validation.py b/python/tests/test_validation.py index f2335325..6bb7f84e 100644 --- a/python/tests/test_validation.py +++ b/python/tests/test_validation.py @@ -18,11 +18,12 @@ from collections.abc import Callable import pytest +import yaml from pydantic import ValidationError from ossie import ( OssieAIContextObject, - OssieCustomExtension, + OssieNonportableExtension, OssieDataset, OssieDialect, OssieDialectExpression, @@ -128,14 +129,24 @@ def test_semantic_model_missing_datasets() -> None: OssieSemanticModel(name="sales_model") -def test_custom_extension_missing_vendor_name() -> None: +def test_nonportable_extension_missing_vendor_name() -> None: with pytest.raises(ValidationError): - OssieCustomExtension(data="{}") + OssieNonportableExtension(data={}) -def test_custom_extension_missing_data() -> None: +def test_nonportable_extension_missing_data() -> None: with pytest.raises(ValidationError): - OssieCustomExtension(vendor_name="ASF") + OssieNonportableExtension(vendor_name="ASF") + + +@pytest.mark.parametrize("data", ['{"id": "model-1"}', ["id"], 1, None]) +def test_nonportable_extension_rejects_non_object_data(data: object) -> None: + with pytest.raises(ValidationError): + OssieNonportableExtension(vendor_name="ASF", data=data) + + +def test_nonportable_extension_accepts_empty_object_data() -> None: + assert OssieNonportableExtension(vendor_name="ASF", data={}).data == {} def test_dialect_expression_missing_dialect() -> None: @@ -200,10 +211,10 @@ def test_dialect_expression_empty_expression_is_rejected() -> None: OssieDialectExpression(dialect="ANSI_SQL", expression="") -def test_custom_extension_empty_vendor_name_is_rejected() -> None: +def test_nonportable_extension_empty_vendor_name_is_rejected() -> None: # `vendor_name` has min_length 1, matching the schema. with pytest.raises(ValidationError): - OssieCustomExtension(vendor_name="", data="{}") + OssieNonportableExtension(vendor_name="", data={}) def test_free_form_dialect_in_expression() -> None: @@ -256,8 +267,8 @@ def test_frozen_ai_context_object() -> None: ai_ctx.instructions = "Updated instructions" -def test_frozen_custom_extension() -> None: - custom_ext = OssieCustomExtension(vendor_name="ASF", data="{}") +def test_frozen_nonportable_extension() -> None: + custom_ext = OssieNonportableExtension(vendor_name="ASF", data={}) with pytest.raises(ValidationError): custom_ext.vendor_name = "other" @@ -296,3 +307,16 @@ def test_frozen_semantic_model() -> None: ) with pytest.raises(ValidationError): semantic_model.name = "other" + + +def test_nonportable_extension_data_serializes_yaml_dates_as_json_strings() -> None: + # JSON mode stringifies a date on the model. validate.py rejects that value + # in a document; constructing the model does not make the date valid. + data = yaml.safe_load("released: 2026-10-29") + custom_ext = OssieNonportableExtension(vendor_name="ASF", data=data) + assert custom_ext.model_dump(mode="json")["data"] == {"released": "2026-10-29"} + + +def test_nonportable_extension_rejects_non_string_data_keys() -> None: + with pytest.raises(ValidationError): + OssieNonportableExtension(vendor_name="ASF", data=yaml.safe_load("1: one")) diff --git a/validation/test_validate.py b/validation/test_validate.py index afb294ce..73a122f9 100644 --- a/validation/test_validate.py +++ b/validation/test_validate.py @@ -623,7 +623,7 @@ def test_relationship_column_counts_are_checked_in_flat_documents(self): self.assertIn("Validation PASSED", result.stdout) def test_root_dialects_and_vendors_are_rejected(self): - # Dialects and vendors belong under expression.dialects and custom_extensions, + # Dialects and vendors belong under expression.dialects and nonportable_extensions, # not alongside the model properties at the document root. result = self.run_validator( "version: 0.3.0.dev0\n" diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 3bab9a39..20102945 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -21,6 +21,7 @@ import re import sys import urllib.request +from datetime import date, datetime, timezone from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path @@ -390,6 +391,225 @@ def test_schema_rejects_empty_relationship_endpoints(core_schema: dict) -> None: ] +@pytest.mark.parametrize( + "data", + [ + {}, + {"warehouse": "ANALYTICS_WH", "some_unmapped_flag": True}, + {"text": '{"legacy": true}', "nested": {"tags": ["a", None], "n": 1.5}}, + ], +) +def test_nonportable_extension_data_accepts_objects(core_schema: dict, data: dict) -> None: + document = _document([dict(_ORDERS)], []) + document["nonportable_extensions"] = [{"vendor_name": "SNOWFLAKE", "data": data}] + document["datasets"][0]["nonportable_extensions"] = [{"vendor_name": "DBT", "data": data}] + + assert _VALIDATE.validate_schema(document, core_schema) == [] + + +_EXTENSION_LOCATIONS = { + "model": lambda d: d, + "dataset": lambda d: d["datasets"][0], + "field": lambda d: d["datasets"][0]["fields"][0], + "dataset_metric": lambda d: d["datasets"][0]["metrics"][0], + "metric": lambda d: d["metrics"][0], + "relationship": lambda d: d["relationships"][0], +} + + +@pytest.mark.parametrize("location", list(_EXTENSION_LOCATIONS)) +@pytest.mark.parametrize("data", ['{"warehouse": "ANALYTICS_WH"}', ["warehouse"], 1, True, None]) +def test_nonportable_extension_data_rejects_non_objects( + core_schema: dict, location: str, data: object +) -> None: + document = _document( + [dict(_ORDERS, metrics=[_metric("order_count", "COUNT(customer_id)")]), _CUSTOMERS], + [_relationship(["id"])], + ) + document["metrics"] = [_metric("customer_count", "COUNT(customers.id)")] + _EXTENSION_LOCATIONS[location](document)["nonportable_extensions"] = [ + {"vendor_name": "SNOWFLAKE", "data": data} + ] + + errors = _VALIDATE.validate_schema(document, core_schema) + + assert len(errors) == 1 + assert "nonportable_extensions -> 0 -> data:" in errors[0] + assert "is not of type 'object'" in errors[0] + + +def _extension_document() -> dict: + document = _document( + [dict(_ORDERS, metrics=[_metric("order_count", "COUNT(customer_id)")]), _CUSTOMERS], + [_relationship(["id"])], + ) + document["metrics"] = [_metric("customer_count", "COUNT(customers.id)")] + return document + + +_EXTENSION_ERROR_PREFIX = { + "model": "", + "dataset": "datasets -> 0 -> ", + "field": "datasets -> 0 -> fields -> 0 -> ", + "dataset_metric": "datasets -> 0 -> metrics -> 0 -> ", + "metric": "metrics -> 0 -> ", + "relationship": "relationships -> 0 -> ", +} + + +def _blocking(errors: list) -> list: + return [error for error in errors if not isinstance(error, _VALIDATE.ValidationWarning)] + + +@pytest.mark.parametrize("location", list(_EXTENSION_LOCATIONS)) +def test_extension_data_rejects_dates_and_non_finite_floats( + core_schema: dict, location: str +) -> None: + # JSON Schema types data as object and does not look inside. PyYAML has + # already turned an unquoted date into a date, so validate_schema accepts + # it. validate_document rejects it at schema severity. + document = _extension_document() + _EXTENSION_LOCATIONS[location](document)["nonportable_extensions"] = [ + { + "vendor_name": "DB_VENDOR", + "data": { + "released": date(2024, 1, 1), + "ratio": float("inf"), + "nested": {"when": datetime(2024, 1, 1, tzinfo=timezone.utc)}, + "missing": float("nan"), + }, + } + ] + + assert _VALIDATE.validate_schema(document, core_schema) == [] + prefix = ( + f"[Schema] {_EXTENSION_ERROR_PREFIX[location]}nonportable_extensions -> 0 -> data" + ) + assert _blocking(_VALIDATE.validate_document(document, core_schema)) == [ + f"{prefix} -> released: date is not a JSON value", + f"{prefix} -> ratio: non-finite float is not a JSON value", + f"{prefix} -> nested -> when: timestamp is not a JSON value", + f"{prefix} -> missing: non-finite float is not a JSON value", + ] + + +def test_yaml_date_under_data_fails_before_it_can_be_dumped(core_schema: dict) -> None: + # The case from the dev@ discussion: an unquoted date loads, the schema + # object check does not see it, and json.dumps cannot write it back. + document = _VALIDATE.load_yaml_named( + """ +version: 0.3.0.dev0 +name: m +datasets: + - name: orders + source: db.s.orders + nonportable_extensions: + - vendor_name: DB_VENDOR + data: + released: 2024-01-01 + ratio: .inf +""", + "model.yaml", + ) + payload = document["datasets"][0]["nonportable_extensions"][0]["data"] + with pytest.raises(TypeError, match="not JSON serializable"): + json.dumps(payload) + + errors = _blocking(_VALIDATE.validate_document(document, core_schema)) + assert errors == [ + "[Schema] datasets -> 0 -> nonportable_extensions -> 0 -> data -> " + "released: date is not a JSON value", + "[Schema] datasets -> 0 -> nonportable_extensions -> 0 -> data -> " + "ratio: non-finite float is not a JSON value", + ] + + +def test_extension_data_accepts_yaml_scalars_that_retype_to_json(core_schema: dict) -> None: + # Residual cost: these are valid JSON and are not what was written. + # yes/NO/true/false/010 are not rejected. 1e3 stays a string under PyYAML. + document = _VALIDATE.load_yaml_named( + """ +version: 0.3.0.dev0 +name: m +datasets: + - name: orders + source: db.s.orders + nonportable_extensions: + - vendor_name: DB_VENDOR + data: + yes_flag: yes + no_flag: NO + truth: true + falsehood: false + octal: 010 + scientific: 1e3 + quoted_date: "2024-01-01" +""", + "model.yaml", + ) + payload = document["datasets"][0]["nonportable_extensions"][0]["data"] + assert payload == { + "yes_flag": True, + "no_flag": False, + "truth": True, + "falsehood": False, + "octal": 8, + "scientific": "1e3", + "quoted_date": "2024-01-01", + } + assert _blocking(_VALIDATE.validate_document(document, core_schema)) == [] + + +def test_extension_data_schema_does_not_describe_keys(core_schema: dict) -> None: + extension = core_schema["$defs"]["NonportableExtension"] + data_schema = extension["properties"]["data"] + assert data_schema["type"] == "object" + assert "properties" not in data_schema + assert "patternProperties" not in data_schema + assert "required" not in data_schema + assert "additionalProperties" not in data_schema + assert "if" not in extension + assert "dependentSchemas" not in extension + assert set(extension["properties"]) == {"vendor_name", "data"} + + +def test_old_custom_extensions_name_is_rejected(core_schema: dict) -> None: + document = _document([_ORDERS], []) + document["custom_extensions"] = [{"vendor_name": "DB_VENDOR", "data": {"kept": True}}] + + errors = _VALIDATE.validate_schema(document, core_schema) + + assert len(errors) == 1 + assert "custom_extensions" in errors[0] + assert "Additional properties are not allowed" in errors[0] + + +def test_portable_checks_ignore_extension_payload(core_schema: dict) -> None: + # Core diagnostics must not change when a vendor payload copies core names. + plain = _document([_ORDERS], [_relationship(["id"], to="missing")]) + carrying = copy.deepcopy(plain) + carrying["nonportable_extensions"] = [ + { + "vendor_name": "DB_VENDOR", + "data": { + "expression": "SUM(orders.amount)", + "sql": "1", + "name": "hijack", + "from": "nowhere", + "datasets": [{"name": "ghost"}], + }, + } + ] + carrying["datasets"][0]["nonportable_extensions"] = [ + {"vendor_name": "DB_VENDOR", "data": {"primary_key": ["not_a_field"]}} + ] + + assert _VALIDATE.validate_document(carrying, core_schema) == _VALIDATE.validate_document( + plain, core_schema + ) + assert _blocking(_VALIDATE.validate_document(plain, core_schema)) + + def test_sql_checks_traverse_root_fields_and_metrics(monkeypatch: pytest.MonkeyPatch) -> None: seen = [] @@ -678,10 +898,10 @@ def test_schema_rejects_empty_dialect_expression(core_schema: dict) -> None: def test_schema_rejects_empty_vendor_name(core_schema: dict) -> None: # `vendor_name` requires minLength 1. - dataset = {**_ORDERS, "custom_extensions": [{"vendor_name": "", "data": "{}"}]} + dataset = {**_ORDERS, "nonportable_extensions": [{"vendor_name": "", "data": {}}]} assert _VALIDATE.validate_schema(_document([dataset], []), core_schema) == [ - "[Schema] datasets -> 0 -> custom_extensions -> 0 -> vendor_name: " + "[Schema] datasets -> 0 -> nonportable_extensions -> 0 -> vendor_name: " "'' should be non-empty" ] diff --git a/validation/validate.py b/validation/validate.py index 12e1b17e..e9f5c674 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -30,7 +30,10 @@ Ossie Semantic Model Validator Validates Ossie YAML or JSON documents containing one semantic model against: -1. JSON Schema (structure, types, enums) +1. JSON Schema (structure, types, enums), then a check that every value under + nonportable_extensions data is a JSON value (dates, timestamps, and + non-finite floats are rejected; the schema types data as object and does + not look inside, and portable checks do not read the payload) 2. Unique names (datasets, fields, metrics, relationships) 3. Valid relationship references 4. Relationship column arity (from_columns and to_columns lengths match) @@ -68,6 +71,7 @@ import importlib.util import itertools import json +import math import os import stat import sys @@ -75,6 +79,7 @@ from collections import Counter from collections.abc import Iterator from dataclasses import dataclass +from datetime import date, datetime, time from decimal import Decimal, InvalidOperation from functools import lru_cache from pathlib import Path @@ -235,6 +240,120 @@ def validate_schema(data: object, schema: dict) -> list[str]: return errors +# Lists the core schema uses to nest objects that carry nonportable_extensions. +# data itself is not walked for more extensions: a vendor payload may use any +# key, including a core name, and portable checks do not interpret it. +_EXTENSION_CONTAINERS = ("datasets", "fields", "metrics", "relationships") + + +def validate_extension_data(data: object) -> list[str]: + """Reject values under nonportable_extensions data that JSON cannot represent. + + ``data`` is typed only as object. JSON Schema accepts that object when a + value inside it is a date, a timestamp, or a non-finite float, because the + loader has already built those and the schema does not describe keys under + data. Those values are schema errors, at the same level as a ``data`` value + that is not an object. + + The check is vendor-agnostic. It does not read the payload for portable + meaning. It does not catch a scalar YAML retyped into a JSON boolean or + integer (``yes``, ``NO``, ``true``, ``false``, ``010``, ``1e3``). + """ + errors: list[str] = [] + _collect_extension_data(data, "", errors) + return errors + + +def _collect_extension_data(node: object, path: str, errors: list[str]) -> None: + if not isinstance(node, dict): + return + prefix = f"{path} -> " if path else "" + extensions = node.get("nonportable_extensions") + if isinstance(extensions, list): + for index, extension in enumerate(extensions): + if not isinstance(extension, dict): + continue + payload = extension.get("data") + if not isinstance(payload, dict): + continue + errors.extend( + _non_json_value_errors( + payload, + f"{prefix}nonportable_extensions -> {index} -> data", + (), + set(), + ) + ) + for key in _EXTENSION_CONTAINERS: + children = node.get(key) + if not isinstance(children, list): + continue + for index, child in enumerate(children): + _collect_extension_data(child, f"{prefix}{key} -> {index}", errors) + + +def _non_json_value_errors( + value: object, + path: str, + active: tuple[int, ...], + walked: set[int], +) -> list[str]: + """Schema errors for one value under data, including nested values. + + ``active`` is the containers on this branch, so a cycle is reported once. + ``walked`` skips a container already reported, so an anchor reused on a + sibling is not reported twice. + """ + if isinstance(value, bool) or value is None or isinstance(value, str): + return [] + if isinstance(value, int): + return [] + if isinstance(value, float): + if math.isfinite(value): + return [] + return [f"[Schema] {path}: non-finite float is not a JSON value"] + if isinstance(value, datetime): + return [f"[Schema] {path}: timestamp is not a JSON value"] + if isinstance(value, date): + return [f"[Schema] {path}: date is not a JSON value"] + if isinstance(value, time): + return [f"[Schema] {path}: time is not a JSON value"] + if isinstance(value, list): + return _non_json_container_errors(value, path, active, walked, False) + if isinstance(value, dict): + return _non_json_container_errors(value, path, active, walked, True) + return [f"[Schema] {path}: {type(value).__name__} is not a JSON value"] + + +def _non_json_container_errors( + value: dict | list, + path: str, + active: tuple[int, ...], + walked: set[int], + mapping: bool, +) -> list[str]: + identity = id(value) + if identity in active: + return [f"[Schema] {path}: cyclic structure is not a JSON value"] + if identity in walked: + return [] + walked.add(identity) + inner = (*active, identity) + errors: list[str] = [] + if mapping: + assert isinstance(value, dict) + for key, item in value.items(): + key_path = f"{path} -> {key}" if isinstance(key, str) else f"{path} -> {key!r}" + if not isinstance(key, str): + errors.append(f"[Schema] {key_path}: key is not a string") + errors.extend(_non_json_value_errors(item, key_path, inner, walked)) + else: + assert isinstance(value, list) + for index, item in enumerate(value): + errors.extend(_non_json_value_errors(item, f"{path} -> {index}", inner, walked)) + return errors + + def find_duplicates(items: list[str]) -> list[str]: """Return the items that appear more than once, each reported once. @@ -2033,6 +2152,10 @@ def validate_document(data, schema: dict, base: Path | None = None) -> list[str] """ errors = [] errors.extend(validate_schema(data, schema)) + # Same severity as a schema type error. The schema does not describe keys + # under data, so dates and non-finite floats are caught here. Portable + # checks below still do not read the payload. + errors.extend(validate_extension_data(data)) def clean() -> bool: # A warning is in the same list but must not stop the checks that follow.