diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae4151034..cc8d10be8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -542,6 +542,7 @@ jobs: filters: | rust: - 'sqlctx-rs/**' + - 'tests/ossie-fixtures/upstream/**' - 'Cargo.toml' - 'Cargo.lock' - '.cargo/**' @@ -588,8 +589,7 @@ jobs: duckdb: - 'sqlctx-duckdb/**' - 'sqlctx-rs/**' - # The extension links the workspace crate; host tests and their - # shared SemanticInput fixture live under the two trees above. + - 'tests/ossie-fixtures/upstream/**' - 'Cargo.toml' - 'Cargo.lock' - '.cargo/**' diff --git a/docs/compatibility/ossie.md b/docs/compatibility/ossie.md index 44a0663a9..3a3366144 100644 --- a/docs/compatibility/ossie.md +++ b/docs/compatibility/ossie.md @@ -468,8 +468,10 @@ Schema validation, ontology validation, permissive import, and export remain owned by that shared interchange API for both engine choices. The separate native Rust forward importer validates logical documents against -the same four immutable JSON Schemas as Python: `0.1.1` and all three pinned -development revisions. These schemas are bundled for offline native and WASM +five immutable logical schemas. Four are shared with Python (`0.1.1` and the +three `0.2.0.dev0` revisions). The fifth is the flat Apache `0.3.0.dev0` +draft at `d27a6be`. DuckDB can load that draft directly from a model file. +These schemas are bundled for offline native and WASM builds. The evaluator covers every assertion used by those schemas and fails closed if an unsupported assertion is introduced. Logical validation reports `pinned_json_schema`; semantic checks also validate recognized SQL variants even diff --git a/docs/duckdb-extension.md b/docs/duckdb-extension.md index bca09cf08..ea0531896 100644 --- a/docs/duckdb-extension.md +++ b/docs/duckdb-extension.md @@ -1,6 +1,6 @@ # DuckDB Extension -The sqlctx DuckDB extension embeds the Rust native runtime in DuckDB. It is a native-format deployment path, separate from the Python CLI and Python adapter ecosystem. +The sqlctx DuckDB extension embeds the Rust native runtime in DuckDB. It reads native sqlctx definitions and Ossie logical model files directly. ## Status @@ -82,6 +82,88 @@ Load native YAML from disk: SELECT * FROM sqlctx_load_file('/path/to/models.yml'); ``` +### Ossie files + +The same loader accepts the released wrapped `0.1.1` format and the flat +`0.3.0.dev0` logical draft pinned at Apache Ossie commit `d27a6be`. +In a database containing the TPC-DS physical tables named in the model, run: + +```sql +select * from sqlctx_load_file('/path/to/tpcds_semantic_model.yaml'); +select total_sales, total_profit from metrics; +select item.i_brand, sales_by_brand from metrics order by item.i_brand; +``` + +The draft also declares a dataset-scoped measure: + +```sql +select agg(s.total_quantity) as total_quantity from store_sales s; +``` + +The imported definitions persist in the database. A physical table, view, or +CTE named `metrics` keeps its ordinary DuckDB meaning. The wrapped file uses +the OSI reader. Flat files use the Rust Ossie importer and its offline schema. +Draft dataset metrics that require source measure-relation metadata +(`AGG(source.measure)`) are currently unsupported. + +#### Windowed metrics in plain SQL + +Selecting any of the TPC-DS draft's three windowed metrics by name from +`metrics` returns `E_DEFERRED_WINDOWED_METRIC`, as required by the +[pinned Ossie wide-table specification](https://github.com/apache/ossie/blob/d27a6beab519c8d3bf08ad5fc901c293205134eb/core-spec/wide_table_semantics.md#52-metric-components). +To calculate them in plain SQL, select `total_sales` with the grouping +dimensions in a CTE, then apply the DuckDB window function to those rows. + +**Running sales by day (`cumulative_sales`).** Each row adds that day's sales +to the total through the previous day. + +```sql +with daily as ( + select date_dim.d_date as sale_date, total_sales + from metrics +) +select sale_date, + sum(total_sales) over ( + order by sale_date rows between unbounded preceding and current row + ) as cumulative_sales +from daily +order by sale_date; +``` + +**Brand rank within each store (`brand_rank_in_store`).** Rank brands by +descending sales within each store. Brands with equal sales share a rank. + +```sql +with brand_sales as ( + select store.s_store_sk as store_id, item.i_brand as brand, total_sales + from metrics +) +select store_id, brand, + rank() over ( + partition by store_id order by total_sales desc + ) as brand_rank_in_store +from brand_sales +order by store_id, brand_rank_in_store, brand; +``` + +**Change in monthly sales (`monthly_sales_change`).** Subtract sales for the +previous month present in the result. The first month has a `NULL` change. + +```sql +with monthly as ( + select date_dim.d_year as sale_year, date_dim.d_moy as sale_month, total_sales + from metrics +) +select sale_year, sale_month, + total_sales - lag(total_sales) over ( + order by sale_year, sale_month + ) as monthly_sales_change +from monthly +order by sale_year, sale_month; +``` + +### Native SQL definitions + Load native SQL definitions from disk: ```sql diff --git a/sqlctx-duckdb/CMakeLists.txt b/sqlctx-duckdb/CMakeLists.txt index 893d109c7..02e4e8a8d 100644 --- a/sqlctx-duckdb/CMakeLists.txt +++ b/sqlctx-duckdb/CMakeLists.txt @@ -157,6 +157,7 @@ endif() file(GLOB_RECURSE SQLCTX_RUST_SOURCES "${SQLCTX_RS_DIR}/src/*.rs" + "${SQLCTX_RS_DIR}/schemas/ossie/*.json" "${SQLCTX_RS_DIR}/include/*.h") add_custom_command( diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 46765a5bc..1397fc25f 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -80,6 +80,11 @@ SELECT status, revenue FROM semantic.orders_model; SELECT sqlctx_rewrite_sql('SELECT orders_model.status, orders_model.revenue FROM orders_model'); ``` +Released Ossie `0.1.1` and flat `0.3.0.dev0` logical models load through +`sqlctx_load_file`. Query model metrics with ordinary SQL, for example +`select total_sales from metrics` for the upstream TPC-DS model. +[Ossie file examples and supported draft semantics](../docs/duckdb-extension.md#ossie-files) + ## Discover and manage definitions ```sql diff --git a/sqlctx-duckdb/src/sqlctx_parser.cpp b/sqlctx-duckdb/src/sqlctx_parser.cpp index 011189780..7322f9d76 100644 --- a/sqlctx-duckdb/src/sqlctx_parser.cpp +++ b/sqlctx-duckdb/src/sqlctx_parser.cpp @@ -412,12 +412,15 @@ class SemanticReferences { if (!use.semantic_field.empty() || explicit_semantic) return; // Every reference binds to the table, so the query keeps its native // meaning, including inside a statement that the compiler rewrites. + QualifyPhysicalTable(*use.table, use.model, use.physical); + } + + static void QualifyPhysicalTable(BaseTableRef &table, const string &name, const SqlctxPhysicalRelation &physical) { #if SQLCTX_QUALIFIED_TABLE_API - use.table->SetQualifiedName(Identifier(use.physical.catalog), Identifier(use.physical.schema), - Identifier(use.model)); + table.SetQualifiedName(Identifier(physical.catalog), Identifier(physical.schema), Identifier(name)); #else - use.table->catalog_name = use.physical.catalog; - use.table->schema_name = use.physical.schema; + table.catalog_name = physical.catalog; + table.schema_name = physical.schema; #endif } @@ -454,6 +457,17 @@ class SemanticReferences { !SqlctxPhysicalRelationExists(context, name); auto entry = models.find(name); if (((!qualified && !ctes.count(name)) || semantic_schema) && entry != models.end()) model = entry->second.model; + // FROM metrics is the global semantic namespace. A CTE or a real + // table on the search path still owns its name in ordinary SQL. + if (!model && !qualified && !ctes.count(name) && !models.empty() && + StringUtil::CIEquals(name, "metrics")) { + SqlctxPhysicalRelation physical; + if (!explicit_semantic && SqlctxFindPhysicalRelation(context, name, physical)) { + QualifyPhysicalTable(table, name, physical); + } else { + found = true; + } + } if (model) { virtual_relation = semantic_schema; name = model->name; diff --git a/sqlctx-duckdb/test/README.md b/sqlctx-duckdb/test/README.md index 43d5f9023..a55bffeaf 100644 --- a/sqlctx-duckdb/test/README.md +++ b/sqlctx-duckdb/test/README.md @@ -24,6 +24,10 @@ for the complete invocation. `test_catalog_host.py` uses the same environment variables and verifies SHOW/DESCRIBE metadata, compatible dimensions, native SELECT, prepared reads, transaction rollback, and export/import across restart and read-only connections. +It also imports unchanged, checksum-pinned upstream Ossie 0.1.1 and 0.3.0.dev0 +TPC-DS files, queries their metrics against seeded physical tables, and repeats +the results after a read-only reopen. Provenance and licenses live beside the +fixtures under `tests/ossie-fixtures/upstream/{faf5810,d27a6be}`; CI needs no network. `test_duckflight_host.py` runs the SQL through an authenticated DuckFlight PostgreSQL listener using psycopg. Set `DUCKFLIGHT_EXTENSION` as well as the two diff --git a/sqlctx-duckdb/test/test_catalog_host.py b/sqlctx-duckdb/test/test_catalog_host.py index 19887d563..3aeca4dc0 100644 --- a/sqlctx-duckdb/test/test_catalog_host.py +++ b/sqlctx-duckdb/test/test_catalog_host.py @@ -3,8 +3,10 @@ # /// """Exercise semantic catalog SQL through each built DuckDB shell.""" +import hashlib import json import os +import re import subprocess from decimal import Decimal from pathlib import Path @@ -430,5 +432,124 @@ def test_standard_catalog_numeric_metadata_matches_host(): assert native == semantic +def test_prefixless_metrics_namespace_respects_duckdb_tables_and_ctes(): + totals = execute("select orders.revenue from metrics;") + assert totals == [[{"revenue": "45.00"}]] + rows = execute(""" + create temp table metrics as select 7 as revenue; + select revenue from metrics; + with metrics as (select 9 as revenue) select revenue from metrics; + select revenue from metrics union all select orders.revenue from orders order by revenue; + """) + assert rows[-3:] == [[{"revenue": 7}], [{"revenue": 9}], [{"revenue": "7.00"}, {"revenue": "45.00"}]] + + +TPCDS_SETUP = """ +create schema public; +create table public.store_sales( + ss_item_sk integer, ss_ticket_number integer, ss_customer_sk integer, + ss_store_sk integer, ss_sold_date_sk integer, ss_quantity integer, + ss_sales_price decimal(10,2), ss_ext_sales_price decimal(10,2), ss_net_profit decimal(10,2) +); +insert into public.store_sales values + (1, 100, 1, 1, 1, 2, 10, 20, 4), + (1, 101, 1, 1, 1, 3, 10, 30, 6), + (2, 102, 2, 2, 2, 1, 15, 15, -2); +create table public.item( + i_item_sk integer, i_item_id varchar, i_item_desc varchar, + i_brand varchar, i_category varchar, i_current_price decimal(10,2) +); +insert into public.item values + (1, 'A', 'First item', 'Acme', 'Home', 10), + (2, 'B', 'Second item', 'Beta', 'Garden', 15); +create table public.customer( + c_customer_sk integer, c_customer_id varchar, c_first_name varchar, + c_last_name varchar, c_email_address varchar +); +insert into public.customer values + (1, 'C1', 'Ada', 'Lovelace', 'ada@example.test'), + (2, 'C2', 'Grace', 'Hopper', 'grace@example.test'); +create table public.store( + s_store_sk integer, s_store_id varchar, s_store_name varchar, + s_city varchar, s_state varchar, s_number_employees integer +); +insert into public.store values (1, 'S1', 'North', 'Seattle', 'WA', 5), (2, 'S2', 'South', 'Portland', 'OR', 3); +create table public.date_dim( + d_date_sk integer, d_date date, d_year integer, d_quarter_name varchar, + d_month_name varchar, d_moy integer +); +insert into public.date_dim values + (1, '2026-01-01', 2026, '2026Q1', 'January', 1), + (2, '2026-02-01', 2026, '2026Q1', 'February', 2); +""" + + +@pytest.mark.parametrize( + ("pin", "checksum", "dataset_metric"), + [ + ("faf5810", "1c8c8e1a41d6b1b4d957ae5934b883b46ca07ad3901927ec6ce0ecff55d2cb6b", False), + ("d27a6be", "72a98b17eda7daa6bcb777125ea44b1cbbb7788bdd6167430e0f58ea7e06a1ce", True), + ], + ids=["upstream-0.1.1", "upstream-0.3.0.dev0"], +) +def test_upstream_ossie_file_metrics_and_reopen(tmp_path, pin, checksum, dataset_metric): + fixture = ( + Path(__file__).resolve().parents[2] + / "tests/ossie-fixtures/upstream" + / pin + / "examples/tpcds_semantic_model.yaml" + ) + # Keep the upstream bytes unchanged, including physical source catalog names. + assert hashlib.sha256(fixture.read_bytes()).hexdigest() == checksum + database = tmp_path / "tpcds.duckdb" + query = """ + select total_sales, total_profit from metrics; + select item.i_brand, sales_by_brand from metrics order by item.i_brand; + select total_sales from metrics where store_sales.ss_quantity > 1; + select customer_lifetime_value, store_productivity from metrics; + """ + if dataset_metric: + query += "select agg(s.total_quantity) as total_quantity from store_sales s; show metrics from store_sales;" + documentation = (Path(__file__).resolve().parents[2] / "docs/duckdb-extension.md").read_text() + window_section = documentation.split("#### Windowed metrics in plain SQL", 1)[1].split( + "### Native SQL definitions", 1 + )[0] + window_queries = re.findall(r"```sql\n(.*?)```", window_section, re.DOTALL) + assert len(window_queries) == 3 + query += "\n".join(window_queries) + results = execute( + query, + setup=TPCDS_SETUP + f"select * from sqlctx_load_file({literal(str(fixture))});", + database=database, + ) + assert results[0] == [{"total_sales": "65.00", "total_profit": "8.00"}] + assert results[1] == [ + {"i_brand": "Acme", "sales_by_brand": "50.00"}, + {"i_brand": "Beta", "sales_by_brand": "15.00"}, + ] + assert results[2] == [{"total_sales": "50.00"}] + assert results[3] == [{"customer_lifetime_value": 32.5, "store_productivity": 8.125}] + if dataset_metric: + assert results[4] == [{"total_quantity": "6"}] + assert [row["qualified_name"] for row in results[5]] == ["store_sales.total_quantity"] + assert results[6] == [ + {"sale_date": "2026-01-01", "cumulative_sales": "50.00"}, + {"sale_date": "2026-02-01", "cumulative_sales": "65.00"}, + ] + assert results[7] == [ + {"store_id": 1, "brand": "Acme", "brand_rank_in_store": 1}, + {"store_id": 2, "brand": "Beta", "brand_rank_in_store": 1}, + ] + assert results[8] == [ + {"sale_year": 2026, "sale_month": 1, "monthly_sales_change": None}, + {"sale_year": 2026, "sale_month": 2, "monthly_sales_change": "-35.00"}, + ] + for metric in ["cumulative_sales", "brand_rank_in_store", "monthly_sales_change"]: + execute(f"select {metric} from metrics;", setup="", database=database, error="E_DEFERRED_WINDOWED_METRIC") + # Reopen with no definitions loaded and no write permission: both physical + # data and the imported semantic catalog must survive the shell process. + assert execute(query, setup="", database=database, readonly=True) == results + + if __name__ == "__main__": raise SystemExit(pytest.main([__file__, "-v", "-o", "addopts="])) diff --git a/sqlctx-rs/schemas/ossie/0.3.0.dev0-d27a6be.json b/sqlctx-rs/schemas/ossie/0.3.0.dev0-d27a6be.json new file mode 100644 index 000000000..8c9b93403 --- /dev/null +++ b/sqlctx-rs/schemas/ossie/0.3.0.dev0-d27a6be.json @@ -0,0 +1,398 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/apache/ossie/core-spec/ossie-schema.json", + "title": "Apache Ossie Core Metadata Specification", + "description": "JSON Schema for validating a single Apache Ossie semantic model document", + "type": "object", + "properties": { + "version": { + "type": "string", + "const": "0.3.0.dev0", + "description": "Apache Ossie specification version" + }, + "name": { + "$ref": "#/$defs/SemanticModel/properties/name" + }, + "description": { + "$ref": "#/$defs/SemanticModel/properties/description" + }, + "ai_context": { + "$ref": "#/$defs/SemanticModel/properties/ai_context" + }, + "datasets": { + "$ref": "#/$defs/SemanticModel/properties/datasets" + }, + "relationships": { + "$ref": "#/$defs/SemanticModel/properties/relationships" + }, + "metrics": { + "$ref": "#/$defs/SemanticModel/properties/metrics" + }, + "nonportable_extensions": { + "$ref": "#/$defs/SemanticModel/properties/nonportable_extensions" + } + }, + "required": ["version", "name", "datasets"], + "additionalProperties": false, + "$defs": { + "Dialect": { + "type": "string", + "minLength": 1, + "examples": ["OSSIE_SQL_2026", "ANSI_SQL", "DB_DIALECT", "BI_EXPRESSION", "SEMANTIC_MODEL_EXPRESSION", "PROGRAMMING_LANGUAGE"], + "description": "Expression language a metric or field expression is declared in. Any non-empty string is accepted. OSSIE_SQL_2026 is the only dialect this specification defines; others are opaque to Ossie. See extensions/dialects.md." + }, + "Vendor": { + "type": "string", + "minLength": 1, + "examples": ["BI_TOOL", "DB_VENDOR", "SEMANTIC_LAYER"], + "description": "Vendor name for non-portable extensions. Any non-empty string is accepted. See extensions/vendors.md." + }, + "AIContext": { + "description": "Additional context for AI tools", + "oneOf": [ + { + "type": "string" + }, + { + "type": "object", + "properties": { + "instructions": { + "type": "string", + "description": "Instructions for AI on how to use this entity" + }, + "synonyms": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Alternative names and terms" + }, + "examples": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Sample questions or use cases" + } + }, + "additionalProperties": true + } + ] + }, + "NonportableExtension": { + "type": "object", + "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": "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"], + "additionalProperties": false + }, + "DialectExpression": { + "type": "object", + "description": "Expression in a specific dialect", + "properties": { + "dialect": { + "$ref": "#/$defs/Dialect" + }, + "expression": { + "type": "string", + "minLength": 1, + "description": "SQL or dialect-specific expression" + } + }, + "required": ["dialect", "expression"], + "additionalProperties": false + }, + "Expression": { + "type": "object", + "description": "Expression definition with multi-dialect support", + "properties": { + "sql": { + "type": "string", + "minLength": 1, + "description": "Primary, portable expression written in OSSIE_SQL_2026. When both this field and an OSSIE_SQL_2026 entry in `dialects` are present, this field is authoritative." + }, + "dialects": { + "type": "array", + "items": { + "$ref": "#/$defs/DialectExpression" + }, + "minItems": 1 + } + }, + "anyOf": [ + { "required": ["sql"] }, + { "required": ["dialects"] } + ], + "additionalProperties": false + }, + "DataType": { + "type": "string", + "enum": [ + "String", + "Integer", + "Decimal", + "Float", + "Boolean", + "Date", + "Time", + "DateTime", + "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. `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", + "description": "Dimension metadata", + "properties": { + "is_time": { + "type": "boolean", + "description": "Temporal-role marker. When true, consumers that distinguish time dimensions (e.g. for time-series analysis or temporal filtering) should treat this field as a time dimension. This is a *role* flag, independent of the field's data type: a field with `is_time: true` may carry any `datatype` (e.g. `Integer` for a year grain, `String` for a month name, as well as temporal data types). When `is_time` is unset, it defaults to `true` if `datatype` is one of `Date`, `Time`, `DateTime`, or `DateTimeTz`, and `false` otherwise. Set `is_time: false` explicitly to opt a temporal-typed column (such as an audit timestamp) out of time-dimension treatment." + } + }, + "additionalProperties": false + }, + "Field": { + "type": "object", + "description": "Row-level attribute for grouping, filtering, and metric expressions", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Unique identifier for the field within the dataset" + }, + "expression": { + "$ref": "#/$defs/Expression" + }, + "dimension": { + "$ref": "#/$defs/Dimension" + }, + "label": { + "type": "string", + "description": "Label for categorization" + }, + "description": { + "type": "string", + "description": "Human-readable description" + }, + "datatype": { + "$ref": "#/$defs/DataType" + }, + "ai_context": { + "$ref": "#/$defs/AIContext" + }, + "nonportable_extensions": { + "type": "array", + "items": { + "$ref": "#/$defs/NonportableExtension" + } + } + }, + "required": ["name", "expression"], + "additionalProperties": false + }, + "Dataset": { + "type": "object", + "description": "Logical dataset representing a business entity (fact or dimension table)", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Unique identifier for the dataset" + }, + "source": { + "type": "string", + "minLength": 1, + "description": "Reference to underlying physical table/view (database.schema.table) or query" + }, + "primary_key": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true, + "description": "Dataset fields that uniquely identify rows, each named once" + }, + "unique_keys": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "minItems": 1, + "description": "Array of unique key definitions, each a list of dataset fields naming each field once" + }, + "description": { + "type": "string", + "description": "Human-readable description" + }, + "ai_context": { + "$ref": "#/$defs/AIContext" + }, + "fields": { + "type": "array", + "items": { + "$ref": "#/$defs/Field" + }, + "description": "The dataset's declared fields. Within the dataset, field names and metric names share one namespace and must all be unique across the two." + }, + "metrics": { + "type": "array", + "items": { + "$ref": "#/$defs/Metric" + }, + "description": "Dataset-scoped metrics: measures defined on this dataset's relation that semantically belong to the dataset. A metric aggregates the dataset's rows, or derives from measures of the dataset's source. The expression references this dataset's declared fields by single-part (unqualified) name, and columns of the dataset's source as source.column. When the source is a measure relation, it may evaluate a source measure with AGG(source.measure). It must resolve entirely within this dataset; an expression that must reference another dataset belongs in the model-scoped metrics instead. Within the dataset, field names and metric names share one namespace and must all be unique across the two." + }, + "nonportable_extensions": { + "type": "array", + "items": { + "$ref": "#/$defs/NonportableExtension" + } + } + }, + "required": ["name", "source"], + "additionalProperties": false + }, + "Relationship": { + "type": "object", + "description": "Foreign key relationship between datasets", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Unique identifier for the relationship" + }, + "from": { + "type": "string", + "minLength": 1, + "description": "Dataset on the many side of the relationship" + }, + "to": { + "type": "string", + "minLength": 1, + "description": "Dataset on the one side of the relationship" + }, + "from_columns": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "description": "Array of field names in the 'from' dataset (foreign key fields)" + }, + "to_columns": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "description": "Array of field names in the 'to' dataset (primary or unique key fields)" + }, + "ai_context": { + "$ref": "#/$defs/AIContext" + }, + "nonportable_extensions": { + "type": "array", + "items": { + "$ref": "#/$defs/NonportableExtension" + } + } + }, + "required": ["name", "from", "to", "from_columns", "to_columns"], + "additionalProperties": false + }, + "Metric": { + "type": "object", + "description": "Quantitative measure defined on business data", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Unique identifier for the metric" + }, + "expression": { + "$ref": "#/$defs/Expression" + }, + "description": { + "type": "string", + "description": "Human-readable description of what the metric measures" + }, + "datatype": { + "$ref": "#/$defs/DataType" + }, + "ai_context": { + "$ref": "#/$defs/AIContext" + }, + "nonportable_extensions": { + "type": "array", + "items": { + "$ref": "#/$defs/NonportableExtension" + } + } + }, + "required": ["name", "expression"], + "additionalProperties": false + }, + "SemanticModel": { + "type": "object", + "description": "Top-level container representing a complete semantic model", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Unique identifier for the semantic model" + }, + "description": { + "type": "string", + "description": "Human-readable description" + }, + "ai_context": { + "$ref": "#/$defs/AIContext" + }, + "datasets": { + "type": "array", + "items": { + "$ref": "#/$defs/Dataset" + }, + "minItems": 1, + "description": "Collection of logical datasets" + }, + "relationships": { + "type": "array", + "items": { + "$ref": "#/$defs/Relationship" + }, + "description": "Defines how datasets are connected" + }, + "metrics": { + "type": "array", + "items": { + "$ref": "#/$defs/Metric" + }, + "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. They may evaluate a dataset-scoped metric with AGG(dataset.metric). Names must be unique across the model. See core-spec/spec.md#metric-scoping." + }, + "nonportable_extensions": { + "type": "array", + "items": { + "$ref": "#/$defs/NonportableExtension" + } + } + }, + "required": ["name", "datasets"], + "additionalProperties": false + } + } +} diff --git a/sqlctx-rs/schemas/ossie/README.md b/sqlctx-rs/schemas/ossie/README.md index 3413b78b4..c332ff1fd 100644 --- a/sqlctx-rs/schemas/ossie/README.md +++ b/sqlctx-rs/schemas/ossie/README.md @@ -1,6 +1,6 @@ # Pinned Ossie logical schemas -These Apache-2.0 assets are exact copies of the shared runtime schemas in +The 0.1 and 0.2 Apache-2.0 assets are exact copies of the shared runtime schemas in `sqlctx/interchange/ossie/schemas/logical//schema.json`. They are bundled inside the Rust crate so standalone Cargo and Python source distributions can validate offline without files outside the package. @@ -11,6 +11,15 @@ can validate offline without files outside the package. | `0.2.0.dev0.json` | Apache Ossie `831f48e582731cf1ee2e65380ca5abf8157869c7` | | `0.2.0.dev0-b6c702e.json` | Apache Ossie `b6c702ed1c07e91382a69e870c875cbd19570828` | | `0.2.0.dev0-172a3e5.json` | Apache Ossie `172a3e566f2fc9c0a733ebbb470e97c33d2bd8b1` | +| `0.3.0.dev0-d27a6be.json` | Apache Ossie `d27a6beab519c8d3bf08ad5fc901c293205134eb` | + +The native 0.3 draft schema is an unmodified copy of +[`core-spec/ossie-schema.json`](https://github.com/apache/ossie/blob/d27a6beab519c8d3bf08ad5fc901c293205134eb/core-spec/ossie-schema.json), +verified against upstream HEAD on 2026-11-24. Its SHA-256 is +`b833534b1da935e373cb75517f8b983dff9d57b399283bac5f78870c928ca1bb`. +It adds object-valued `nonportable_extensions` and unique key items. Native +lowering also supports model `AGG(dataset.metric)` composition; source measure +relations requiring `AGG(source.measure)` are explicitly unsupported. The shared `schemas/manifest.json` records original URLs, hashes, and any runtime identifier transformations. OSI's original path is `core-spec/osi-schema.json`; @@ -18,7 +27,7 @@ Apache Ossie's is `core-spec/ossie-schema.json`. `LICENSE` and `NOTICE` accompan the redistributed assets. `test_native_import_parity.py` verifies byte-for-byte identity with the canonical shared files. -The native evaluator supports every assertion used by these four immutable +The native evaluator supports every assertion used by these five immutable schemas, checks the complete schema vocabulary at initialization, and rejects unknown assertions or references outside the bundled schema. It is not a user-supplied or general-purpose JSON Schema service. Schema changes require diff --git a/sqlctx-rs/src/adapters/osi.rs b/sqlctx-rs/src/adapters/osi.rs index 194f4a355..151f92365 100644 --- a/sqlctx-rs/src/adapters/osi.rs +++ b/sqlctx-rs/src/adapters/osi.rs @@ -132,6 +132,13 @@ impl Adapter for OsiAdapter { parse_semantic_model(sm_def, &mut doc)?; } + if root.get("version").and_then(Json::as_str) == Some("0.1.1") { + for metric in &mut doc.graph_metrics { + // A released model metric may combine aggregates at several dataset grains. + metric.metadata.get_or_insert_with(|| serde_json::json!({}))["osi_model_metric"] = + Json::Bool(true); + } + } let mut graph_metadata = JsonMap::new(); graph_metadata.insert("osi".to_string(), Json::Object(osi_meta)); doc.metadata = Some(Json::Object(graph_metadata)); diff --git a/sqlctx-rs/src/adapters/ossie.rs b/sqlctx-rs/src/adapters/ossie.rs index 41d787db5..e8188dec8 100644 --- a/sqlctx-rs/src/adapters/ossie.rs +++ b/sqlctx-rs/src/adapters/ossie.rs @@ -21,6 +21,24 @@ use crate::error::{Result, SqlctxError}; const VALIDATION_MODE: &str = "closed_structural_subset"; pub(super) const CURRENT_SCHEMA_REVISION: &str = "b6c702ed1c07e91382a69e870c875cbd19570828"; pub const LATEST_SCHEMA_REVISION: &str = "172a3e566f2fc9c0a733ebbb470e97c33d2bd8b1"; +pub const DRAFT_SCHEMA_REVISION: &str = "d27a6beab519c8d3bf08ad5fc901c293205134eb"; +pub(crate) fn supports_dataset_metrics(revision: Option<&str>) -> bool { + matches!( + revision, + Some(LATEST_SCHEMA_REVISION | DRAFT_SCHEMA_REVISION) + ) +} +/// Dataset measures are stored as qualified graph declarations in host catalogs. +pub(crate) fn dataset_metric_field(metric: &Metric) -> Option<(&str, &str)> { + let owner = metric + .metadata + .as_ref()? + .get("ossie_dataset_owner")? + .as_str()?; + let field = metric.name.strip_prefix(owner)?.strip_prefix('.')?; + Some((owner, field)) +} + const LATEST_SCHEMA_VERSION: &str = "0.2.0.dev0-latest"; const CURRENT_SCHEMA_VERSION: &str = "0.2.0.dev0-current"; const MAX_SOURCE_BYTES: usize = 16 * 1024 * 1024; @@ -616,7 +634,7 @@ impl OssieForwardAdapter { &scope_pointer, &scope_id, target, - profile.schema_revision.as_deref() == Some(LATEST_SCHEMA_REVISION), + profile.schema_revision.as_deref(), &mut diagnostics, ) { scopes.push(scope); @@ -713,6 +731,7 @@ impl OssieForwardAdapter { schema_revision: Option<&str>, ) -> InspectedDocument { let schema_revision = schema_revision.map(|revision| match revision { + "d27a6be" => DRAFT_SCHEMA_REVISION, "172a3e5" => LATEST_SCHEMA_REVISION, "b6c702e" => CURRENT_SCHEMA_REVISION, "831f48e" => "831f48e582731cf1ee2e65380ca5abf8157869c7", @@ -780,6 +799,18 @@ impl OssieForwardAdapter { kind == Some(DocumentKind::Logical) && !object.contains_key("semantic_model"); let mut diagnostics = Vec::new(); let mut profile = resolve_profile(object.get("version"), consumer, &mut diagnostics); + if profile + .as_ref() + .is_some_and(|profile| profile.schema_version == "0.3.0.dev0") + && !flat_root + { + diagnostics.push(diagnostic( + "ossie.schema.profile_unsupported", + "The pinned 0.3.0.dev0 profile requires a flat logical document.", + "", + None, + )); + } if kind == Some(DocumentKind::Ontology) && current_ontology_shape(object) { if let Some(profile) = profile.as_mut() { profile.schema_revision = Some(CURRENT_SCHEMA_REVISION.to_string()); @@ -787,23 +818,39 @@ impl OssieForwardAdapter { } if flat_root { if let Some(profile) = profile.as_mut() { - if profile.schema_version != "0.2.0.dev0" { + if !matches!(profile.schema_version.as_str(), "0.2.0.dev0" | "0.3.0.dev0") { diagnostics.push(diagnostic( "ossie.schema.profile_unsupported", - "Flat logical documents require version 0.2.0.dev0.", + "Flat logical documents require version 0.2.0.dev0 or 0.3.0.dev0.", "/version", None, )); } - profile.schema_revision = Some(CURRENT_SCHEMA_REVISION.to_string()); + profile.schema_revision = Some( + if profile.schema_version == "0.3.0.dev0" { + DRAFT_SCHEMA_REVISION + } else { + CURRENT_SCHEMA_REVISION + } + .to_string(), + ); } } if let Some(profile) = profile.as_mut() { - if flat_root && latest_logical_shape(object) && schema_revision.is_none() { + if flat_root + && profile.schema_version == "0.2.0.dev0" + && latest_logical_shape(object) + && schema_revision.is_none() + { profile.schema_revision = Some(LATEST_SCHEMA_REVISION.to_string()); } if let Some(revision) = schema_revision { - if profile.schema_version != "0.2.0.dev0" + if profile.schema_version == "0.3.0.dev0" + && flat_root + && revision == DRAFT_SCHEMA_REVISION + { + profile.schema_revision = Some(revision.to_string()); + } else if profile.schema_version != "0.2.0.dev0" || !matches!( revision, CURRENT_SCHEMA_REVISION @@ -847,11 +894,17 @@ impl OssieForwardAdapter { Some(DocumentKind::Logical) => { validate_logical_root(object, profile.as_ref(), &mut diagnostics); scope_ids = logical_scope_ids(object); - if profile.as_ref().is_some_and(|profile| profile.schema_revision.as_deref() == Some(LATEST_SCHEMA_REVISION)) { - validate_latest_reserved_names(&root, "", &mut diagnostics); - validate_latest_variants(&root, &mut diagnostics); + let modern = profile.as_ref().is_some_and(|profile| { + supports_dataset_metrics(profile.schema_revision.as_deref()) + }); + let draft = profile.as_ref().is_some_and(|profile| profile.schema_revision.as_deref() == Some(DRAFT_SCHEMA_REVISION)); + if modern { + if !draft { + validate_latest_reserved_names(&root, "", &mut diagnostics); + } + validate_latest_variants(&root, draft, &mut diagnostics); } - validate_semantics(object, &scope_ids, profile.as_ref().is_some_and(|profile| profile.schema_revision.as_deref() == Some(LATEST_SCHEMA_REVISION)), &mut diagnostics); + validate_semantics(object, &scope_ids, modern, &mut diagnostics); } Some(DocumentKind::Ontology) => validate_ontology_root(object, &mut diagnostics), None => diagnostics.push(diagnostic( @@ -989,9 +1042,150 @@ fn validate_latest_reserved_names( } } +fn agg_function(value: &Value) -> Option<&Value> { + ["function", "aggregate_function"] + .into_iter() + .find_map(|kind| { + value.get(kind).filter(|function| { + function["name"] + .as_str() + .is_some_and(|name| name.eq_ignore_ascii_case("AGG")) + }) + }) +} + +fn contains_agg(value: &Value) -> bool { + agg_function(value).is_some() + || match value { + Value::Object(fields) => fields.values().any(contains_agg), + Value::Array(values) => values.iter().any(contains_agg), + _ => false, + } +} + +fn agg_argument(function: &Value) -> std::result::Result<&Value, String> { + let args = function["args"] + .as_array() + .ok_or("AGG requires one qualified measure reference.")?; + if args.len() != 1 + || function.get("filter").is_some_and(|value| !value.is_null()) + || function.get("distinct").and_then(Value::as_bool) == Some(true) + { + return Err( + "AGG requires one qualified measure reference and cannot use FILTER or DISTINCT." + .into(), + ); + } + let column = args[0] + .get("column") + .ok_or("AGG requires one qualified measure reference.")?; + if column.get("table").is_none_or(Value::is_null) + || ["db", "catalog"] + .iter() + .any(|key| column.get(*key).is_some_and(|value| !value.is_null())) + { + return Err("AGG requires one two-part qualified measure reference.".into()); + } + Ok(&args[0]) +} + +/// Bind measure references in the source language before target SQL generation +/// can add quoting to keyword identifiers (for example, a metric named rows). +/// Private placeholders keep already-lowered dataset expressions out of the +/// portable lowering pass; they are replaced after normal field binding. +fn compose_draft_metric( + expression: Option<&Value>, + target: OssieTarget, + models: &[Model], + metrics: &[Metric], +) -> std::result::Result<(Option, HashMap), String> { + fn identifier_key(value: &Value) -> String { + let name = value["name"].as_str().unwrap_or(""); + if value["quoted"].as_bool() == Some(true) { + name.to_string() + } else { + normalize_identifier(name) + } + } + fn walk( + value: &mut Value, + models: &[Model], + metrics: &[Metric], + compositions: &mut HashMap, + ) -> std::result::Result<(), String> { + if let Some(function) = agg_function(value) { + let argument = agg_argument(function)?; + let column = &argument["column"]; + let dataset = identifier_key(&column["table"]); + let name = identifier_key(&column["name"]); + let model = models + .iter() + .find(|model| { + normalize_identifier(source_name(&model.name, &model.metadata)) == dataset + }) + .ok_or_else(|| format!("Unknown dataset {dataset:?}."))?; + let metric = metrics + .iter() + .find(|metric| { + metric + .metadata + .as_ref() + .and_then(|metadata| metadata["ossie_dataset_owner"].as_str()) + == Some(model.name.as_str()) + && normalize_identifier(source_name(&metric.name, &metric.metadata)) == name + }) + .ok_or_else(|| { + format!("AGG requires a declared dataset metric, got {dataset}.{name}.") + })?; + let placeholder = format!("__ossie_composed_{}", compositions.len()); + compositions.insert( + placeholder.clone(), + metric + .sql + .clone() + .ok_or("Dataset metric has no executable expression.")?, + ); + *value = serde_json::to_value(Expression::column(placeholder)) + .map_err(|error| error.to_string())?; + return Ok(()); + } + match value { + Value::Object(fields) => { + for child in fields.values_mut() { + walk(child, models, metrics, compositions)?; + } + } + Value::Array(values) => { + for child in values { + walk(child, models, metrics, compositions)?; + } + } + _ => {} + } + Ok(()) + } + let mut compositions = HashMap::new(); + let Some((sql, dialect)) = select_variant(expression, target) else { + return Ok((expression.cloned(), compositions)); + }; + if dialect != "OSSIE_SQL_2026" { + return Ok((expression.cloned(), compositions)); + } + let mut value = serde_json::to_value(super::ossie_sql::parse_portable_expression(&sql)?) + .map_err(|error| error.to_string())?; + walk(&mut value, models, metrics, &mut compositions)?; + if compositions.is_empty() { + return Ok((expression.cloned(), compositions)); + } + let ast: Expression = serde_json::from_value(value).map_err(|error| error.to_string())?; + let sql = + polyglot_sql::generate(&ast, DialectType::Snowflake).map_err(|error| error.to_string())?; + Ok((Some(serde_json::json!({"sql": sql})), compositions)) +} + /// Validate every known expression language, including variants not selected for /// execution. Unknown vendor languages remain opaque, as required by Ossie. -fn validate_latest_variants(root: &Value, diagnostics: &mut Vec) { +fn validate_latest_variants(root: &Value, draft: bool, diagnostics: &mut Vec) { fn key(value: &Value, label: &str) -> String { let name = value["name"].as_str().unwrap_or(""); if value["quoted"].as_bool() == Some(true) @@ -1029,7 +1223,29 @@ fn validate_latest_variants(root: &Value, diagnostics: &mut Vec label: &str, owner: Option<&str>, fields: &HashMap>, + metrics: &HashMap>, + draft: bool, ) -> Result<()> { + if draft && label == "OSSIE_SQL_2026" { + if let Some(function) = agg_function(value) { + let argument = agg_argument(function).map_err(SqlctxError::Validation)?; + let column = &argument["column"]; + let table = key(&column["table"], label); + let name = key(&column["name"], label); + let valid = if let Some(owner) = owner { + table == "SOURCE" && !fields[owner].contains("SOURCE") + } else { + metrics + .get(&table) + .is_some_and(|names| names.contains(&name)) + }; + return if valid { + Ok(()) + } else { + Err(SqlctxError::Validation("AGG must reference dataset.metric in model metrics or source.measure in dataset metrics.".into())) + }; + } + } if let Some(column) = value.get("column") { let field = key(&column["name"], label); let table = column @@ -1081,12 +1297,12 @@ fn validate_latest_variants(root: &Value, diagnostics: &mut Vec match value { Value::Object(object) => { for child in object.values() { - check(child, label, owner, fields)?; + check(child, label, owner, fields, metrics, draft)?; } } Value::Array(values) => { for child in values { - check(child, label, owner, fields)?; + check(child, label, owner, fields, metrics, draft)?; } } _ => {} @@ -1119,6 +1335,20 @@ fn validate_latest_variants(root: &Value, diagnostics: &mut Vec }) .collect::>(); let base = format!("/semantic_model/{scope_index}"); + let metrics = datasets + .iter() + .filter_map(|dataset| { + Some(( + normalize_identifier(dataset["name"].as_str()?), + dataset["metrics"] + .as_array() + .into_iter() + .flatten() + .filter_map(|metric| metric["name"].as_str().map(normalize_identifier)) + .collect::>(), + )) + }) + .collect::>(); let mut declarations = Vec::new(); for (i, dataset) in datasets.iter().enumerate() { let Some(name) = dataset["name"].as_str() else { @@ -1204,7 +1434,9 @@ fn validate_latest_variants(root: &Value, diagnostics: &mut Vec match parsed { Ok(ast) if metric => { let value = serde_json::to_value(ast).expect("serializable SQL AST"); - if let Err(error) = check(&value, label, owner.as_deref(), &fields) { + if let Err(error) = + check(&value, label, owner.as_deref(), &fields, &metrics, draft) + { diagnostics.push(diagnostic( "ossie.semantic.metric.reference_invalid", error.to_string(), @@ -1213,7 +1445,21 @@ fn validate_latest_variants(root: &Value, diagnostics: &mut Vec )); } } - Ok(_) => {} + Ok(ast) => { + if draft + && label == "OSSIE_SQL_2026" + && contains_agg( + &serde_json::to_value(ast).expect("serializable SQL AST"), + ) + { + diagnostics.push(diagnostic( + "ossie.semantic.expression.invalid_sql", + "Fields cannot evaluate measures with AGG.", + &pointer, + scope_id, + )); + } + } Err(error) => diagnostics.push(diagnostic( "ossie.semantic.expression.invalid_sql", error, @@ -1315,6 +1561,7 @@ fn resolve_profile( let (validation_version, alias) = match (consumer, version) { (OssieConsumerProfile::OssieCore, "0.1.1") => ("0.1.1", None), (OssieConsumerProfile::OssieCore, "0.2.0.dev0") => ("0.2.0.dev0", None), + (OssieConsumerProfile::OssieCore, "0.3.0.dev0") => ("0.3.0.dev0", None), (OssieConsumerProfile::Dbt112, "0.1.0") => ("0.1.1", Some("0.1.1")), (OssieConsumerProfile::Dbt112, "0.1.1") => ("0.1.1", None), (OssieConsumerProfile::OssieCore, "0.1.0") => { @@ -1356,7 +1603,7 @@ fn validate_logical_root( diagnostics: &mut Vec, ) { let validation_version = profile.map(|profile| { - if profile.schema_revision.as_deref() == Some(LATEST_SCHEMA_REVISION) { + if supports_dataset_metrics(profile.schema_revision.as_deref()) { LATEST_SCHEMA_VERSION } else if profile.schema_revision.as_deref() == Some(CURRENT_SCHEMA_REVISION) { CURRENT_SCHEMA_VERSION @@ -1424,6 +1671,7 @@ fn validate_logical_root( "relationships", "metrics", "custom_extensions", + "nonportable_extensions", ], &pointer, diagnostics, @@ -1493,6 +1741,7 @@ fn validate_dataset( "fields", "metrics", "custom_extensions", + "nonportable_extensions", ][..] } else { &[ @@ -1504,6 +1753,7 @@ fn validate_dataset( "ai_context", "fields", "custom_extensions", + "nonportable_extensions", ][..] }; reject_unknown(dataset, allowed, pointer, diagnostics, None); @@ -1600,6 +1850,7 @@ fn validate_field_schema( "datatype", "ai_context", "custom_extensions", + "nonportable_extensions", ][..] } else { &[ @@ -1610,6 +1861,7 @@ fn validate_field_schema( "description", "ai_context", "custom_extensions", + "nonportable_extensions", ][..] }; reject_unknown(field, allowed, pointer, diagnostics, None); @@ -1673,6 +1925,7 @@ fn validate_metric_schema( "datatype", "ai_context", "custom_extensions", + "nonportable_extensions", ][..] } else { &[ @@ -1681,6 +1934,7 @@ fn validate_metric_schema( "description", "ai_context", "custom_extensions", + "nonportable_extensions", ][..] }; reject_unknown(metric, allowed, pointer, diagnostics, None); @@ -1716,6 +1970,7 @@ fn validate_relationship_schema( "to_columns", "ai_context", "custom_extensions", + "nonportable_extensions", ], pointer, diagnostics, @@ -2321,9 +2576,11 @@ fn compile_scope( scope_pointer: &str, scope_id: &str, target: OssieTarget, - latest: bool, + schema_revision: Option<&str>, diagnostics: &mut Vec, ) -> Option { + let latest = supports_dataset_metrics(schema_revision); + let draft = schema_revision == Some(DRAFT_SCHEMA_REVISION); let scope = value.as_object()?; let datasets = scope.get("datasets")?.as_array()?; let dataset_names = runtime_names( @@ -2479,7 +2736,10 @@ fn compile_scope( supported_granularities: None, label: optional_string(field, "label"), description: optional_string(field, "description"), - metadata: Some(serde_json::json!({"ossie_source_name": field_name})), + metadata: preserve_extensions( + Some(serde_json::json!({"ossie_source_name": field_name})), + field, + ), meta: None, format: None, value_format_name: None, @@ -2489,6 +2749,10 @@ fn compile_scope( }); } + let mut metadata = serde_json::json!({"ossie_source_name": name, "ossie_scope_name": scope_id, "ossie_target_dialect": target.label(), "ossie_schema_revision": if latest { schema_revision } else { None }, "ossie_source_kind": if is_query { "query" } else { "table" }}); + if let Some(extensions) = scope.get("nonportable_extensions") { + metadata["ossie_scope_nonportable_extensions"] = extensions.clone(); + } let model = Model { name: runtime_name, table: (!is_query).then_some(source.clone()), @@ -2507,9 +2771,7 @@ fn compile_scope( default_grain: None, label: None, description: optional_string(dataset, "description"), - metadata: Some( - serde_json::json!({"ossie_source_name": name, "ossie_scope_name": scope_id, "ossie_target_dialect": target.label(), "ossie_schema_revision": if latest { Some(LATEST_SCHEMA_REVISION) } else { None }, "ossie_source_kind": if is_query { "query" } else { "table" }}), - ), + metadata: preserve_extensions(Some(metadata), dataset), meta: None, }; model_index.insert(normalize_identifier(&name), models.len()); @@ -2599,7 +2861,7 @@ fn compile_scope( related_foreign_key: None, related_foreign_key_columns: None, sql: None, - metadata: None, + metadata: preserve_extensions(None, relationship), }); } @@ -2643,7 +2905,15 @@ fn compile_scope( }) }) .and_then(|sql| { - bind_latest_metric_sql(&sql, &mut models, Some(owner), target, &dialect) + bind_latest_metric_sql( + &sql, + &mut models, + Some(owner), + target, + &dialect, + draft, + &HashMap::new(), + ) }); match sql { Ok(sql) => { @@ -2654,10 +2924,11 @@ fn compile_scope( parsed.sql_is_complete = true; parsed.description = optional_string(metric, "description"); parsed.logical_data_type = optional_string(metric, "datatype"); - parsed.metadata = Some( - serde_json::json!({"ossie_expression_dialect": dialect, + parsed.metadata = preserve_extensions( + Some(serde_json::json!({"ossie_expression_dialect": dialect, "ossie_target_dialect": target.label(), "ossie_source_name": name, - "ossie_dataset_metric": true, "ossie_dataset_metric_index": metric_index, "ossie_dataset_owner": models[owner].name}), + "ossie_dataset_metric": true, "ossie_dataset_metric_index": metric_index, "ossie_dataset_owner": models[owner].name})), + metric, ); metrics.push(parsed); } @@ -2703,7 +2974,23 @@ fn compile_scope( continue; }; let pointer = format!("{scope_pointer}/metrics/{metric_index}/expression"); - let selected = match lower_selected_expression(metric.get("expression"), target) { + let (expression, compositions) = if draft { + match compose_draft_metric(metric.get("expression"), target, &models, &metrics) { + Ok(result) => result, + Err(message) => { + diagnostics.push(diagnostic( + "ossie.lowering.metric_unexecutable", + message, + &pointer, + Some(scope_id), + )); + continue; + } + } + } else { + (metric.get("expression").cloned(), HashMap::new()) + }; + let selected = match lower_selected_expression(expression.as_ref(), target) { Ok(selected) => selected, Err(message) => { diagnostics.push(diagnostic( @@ -2739,7 +3026,15 @@ fn compile_scope( let expression_dialect = selected_expression_dialect(metric.get("expression"), target).unwrap_or_default(); let bound = if latest { - bind_latest_metric_sql(&sql, &mut models, None, target, &expression_dialect) + bind_latest_metric_sql( + &sql, + &mut models, + None, + target, + &expression_dialect, + draft, + &compositions, + ) } else { bind_metric_sql(&sql, &models, &metric_names, target, &expression_dialect) }; @@ -2761,11 +3056,14 @@ fn compile_scope( parsed.sql = Some(sql); parsed.sql_is_complete = true; parsed.description = optional_string(metric, "description"); - parsed.metadata = Some(serde_json::json!({ - "ossie_expression_dialect": expression_dialect, - "ossie_target_dialect": target.label(), - "ossie_source_name": name, - })); + parsed.metadata = preserve_extensions( + Some(serde_json::json!({ + "ossie_expression_dialect": expression_dialect, + "ossie_target_dialect": target.label(), + "ossie_source_name": name, + })), + metric, + ); parsed.logical_data_type = metric .get("datatype") .and_then(Value::as_str) @@ -2782,6 +3080,15 @@ fn compile_scope( }) } +fn preserve_extensions(metadata: Option, declaration: &Map) -> Option { + let Some(extensions) = declaration.get("nonportable_extensions") else { + return metadata; + }; + let mut metadata = metadata.unwrap_or_else(|| serde_json::json!({})); + metadata["ossie_nonportable_extensions"] = extensions.clone(); + Some(metadata) +} + fn classify_source(source: &str, target: OssieTarget) -> Option { if let Ok(expressions) = crate::semantic_input::dialects::parse_many(source, target.parser_dialect()) @@ -3062,6 +3369,8 @@ fn bind_latest_metric_sql( owner: Option, target: OssieTarget, expression_dialect: &str, + draft: bool, + compositions: &HashMap, ) -> std::result::Result { fn identifier_key(value: &Value, dialect: &str) -> String { let name = value["name"].as_str().unwrap_or(""); @@ -3107,8 +3416,29 @@ fn bind_latest_metric_sql( owner: Option, target: OssieTarget, dialect: &str, + draft: bool, + compositions: &HashMap, ) -> std::result::Result<(), String> { + if draft && dialect == "OSSIE_SQL_2026" { + if let Some(function) = agg_function(value) { + agg_argument(function)?; + if owner.is_some() { + return Err("AGG(source.measure) requires source measure-relation metadata; this importer does not support source measure relations.".into()); + } + return Err("Unbound AGG measure reference.".into()); + } + } if let Some(column) = value.get_mut("column").and_then(Value::as_object_mut) { + if column.get("table").is_none_or(Value::is_null) { + if let Some(sql) = column["name"]["name"] + .as_str() + .and_then(|name| compositions.get(name)) + { + *value = serde_json::to_value(parse_scalar_sql(sql, target)?) + .map_err(|error| error.to_string())?; + return Ok(()); + } + } let field_key = identifier_key(&column["name"], dialect); let qualifier = column .get("table") @@ -3175,7 +3505,15 @@ fn bind_latest_metric_sql( .map_err(|error| error.to_string())?, ); if let Some(predicate) = count.get_mut("filter") { - walk(predicate, models, Some(owner), target, dialect)?; + walk( + predicate, + models, + Some(owner), + target, + dialect, + draft, + compositions, + )?; } return Ok(()); } @@ -3184,12 +3522,12 @@ fn bind_latest_metric_sql( match value { Value::Object(fields) => { for child in fields.values_mut() { - walk(child, models, owner, target, dialect)?; + walk(child, models, owner, target, dialect, draft, compositions)?; } } Value::Array(values) => { for child in values { - walk(child, models, owner, target, dialect)?; + walk(child, models, owner, target, dialect, draft, compositions)?; } } _ => {} @@ -3200,7 +3538,15 @@ fn bind_latest_metric_sql( serde_json::to_value(parse_scalar_sql(sql, target)?).map_err(|error| error.to_string())?; // Model-level argument grain is resolved by the Layer 3 query compiler. // Columnless aggregate declarations remain valid Layer 1 source models. - walk(&mut value, models, owner, target, expression_dialect)?; + walk( + &mut value, + models, + owner, + target, + expression_dialect, + draft, + compositions, + )?; let expression = serde_json::from_value(value).map_err(|error| error.to_string())?; crate::semantic_input::dialects::emit( expression, diff --git a/sqlctx-rs/src/adapters/ossie_schema.rs b/sqlctx-rs/src/adapters/ossie_schema.rs index 2c0701c40..43c29dd57 100644 --- a/sqlctx-rs/src/adapters/ossie_schema.rs +++ b/sqlctx-rs/src/adapters/ossie_schema.rs @@ -10,10 +10,11 @@ use super::ossie::{diagnostic, OssieDiagnostic, OssieProfile}; const LEGACY: &str = include_str!("../../schemas/ossie/0.2.0.dev0.json"); const CURRENT: &str = include_str!("../../schemas/ossie/0.2.0.dev0-b6c702e.json"); const LATEST: &str = include_str!("../../schemas/ossie/0.2.0.dev0-172a3e5.json"); +const DRAFT: &str = include_str!("../../schemas/ossie/0.3.0.dev0-d27a6be.json"); const STABLE: &str = include_str!("../../schemas/ossie/0.1.1.json"); static SCHEMAS: Lazy>> = Lazy::new(|| { - [STABLE, LEGACY, CURRENT, LATEST] + [STABLE, LEGACY, CURRENT, LATEST, DRAFT] .iter() .map(|text| { let schema: Value = serde_json::from_str(text).map_err(|error| error.to_string())?; @@ -25,6 +26,7 @@ static SCHEMAS: Lazy>> = Lazy::new(|| { fn schema(profile: &OssieProfile) -> &Result { &SCHEMAS[match profile.schema_revision.as_deref() { + Some(super::ossie::DRAFT_SCHEMA_REVISION) => 4, Some(super::ossie::LATEST_SCHEMA_REVISION) => 3, Some(super::ossie::CURRENT_SCHEMA_REVISION) => 2, _ if profile.validation_schema_version == "0.1.1" => 0, @@ -39,7 +41,7 @@ fn check_schema(schema: &Value, root: &Value) -> Result<(), String> { for (key, value) in object { match key.as_str() { "$schema" | "$id" | "title" | "description" | "examples" | "deprecated" | "type" - | "const" | "enum" | "required" | "minLength" | "minItems" => {} + | "const" | "enum" | "required" | "minLength" | "minItems" | "uniqueItems" => {} "$ref" => { let reference = value .as_str() @@ -146,6 +148,19 @@ fn evaluate( } } if let Some(items) = value.as_array() { + if schema.get("uniqueItems") == Some(&Value::Bool(true)) + && items + .iter() + .enumerate() + .any(|(index, item)| items[..index].contains(item)) + { + errors.push(diagnostic( + "ossie.schema.unique_items", + "Array items must be unique.", + path, + None, + )); + } if let Some(min) = schema.get("minItems").and_then(Value::as_u64) { if items.len() < min as usize { errors.push(diagnostic( @@ -250,7 +265,7 @@ mod tests { use super::*; #[test] fn every_pinned_logical_assertion_and_reference_is_supported() { - for text in [STABLE, LEGACY, CURRENT, LATEST] { + for text in [STABLE, LEGACY, CURRENT, LATEST, DRAFT] { let schema: Value = serde_json::from_str(text).unwrap(); check_schema(&schema, &schema).unwrap(); } diff --git a/sqlctx-rs/src/config/loader.rs b/sqlctx-rs/src/config/loader.rs index 98b07e13c..bcad4bd93 100644 --- a/sqlctx-rs/src/config/loader.rs +++ b/sqlctx-rs/src/config/loader.rs @@ -7,6 +7,9 @@ use std::path::Path; use regex::Regex; use serde::{Deserialize, Serialize}; +use crate::adapters::ossie::{ + OssieConsumerProfile, OssieForwardAdapter, OssieSerialization, OssieTarget, +}; use crate::adapters::{Adapter, CubeAdapter, OsiAdapter}; use crate::core::{ extract_dependencies, resolve_model_inheritance, Metric, Model, Parameter, Relationship, @@ -58,6 +61,8 @@ pub enum ConfigFormat { Cube, /// OSI (Open Semantic Interchange) format (semantic_model: / ontology_mappings: key) Osi, + /// Flat Ossie logical model. + Ossie, } impl ConfigFormat { @@ -66,6 +71,7 @@ impl ConfigFormat { ConfigFormat::Sqlctx => "sqlctx", ConfigFormat::Cube => "Cube", ConfigFormat::Osi => "OSI", + ConfigFormat::Ossie => "Ossie", } } } @@ -677,18 +683,20 @@ fn deep_merge_json(target: &mut serde_json::Value, incoming: serde_json::Value) /// Detect the config format from content fn detect_format(content: &str) -> ConfigFormat { - // Check for Cube.js format markers - if content.contains("cubes:") { - return ConfigFormat::Cube; - } - - // Check for OSI format markers - if content.contains("semantic_model:") || content.contains("ontology_mappings:") { - return ConfigFormat::Osi; + let Ok(serde_yaml::Value::Mapping(root)) = serde_yaml::from_str(content) else { + return ConfigFormat::Sqlctx; + }; + if root.get("version").and_then(serde_yaml::Value::as_str) == Some("0.3.0.dev0") { + ConfigFormat::Ossie + } else if root.contains_key("cubes") { + ConfigFormat::Cube + } else if root.contains_key("semantic_model") || root.contains_key("ontology_mappings") { + ConfigFormat::Osi + } else if root.contains_key("datasets") { + ConfigFormat::Ossie + } else { + ConfigFormat::Sqlctx } - - // Default to sqlctx format - ConfigFormat::Sqlctx } /// Parse content based on detected format @@ -832,6 +840,22 @@ fn parse_literal_content_with_extends(content: &str, format: ConfigFormat) -> Re ..Default::default() }) } + ConfigFormat::Ossie => { + let scope = OssieForwardAdapter.select_scope( + content, + OssieSerialization::Yaml, + OssieConsumerProfile::OssieCore, + OssieTarget::DuckDb, + None, + )?; + scope.clone().into_graph()?; + Ok(ParsedConfig { + models: scope.models, + graph_metrics: scope.metrics, + explicit_relationships: true, + ..Default::default() + }) + } ConfigFormat::Osi => { let doc = OsiAdapter::new().parse_document(content)?; Ok(ParsedConfig { diff --git a/sqlctx-rs/src/core/graph.rs b/sqlctx-rs/src/core/graph.rs index d22e2181f..f42f5486d 100644 --- a/sqlctx-rs/src/core/graph.rs +++ b/sqlctx-rs/src/core/graph.rs @@ -120,7 +120,12 @@ impl SemanticGraph { } pub fn metric_owner(&self, metric: &str) -> Option<&str> { - self.metric_owners.get(metric).map(String::as_str) + if self.strict_metric_scope { + return self.metric_owners.get(metric).map(String::as_str); + } + // File imports and persisted catalogs retain dataset ownership on the declaration. + crate::adapters::ossie::dataset_metric_field(self.metrics.get(metric)?) + .map(|(owner, _)| owner) } /// Resolve population ownership identically before policy preparation and SQL generation. diff --git a/sqlctx-rs/src/ffi/catalog.rs b/sqlctx-rs/src/ffi/catalog.rs index 36c46ea6b..34befec08 100644 --- a/sqlctx-rs/src/ffi/catalog.rs +++ b/sqlctx-rs/src/ffi/catalog.rs @@ -1146,6 +1146,15 @@ pub extern "C" fn sqlctx_snapshot_list_models(snapshot: *const c_char) -> Sqlctx .chain(model.metrics.into_iter().map(|field| field.name)) .chain(model.segments.into_iter().map(|field| field.name)) .collect(); + for (owner, field) in snapshot + .metrics + .iter() + .filter_map(crate::adapters::ossie::dataset_metric_field) + { + if owner == model.name { + fields.push(field.to_owned()); + } + } fields.sort(); fields.dedup(); let fields: Vec = fields diff --git a/sqlctx-rs/src/ffi/catalog/api.rs b/sqlctx-rs/src/ffi/catalog/api.rs index 5652174cf..3857f324a 100644 --- a/sqlctx-rs/src/ffi/catalog/api.rs +++ b/sqlctx-rs/src/ffi/catalog/api.rs @@ -92,8 +92,16 @@ fn entries(snapshot: &Snapshot, kind: &str, model: &str) -> CatalogResult CatalogResult SqlGenerator<'a> { metric: &Metric, visiting: &mut HashSet, ) -> Result> { - if self.graph.has_strict_metric_scope() { + if self.graph.has_strict_metric_scope() || aggregate_plan::is_osi_model_calculation(metric) + { return self.strict_graph_metric_owners(reference, metric, visiting); } let mut owners = HashSet::new(); diff --git a/sqlctx-rs/src/sql/generator/aggregate_plan.rs b/sqlctx-rs/src/sql/generator/aggregate_plan.rs index 2a03f4a73..a1fca3196 100644 --- a/sqlctx-rs/src/sql/generator/aggregate_plan.rs +++ b/sqlctx-rs/src/sql/generator/aggregate_plan.rs @@ -39,11 +39,20 @@ struct Plan<'a, 'g> { inline_aggregates: bool, } +pub(super) fn is_osi_model_calculation(metric: &Metric) -> bool { + metric.r#type == MetricType::Derived + && metric + .metadata + .as_ref() + .is_some_and(|metadata| metadata["osi_model_metric"].as_bool() == Some(true)) +} + pub(super) fn has_logical_inputs(metric: &Metric) -> bool { metric .metadata .as_ref() .is_some_and(|metadata| metadata.get("ossie_expression_dialect").is_some()) + || is_osi_model_calculation(metric) } fn unsupported(capability: &str) -> SqlctxError { @@ -625,7 +634,15 @@ pub(super) fn try_generate( generator: &SqlGenerator<'_>, query: &SemanticQuery, ) -> Result> { - if !generator.graph.has_strict_metric_scope() || query.metrics.is_empty() { + let has_osi_calculation = query.metrics.iter().any(|reference| { + generator + .graph + .get_metric(reference) + .is_some_and(is_osi_model_calculation) + }); + if query.metrics.is_empty() + || (!generator.graph.has_strict_metric_scope() && !has_osi_calculation) + { return Ok(None); } let mut plan = Plan { diff --git a/sqlctx-rs/src/sql/generator/ossie_wide.rs b/sqlctx-rs/src/sql/generator/ossie_wide.rs index 30891a86a..52c85dd78 100644 --- a/sqlctx-rs/src/sql/generator/ossie_wide.rs +++ b/sqlctx-rs/src/sql/generator/ossie_wide.rs @@ -6,7 +6,6 @@ use polyglot_sql::expressions::Column; use serde_json::Value; use std::collections::BTreeMap; -const REVISION: &str = "172a3e566f2fc9c0a733ebbb470e97c33d2bd8b1"; fn fail(code: &str, message: impl std::fmt::Display) -> SqlctxError { SqlctxError::YardstickBinding(format!("{code}: {message}")) } @@ -200,10 +199,11 @@ impl SqlGenerator<'_> { pub(super) fn uses_latest_ossie(&self) -> bool { self.graph.models().next().is_some() && self.graph.models().all(|m| { - m.metadata - .as_ref() - .and_then(|v| v["ossie_schema_revision"].as_str()) - == Some(REVISION) + crate::adapters::ossie::supports_dataset_metrics( + m.metadata + .as_ref() + .and_then(|v| v["ossie_schema_revision"].as_str()), + ) }) } pub(super) fn generate_latest_ossie(&self, query: &SemanticQuery) -> Result { @@ -247,7 +247,9 @@ impl SqlGenerator<'_> { .collect::>() }; let mut request = serde_json::json!({"dimensions": entries(&query.dimensions, "field"), "metrics": entries(&query.metrics, "metric")}); - if !query.filters.is_empty() { + if let [filter] = query.filters.as_slice() { + request["filter"] = filter.clone().into(); + } else if !query.filters.is_empty() { request["filter"] = query .filters .iter() @@ -576,7 +578,7 @@ impl<'a, 'g> Planner<'a, 'g> { stored_dialect(&metric.metadata, DialectType::DuckDB)?, )?)?; let begin = self.components.len(); - if nested_aggregate(&value, false) { + if !contains_kind(&value, is_window) && nested_aggregate(&value, false) { metric_errors.push(( 1, "E_INVALID_QUERY", diff --git a/sqlctx-rs/src/sql/rewriter/ossie_relational.rs b/sqlctx-rs/src/sql/rewriter/ossie_relational.rs index 8a6138fcd..a15c76aa4 100644 --- a/sqlctx-rs/src/sql/rewriter/ossie_relational.rs +++ b/sqlctx-rs/src/sql/rewriter/ossie_relational.rs @@ -3250,12 +3250,13 @@ fn preprocess_measure_syntax(source: &str) -> Result { impl QueryRewriter<'_> { fn has_ossie_relational_models(&self) -> bool { self.graph.models().any(|model| { - model - .metadata - .as_ref() - .and_then(|meta| meta.get("ossie_schema_revision")) - .and_then(Value::as_str) - == Some(crate::adapters::ossie::LATEST_SCHEMA_REVISION) + crate::adapters::ossie::supports_dataset_metrics( + model + .metadata + .as_ref() + .and_then(|meta| meta.get("ossie_schema_revision")) + .and_then(Value::as_str), + ) }) || self.graph.metrics().any(|metric| { metric .metadata diff --git a/sqlctx-rs/tests/ossie_forward.rs b/sqlctx-rs/tests/ossie_forward.rs index fa0366bbe..2e5a6470c 100644 --- a/sqlctx-rs/tests/ossie_forward.rs +++ b/sqlctx-rs/tests/ossie_forward.rs @@ -206,6 +206,234 @@ fn current_metadata_and_dialects_validate_without_becoming_sql_targets() { const LATEST_REVISION: &str = "172a3e566f2fc9c0a733ebbb470e97c33d2bd8b1"; const OCTOBER_REVISION: &str = "b6c702ed1c07e91382a69e870c875cbd19570828"; +const DRAFT_REVISION: &str = "d27a6beab519c8d3bf08ad5fc901c293205134eb"; + +fn draft_document() -> serde_json::Value { + let mut document = latest_document(); + document["version"] = "0.3.0.dev0".into(); + document +} + +fn draft_scope(document: &serde_json::Value) -> sqlctx::Result { + OssieForwardAdapter.select_scope( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + OssieTarget::DuckDb, + None, + ) +} + +#[test] +fn draft_profile_rejects_wrapped_and_ontology_document_families() { + let mut scope = draft_document(); + scope.as_object_mut().unwrap().remove("version"); + for document in [ + serde_json::json!({"version":"0.3.0.dev0", "semantic_model":[scope]}), + serde_json::json!({"version":"0.3.0.dev0", "ontology":[]}), + serde_json::json!({"version":"0.3.0.dev0", "ontology_mappings":[]}), + ] { + for revision in [None, Some(DRAFT_REVISION), Some(LATEST_REVISION)] { + let status = OssieForwardAdapter.inspect_with_revision( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + revision, + ); + assert!( + !status.valid && !status.executable, + "{document}: {status:?}" + ); + assert!(status + .diagnostics + .iter() + .any(|diagnostic| diagnostic.code == "ossie.schema.profile_unsupported")); + } + } +} + +#[test] +fn draft_profile_validates_structured_extensions_and_pinned_revision() { + let mut document = draft_document(); + let extension = serde_json::json!([{"vendor_name":"example", "data": { + "expression":{"sql":"AGG(opaque.not_sql)"}, "array":[null, true, 42] + }}]); + document["nonportable_extensions"] = extension.clone(); + document["datasets"][0]["nonportable_extensions"] = extension.clone(); + document["datasets"][0]["fields"][0]["nonportable_extensions"] = extension.clone(); + document["datasets"][0]["metrics"][0]["nonportable_extensions"] = extension; + let status = OssieForwardAdapter.inspect( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + ); + assert!(status.valid, "{:?}", status.diagnostics); + assert_eq!( + status.profile.unwrap().schema_revision.as_deref(), + Some(DRAFT_REVISION) + ); + let scope = draft_scope(&document).unwrap(); + assert_eq!( + scope.models[0].metadata.as_ref().unwrap()["ossie_nonportable_extensions"], + document["datasets"][0]["nonportable_extensions"] + ); + assert_eq!( + scope.models[0].metadata.as_ref().unwrap()["ossie_scope_nonportable_extensions"], + document["nonportable_extensions"] + ); + assert_eq!( + scope.metrics[0].metadata.as_ref().unwrap()["ossie_nonportable_extensions"], + document["datasets"][0]["metrics"][0]["nonportable_extensions"] + ); + assert!(OssieForwardAdapter + .select_scope_with_revision( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + OssieTarget::DuckDb, + None, + Some("d27a6be") + ) + .is_ok()); + assert!(OssieForwardAdapter + .select_scope_with_revision( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + OssieTarget::DuckDb, + None, + Some(LATEST_REVISION) + ) + .is_err()); + document["nonportable_extensions"][0]["data"] = "{}".into(); + assert!(draft_scope(&document).is_err()); + document + .as_object_mut() + .unwrap() + .remove("nonportable_extensions"); + document["custom_extensions"] = serde_json::json!([]); + assert!(draft_scope(&document).is_err()); +} + +#[test] +fn draft_model_agg_composes_dataset_metrics_and_keeps_their_inputs() { + let mut document = draft_document(); + document["metrics"] = serde_json::json!([ + {"name":"average", "expression":{"sql":"AGG(orders.total) / AGG(orders.rows)"}}, + {"name":"physical_total", "expression":{"sql":"AGG(orders.physical)"}} + ]); + let scope = draft_scope(&document).unwrap(); + let graph = scope.into_graph().unwrap(); + let sql = sqlctx::SqlGenerator::new(&graph) + .generate( + &sqlctx::SemanticQuery::new() + .with_metrics(vec!["average".into(), "physical_total".into()]), + ) + .unwrap(); + assert!(sql.contains("amount * 2"), "{sql}"); + assert!(!sql.contains("AGG("), "{sql}"); + assert!(!sql.contains("source.amount"), "{sql}"); + assert_eq!(graph.metric_owner("orders.rows"), Some("orders")); +} + +#[test] +fn draft_agg_rejects_invalid_references_and_unsupported_source_measures() { + for expression in [ + "AGG(orders.amount)", + "AGG(orders.missing)", + "AGG(total)", + "AGG(orders.total + 1)", + "AGG(orders.total, orders.rows)", + "AGG(orders.total) FILTER (WHERE orders.amount > 0)", + "orders.total", + "SUM(orders.total)", + ] { + let mut document = draft_document(); + document["metrics"] = serde_json::json!([{"name":"bad", "expression":{"sql":expression}}]); + assert!(draft_scope(&document).is_err(), "{expression}"); + } + let mut document = draft_document(); + document["datasets"][0]["fields"][0]["expression"]["sql"] = "AGG(amount)".into(); + assert!(draft_scope(&document).is_err()); + let mut document = draft_document(); + document["datasets"][0]["metrics"][0]["expression"]["sql"] = "AGG(source.total)".into(); + let status = OssieForwardAdapter.inspect( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + ); + assert!(status.valid, "{:?}", status.diagnostics); + assert!(draft_scope(&document) + .unwrap_err() + .to_string() + .contains("source measure-relation metadata")); +} + +#[test] +fn draft_composition_keeps_quoted_and_regular_metric_names_distinct() { + let mut document = draft_document(); + document["datasets"][0]["metrics"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name":"\"total\"", "expression":{"sql":"SUM(source.amount)"} + })); + document["metrics"] = serde_json::json!([ + {"name":"regular", "expression":{"sql":"AGG(orders.total)"}}, + {"name":"quoted", "expression":{"sql":"AGG(orders.\"total\")"}} + ]); + let scope = draft_scope(&document).unwrap(); + assert_eq!(scope.metrics[4].sql, scope.metrics[0].sql); + assert_eq!(scope.metrics[5].sql, scope.metrics[3].sql); + assert_ne!(scope.metrics[4].sql, scope.metrics[5].sql); +} + +#[test] +fn draft_keys_require_unique_items_in_the_pinned_schema() { + let mut document = draft_document(); + document["datasets"][0]["primary_key"] = serde_json::json!(["amount", "amount"]); + let status = OssieForwardAdapter.inspect( + &document.to_string(), + OssieSerialization::Json, + OssieConsumerProfile::OssieCore, + ); + assert!(status + .diagnostics + .iter() + .any(|diagnostic| diagnostic.code == "ossie.schema.unique_items" + && diagnostic.instance_path == "/datasets/0/primary_key")); +} + +#[test] +fn current_upstream_tpcds_file_imports_without_source_edits() { + let content = fs::read_to_string( + fixture_root().join("upstream/d27a6be/examples/tpcds_semantic_model.yaml"), + ) + .unwrap(); + let scope = OssieForwardAdapter + .select_scope( + &content, + OssieSerialization::Yaml, + OssieConsumerProfile::OssieCore, + OssieTarget::DuckDb, + None, + ) + .unwrap(); + assert_eq!(scope.scope_id, "tpcds_retail_model"); + assert_eq!( + scope.models[0].table.as_deref(), + Some("tpcds.public.store_sales") + ); + assert_eq!( + scope.models[0].metadata.as_ref().unwrap()["ossie_schema_revision"], + DRAFT_REVISION + ); + let graph = scope.into_graph().unwrap(); + let sql = sqlctx::SqlGenerator::new(&graph) + .generate(&sqlctx::SemanticQuery::new().with_metrics(vec!["total_sales".into()])) + .unwrap(); + assert!(sql.contains("store_sales"), "{sql}"); +} fn latest_document() -> serde_json::Value { serde_json::json!({"version": "0.2.0.dev0", "name": "commerce", "datasets": [{ diff --git a/tests/ossie-fixtures/upstream/d27a6be/LICENSE b/tests/ossie-fixtures/upstream/d27a6be/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/tests/ossie-fixtures/upstream/d27a6be/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tests/ossie-fixtures/upstream/d27a6be/NOTICE b/tests/ossie-fixtures/upstream/d27a6be/NOTICE new file mode 100644 index 000000000..e4bc78e2b --- /dev/null +++ b/tests/ossie-fixtures/upstream/d27a6be/NOTICE @@ -0,0 +1,5 @@ +Apache Ossie (incubating) +Copyright 2026 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/tests/ossie-fixtures/upstream/d27a6be/README.md b/tests/ossie-fixtures/upstream/d27a6be/README.md new file mode 100644 index 000000000..d6b39b801 --- /dev/null +++ b/tests/ossie-fixtures/upstream/d27a6be/README.md @@ -0,0 +1,17 @@ +# Ossie 0.3.0.dev0 real-file fixture + +`examples/tpcds_semantic_model.yaml` is an unchanged copy from Apache Ossie +commit [`d27a6beab519c8d3bf08ad5fc901c293205134eb`](https://github.com/apache/ossie/blob/d27a6beab519c8d3bf08ad5fc901c293205134eb/examples/tpcds_semantic_model.yaml). +The file declares `version: "0.3.0.dev0"`. SHA-256: +`72a98b17eda7daa6bcb777125ea44b1cbbb7788bdd6167430e0f58ea7e06a1ce`. + +`LICENSE` and `NOTICE` are unchanged files from the same commit. Its Apache +License header is preserved. Retrieved November 24, 2026. This pins a specific +draft, not a promise of compatibility with future upstream revisions. + +`sqlctx-duckdb/test/test_catalog_host.py` loads this exact file through +`sqlctx_load_file`, creates matching `tpcds.public` physical sources, and asserts +root-level total sales, total profit, joined brand sales, filtered sales, lifetime value, store productivity, and +the dataset-scoped `store_sales.total_quantity` metric. It repeats the queries +after reopening the persisted database read-only. CI uses only these local +bytes; no network is needed. The draft wide-table specification defers execution of windowed model metrics. diff --git a/tests/ossie-fixtures/upstream/d27a6be/examples/tpcds_semantic_model.yaml b/tests/ossie-fixtures/upstream/d27a6be/examples/tpcds_semantic_model.yaml new file mode 100644 index 000000000..daa513a21 --- /dev/null +++ b/tests/ossie-fixtures/upstream/d27a6be/examples/tpcds_semantic_model.yaml @@ -0,0 +1,612 @@ +# yaml-language-server: $schema=../core-spec/ossie-schema.json +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# TPC-DS Semantic Model Example +# This example demonstrates the Ossie Core Metadata Spec using the TPC-DS benchmark schema +# TPC-DS is a decision support benchmark with a realistic retail business model + +version: "0.3.0.dev0" + +name: tpcds_retail_model +description: TPC-DS retail semantic model for sales and customer analytics +ai_context: + instructions: "Use this semantic model for retail analytics. It provides comprehensive sales, customer, product, and store data from the TPC-DS benchmark. The model supports time-based analysis, customer segmentation, product performance, and store operations metrics." + +datasets: + # Fact table: Store sales transactions + - name: store_sales + source: tpcds.public.store_sales + primary_key: [ss_item_sk, ss_ticket_number] # Composite primary key + unique_keys: + - [ss_item_sk, ss_ticket_number] # Composite key: item + ticket number uniquely identifies a line item + description: Fact table containing all store sales transactions + ai_context: + synonyms: + - "sales transactions" + - "store purchases" + - "retail sales" + - "POS data" + + fields: + - name: ss_sold_date_sk + expression: + sql: ss_sold_date_sk + description: Foreign key to date dimension + datatype: Integer + dimension: + is_time: false + ai_context: + synonyms: + - "sale date" + - "transaction date" + + - name: ss_item_sk + expression: + sql: ss_item_sk + description: Foreign key to item dimension + datatype: Integer + dimension: + is_time: false + ai_context: + synonyms: + - "product" + - "item" + + - name: ss_ticket_number + expression: + sql: ss_ticket_number + description: Ticket number identifying the sales transaction + datatype: Integer + dimension: + is_time: false + + - name: ss_customer_sk + expression: + sql: ss_customer_sk + description: Foreign key to customer dimension + datatype: Integer + dimension: + is_time: false + ai_context: + synonyms: + - "customer" + - "buyer" + + - name: ss_store_sk + expression: + sql: ss_store_sk + description: Foreign key to store dimension + datatype: Integer + dimension: + is_time: false + ai_context: + synonyms: + - "store" + - "location" + + - name: ss_quantity + expression: + sql: ss_quantity + description: Quantity of items sold + datatype: Integer + ai_context: + synonyms: + - "units sold" + - "quantity" + + - name: ss_sales_price + expression: + sql: ss_sales_price + description: Sales price per unit + datatype: Decimal + ai_context: + synonyms: + - "unit price" + - "price" + + - name: ss_ext_sales_price + expression: + sql: ss_ext_sales_price + description: Extended sales price (quantity * price) + datatype: Decimal + ai_context: + synonyms: + - "total price" + - "line total" + + - name: ss_net_profit + expression: + sql: ss_net_profit + description: Net profit from the sale + datatype: Decimal + ai_context: + synonyms: + - "profit" + - "margin" + + # Dataset-scoped metric: aggregates this dataset's own declared field by + # single-part (unqualified) name; resolves within store_sales. Contrast with + # the model-root `metrics:` block below, whose expressions span datasets. + metrics: + - name: total_quantity + expression: + sql: SUM(ss_quantity) + description: Total quantity sold across all store sales + datatype: Integer + + # Dimension table: Date + - name: date_dim + source: tpcds.public.date_dim + primary_key: [d_date_sk] # Simple primary key + unique_keys: + - [d_date_sk] # Simple key: single column + description: Date dimension with calendar attributes + ai_context: + synonyms: + - "calendar" + - "dates" + - "time periods" + + fields: + - name: d_date_sk + expression: + sql: d_date_sk + description: Surrogate key for date + datatype: Integer + dimension: + is_time: false + + - name: d_date + expression: + sql: d_date + description: Actual date value + datatype: Date + dimension: {} + ai_context: + synonyms: + - "date" + - "calendar date" + + - name: d_year + expression: + sql: d_year + description: Year + datatype: Integer + dimension: + is_time: true + ai_context: + synonyms: + - "year" + + # Declares temporal role via is_time without a datatype annotation. + # Both datatype and is_time are independently optional. + - name: d_quarter_name + expression: + sql: d_quarter_name + description: Quarter name (e.g., 2024Q1) + dimension: + is_time: true + ai_context: + synonyms: + - "quarter" + - "fiscal quarter" + + # Declares temporal role via is_time without a datatype annotation. + # Both datatype and is_time are independently optional. + - name: d_moy + expression: + sql: d_moy + description: Month of year (1-12) + dimension: + is_time: true + ai_context: + synonyms: + - "month" + + # Dimension table: Customer + - name: customer + source: tpcds.public.customer + primary_key: [c_customer_sk] # Simple primary key + unique_keys: + - [c_customer_sk] # Simple key: single column + - [c_customer_id] # Alternate key: customer business key + description: Customer dimension with demographic information + ai_context: + synonyms: + - "customers" + - "shoppers" + - "buyers" + + fields: + - name: c_customer_sk + expression: + sql: c_customer_sk + description: Surrogate key for customer + datatype: Integer + dimension: + is_time: false + + - name: c_customer_id + expression: + sql: c_customer_id + description: Business key for customer + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "customer ID" + - "customer number" + + - name: c_first_name + expression: + sql: c_first_name + description: Customer first name + datatype: String + dimension: + is_time: false + + - name: c_last_name + expression: + sql: c_last_name + description: Customer last name + datatype: String + dimension: + is_time: false + + - name: customer_full_name + expression: + # Primary, portable OSSIE_SQL_2026 form + sql: c_first_name || ' ' || c_last_name + description: Customer full name (computed field) + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "full name" + - "customer name" + + - name: c_email_address + expression: + sql: c_email_address + description: Customer email address + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "email" + - "contact" + + # Dimension table: Item (Product) + - name: item + source: tpcds.public.item + primary_key: [i_item_sk] # Simple primary key + unique_keys: + - [i_item_sk] # Simple key: single column + description: Item/Product dimension with product attributes + ai_context: + synonyms: + - "products" + - "items" + - "merchandise" + + fields: + - name: i_item_sk + expression: + sql: i_item_sk + description: Surrogate key for item + datatype: Integer + dimension: + is_time: false + + - name: i_item_id + expression: + sql: i_item_id + description: Business key for item + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "item ID" + - "product ID" + - "SKU" + + - name: i_item_desc + expression: + sql: i_item_desc + description: Item description + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "product description" + - "item name" + + - name: i_brand + expression: + sql: i_brand + description: Brand name + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "brand" + - "manufacturer" + + - name: i_category + expression: + sql: i_category + description: Item category + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "product category" + - "department" + + - name: i_current_price + expression: + sql: i_current_price + description: Current price of the item + datatype: Decimal + dimension: + is_time: false + ai_context: + synonyms: + - "price" + - "list price" + + # Dimension table: Store + - name: store + source: tpcds.public.store + primary_key: [s_store_sk] # Simple primary key + unique_keys: + - [s_store_sk] # Simple key: single column + description: Store dimension with location and store attributes + ai_context: + synonyms: + - "stores" + - "retail locations" + - "branches" + + fields: + - name: s_store_sk + expression: + sql: s_store_sk + description: Surrogate key for store + datatype: Integer + dimension: + is_time: false + + - name: s_store_id + expression: + sql: s_store_id + description: Business key for store + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "store ID" + - "store number" + + - name: s_store_name + expression: + sql: s_store_name + description: Store name + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "store name" + - "location name" + + - name: s_city + expression: + sql: s_city + description: City where store is located + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "city" + - "location" + + - name: s_state + expression: + sql: s_state + description: State where store is located + datatype: String + dimension: + is_time: false + ai_context: + synonyms: + - "state" + - "region" + + - name: s_number_employees + expression: + sql: s_number_employees + description: Number of employees at the store + datatype: Integer + ai_context: + synonyms: + - "employee count" + - "staff size" + +# Relationships between datasets +relationships: + - name: store_sales_to_date + from: store_sales + to: date_dim + from_columns: [ss_sold_date_sk] + to_columns: [d_date_sk] + ai_context: + synonyms: + - "sales date relationship" + - "when sale occurred" + + - name: store_sales_to_customer + from: store_sales + to: customer + from_columns: [ss_customer_sk] + to_columns: [c_customer_sk] + ai_context: + synonyms: + - "customer purchase relationship" + - "who bought" + + - name: store_sales_to_item + from: store_sales + to: item + from_columns: [ss_item_sk] + to_columns: [i_item_sk] + ai_context: + synonyms: + - "product sold relationship" + - "what was sold" + + - name: store_sales_to_store + from: store_sales + to: store + from_columns: [ss_store_sk] + to_columns: [s_store_sk] + ai_context: + synonyms: + - "store location relationship" + - "where sale occurred" + +# Semantic model-level metrics spanning multiple datasets +metrics: + - name: total_sales + expression: + sql: SUM(store_sales.ss_ext_sales_price) + description: Total sales revenue across all transactions + datatype: Decimal + ai_context: + synonyms: + - "total revenue" + - "gross sales" + - "sales amount" + + - name: total_profit + expression: + sql: SUM(store_sales.ss_net_profit) + description: Total net profit from store sales + datatype: Decimal + ai_context: + synonyms: + - "net profit" + - "total earnings" + - "profit" + + - name: customer_lifetime_value + expression: + sql: SUM(store_sales.ss_ext_sales_price) / COUNT(DISTINCT customer.c_customer_sk) + description: Average lifetime sales value per customer + datatype: Decimal + ai_context: + synonyms: + - "CLV" + - "LTV" + - "customer value" + - "lifetime revenue" + + - name: sales_by_brand + expression: + sql: SUM(store_sales.ss_ext_sales_price) + description: Total sales by brand (requires grouping by item.i_brand) + datatype: Decimal + ai_context: + synonyms: + - "brand sales" + - "brand performance" + - "brand revenue" + + # See Appendix B.6 of core-spec/wide_table_semantics.md for the branch lowering. + - name: store_productivity + expression: + sql: SUM(store_sales.ss_ext_sales_price) / NULLIF(SUM(store.s_number_employees), 0) + description: Sales per employee across stores + datatype: Decimal + ai_context: + synonyms: + - "sales per employee" + - "employee productivity" + - "revenue per employee" + + # Window-function metrics. Each one wraps an aggregate in a window, so the + # grain named in the description is the GROUP BY the query is expected to supply. + - name: cumulative_sales + expression: + sql: SUM(SUM(store_sales.ss_ext_sales_price)) OVER (ORDER BY date_dim.d_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) + description: Running total of sales revenue by date (requires grouping by date_dim.d_date) + datatype: Decimal + ai_context: + synonyms: + - "running total sales" + - "cumulative revenue" + - "sales to date" + + - name: brand_rank_in_store + expression: + sql: RANK() OVER (PARTITION BY store.s_store_sk ORDER BY SUM(store_sales.ss_ext_sales_price) DESC) + description: Rank of each brand by sales within a store, 1 = highest (requires grouping by store.s_store_sk and item.i_brand) + datatype: Integer + ai_context: + synonyms: + - "brand ranking by store" + - "top brands per store" + - "store brand leaderboard" + + - name: monthly_sales_change + expression: + sql: SUM(store_sales.ss_ext_sales_price) - LAG(SUM(store_sales.ss_ext_sales_price), 1) OVER (ORDER BY date_dim.d_year, date_dim.d_moy) + description: Sales revenue change versus the previous month (requires grouping by date_dim.d_year and date_dim.d_moy) + datatype: Decimal + ai_context: + synonyms: + - "month over month sales change" + - "MoM sales" + - "sales delta" + +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" + + - vendor_name: DBT + data: + project_name: tpcds_analytics + models_path: models/semantic diff --git a/tests/ossie-fixtures/upstream/faf5810/LICENSE b/tests/ossie-fixtures/upstream/faf5810/LICENSE new file mode 100644 index 000000000..67db85882 --- /dev/null +++ b/tests/ossie-fixtures/upstream/faf5810/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/tests/ossie-fixtures/upstream/faf5810/LICENSE-Docs b/tests/ossie-fixtures/upstream/faf5810/LICENSE-Docs new file mode 100644 index 000000000..49ce653bf --- /dev/null +++ b/tests/ossie-fixtures/upstream/faf5810/LICENSE-Docs @@ -0,0 +1,317 @@ +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. diff --git a/tests/ossie-fixtures/upstream/faf5810/NOTICE b/tests/ossie-fixtures/upstream/faf5810/NOTICE new file mode 100644 index 000000000..2deb0796f --- /dev/null +++ b/tests/ossie-fixtures/upstream/faf5810/NOTICE @@ -0,0 +1,2 @@ +Open Semantic Interchange +Copyright 2026 - Open Semantic Interchange diff --git a/tests/ossie-fixtures/upstream/faf5810/README.md b/tests/ossie-fixtures/upstream/faf5810/README.md new file mode 100644 index 000000000..fb5fbed6e --- /dev/null +++ b/tests/ossie-fixtures/upstream/faf5810/README.md @@ -0,0 +1,17 @@ +# Released Ossie 0.1.1 real-file fixture + +`examples/tpcds_semantic_model.yaml` is an unchanged copy from Apache Ossie +commit [`faf581054dcf7964d5fe0ceae7d6f415c8ce32a5`](https://github.com/apache/ossie/blob/faf581054dcf7964d5fe0ceae7d6f415c8ce32a5/examples/tpcds_semantic_model.yaml). +The file declares `version: "0.1.1"`. SHA-256: +`1c8c8e1a41d6b1b4d957ae5934b883b46ca07ad3901927ec6ce0ecff55d2cb6b`. + +`LICENSE`, `LICENSE-Docs`, and `NOTICE` are unchanged files from the same commit. +Retrieved November 24, 2026. The older `tests/fixtures/osi/tpcds_osi_official.yaml` +has different bytes and a different declared version; it is not this fixture. + +`sqlctx-duckdb/test/test_catalog_host.py` loads this exact file through +`sqlctx_load_file`, creates matching `tpcds.public` physical sources, and asserts +total sales, total profit, joined brand sales, filtered sales, customer lifetime +value, and store productivity. It repeats +the queries after reopening the persisted database read-only. CI uses only +these local bytes; no network is needed. diff --git a/tests/ossie-fixtures/upstream/faf5810/examples/tpcds_semantic_model.yaml b/tests/ossie-fixtures/upstream/faf5810/examples/tpcds_semantic_model.yaml new file mode 100644 index 000000000..98e956b1b --- /dev/null +++ b/tests/ossie-fixtures/upstream/faf5810/examples/tpcds_semantic_model.yaml @@ -0,0 +1,578 @@ +# yaml-language-server: $schema=../core-spec/osi-schema.json + +# TPC-DS Semantic Model Example +# This example demonstrates the OSI Core Metadata Spec using the TPC-DS benchmark schema +# TPC-DS is a decision support benchmark with a realistic retail business model + +version: "0.1.1" + +semantic_model: + - name: tpcds_retail_model + description: TPC-DS retail semantic model for sales and customer analytics + ai_context: + instructions: "Use this semantic model for retail analytics. It provides comprehensive sales, customer, product, and store data from the TPC-DS benchmark. The model supports time-based analysis, customer segmentation, product performance, and store operations metrics." + + datasets: + # Fact table: Store sales transactions + - name: store_sales + source: tpcds.public.store_sales + primary_key: [ss_item_sk, ss_ticket_number] # Composite primary key + unique_keys: + - [ss_item_sk, ss_ticket_number] # Composite key: item + ticket number uniquely identifies a line item + description: Fact table containing all store sales transactions + ai_context: + synonyms: + - "sales transactions" + - "store purchases" + - "retail sales" + - "POS data" + + fields: + - name: ss_sold_date_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_sold_date_sk + description: Foreign key to date dimension + dimension: + is_time: false + ai_context: + synonyms: + - "sale date" + - "transaction date" + + - name: ss_item_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_item_sk + description: Foreign key to item dimension + dimension: + is_time: false + ai_context: + synonyms: + - "product" + - "item" + + - name: ss_customer_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_customer_sk + description: Foreign key to customer dimension + dimension: + is_time: false + ai_context: + synonyms: + - "customer" + - "buyer" + + - name: ss_store_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_store_sk + description: Foreign key to store dimension + dimension: + is_time: false + ai_context: + synonyms: + - "store" + - "location" + + - name: ss_quantity + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_quantity + description: Quantity of items sold + ai_context: + synonyms: + - "units sold" + - "quantity" + + - name: ss_sales_price + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_sales_price + description: Sales price per unit + ai_context: + synonyms: + - "unit price" + - "price" + + - name: ss_ext_sales_price + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_ext_sales_price + description: Extended sales price (quantity * price) + ai_context: + synonyms: + - "total price" + - "line total" + + - name: ss_net_profit + expression: + dialects: + - dialect: ANSI_SQL + expression: ss_net_profit + description: Net profit from the sale + ai_context: + synonyms: + - "profit" + - "margin" + + # Dimension table: Date + - name: date_dim + source: tpcds.public.date_dim + primary_key: [d_date_sk] # Simple primary key + unique_keys: + - [d_date_sk] # Simple key: single column + description: Date dimension with calendar attributes + ai_context: + synonyms: + - "calendar" + - "dates" + - "time periods" + + fields: + - name: d_date_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: d_date_sk + description: Surrogate key for date + dimension: + is_time: false + + - name: d_date + expression: + dialects: + - dialect: ANSI_SQL + expression: d_date + description: Actual date value + dimension: + is_time: true + ai_context: + synonyms: + - "date" + - "calendar date" + + - name: d_year + expression: + dialects: + - dialect: ANSI_SQL + expression: d_year + description: Year + dimension: + is_time: true + ai_context: + synonyms: + - "year" + + - name: d_quarter_name + expression: + dialects: + - dialect: ANSI_SQL + expression: d_quarter_name + description: Quarter name (e.g., 2024Q1) + dimension: + is_time: true + ai_context: + synonyms: + - "quarter" + - "fiscal quarter" + + - name: d_month_name + expression: + dialects: + - dialect: ANSI_SQL + expression: d_month_name + description: Month name + dimension: + is_time: true + ai_context: + synonyms: + - "month" + + # Dimension table: Customer + - name: customer + source: tpcds.public.customer + primary_key: [c_customer_sk] # Simple primary key + unique_keys: + - [c_customer_sk] # Simple key: single column + description: Customer dimension with demographic information + ai_context: + synonyms: + - "customers" + - "shoppers" + - "buyers" + + fields: + - name: c_customer_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: c_customer_sk + description: Surrogate key for customer + dimension: + is_time: false + + - name: c_customer_id + expression: + dialects: + - dialect: ANSI_SQL + expression: c_customer_id + description: Business key for customer + dimension: + is_time: false + ai_context: + synonyms: + - "customer ID" + - "customer number" + + - name: c_first_name + expression: + dialects: + - dialect: ANSI_SQL + expression: c_first_name + description: Customer first name + dimension: + is_time: false + + - name: c_last_name + expression: + dialects: + - dialect: ANSI_SQL + expression: c_last_name + description: Customer last name + dimension: + is_time: false + + - name: customer_full_name + expression: + dialects: + - dialect: ANSI_SQL + expression: c_first_name || ' ' || c_last_name + description: Customer full name (computed field) + dimension: + is_time: false + ai_context: + synonyms: + - "full name" + - "customer name" + + - name: c_email_address + expression: + dialects: + - dialect: ANSI_SQL + expression: c_email_address + description: Customer email address + dimension: + is_time: false + ai_context: + synonyms: + - "email" + - "contact" + + # Dimension table: Item (Product) + - name: item + source: tpcds.public.item + primary_key: [i_item_sk] # Simple primary key + unique_keys: + - [i_item_sk] # Simple key: single column + description: Item/Product dimension with product attributes + ai_context: + synonyms: + - "products" + - "items" + - "merchandise" + + fields: + - name: i_item_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: i_item_sk + description: Surrogate key for item + dimension: + is_time: false + + - name: i_item_id + expression: + dialects: + - dialect: ANSI_SQL + expression: i_item_id + description: Business key for item + dimension: + is_time: false + ai_context: + synonyms: + - "item ID" + - "product ID" + - "SKU" + + - name: i_item_desc + expression: + dialects: + - dialect: ANSI_SQL + expression: i_item_desc + description: Item description + dimension: + is_time: false + ai_context: + synonyms: + - "product description" + - "item name" + + - name: i_brand + expression: + dialects: + - dialect: ANSI_SQL + expression: i_brand + description: Brand name + dimension: + is_time: false + ai_context: + synonyms: + - "brand" + - "manufacturer" + + - name: i_category + expression: + dialects: + - dialect: ANSI_SQL + expression: i_category + description: Item category + dimension: + is_time: false + ai_context: + synonyms: + - "product category" + - "department" + + - name: i_current_price + expression: + dialects: + - dialect: ANSI_SQL + expression: i_current_price + description: Current price of the item + dimension: + is_time: false + ai_context: + synonyms: + - "price" + - "list price" + + # Dimension table: Store + - name: store + source: tpcds.public.store + primary_key: [s_store_sk] # Simple primary key + unique_keys: + - [s_store_id] # Simple key: single column + description: Store dimension with location and store attributes + ai_context: + synonyms: + - "stores" + - "retail locations" + - "branches" + + fields: + - name: s_store_sk + expression: + dialects: + - dialect: ANSI_SQL + expression: s_store_sk + description: Surrogate key for store + dimension: + is_time: false + + - name: s_store_id + expression: + dialects: + - dialect: ANSI_SQL + expression: s_store_id + description: Business key for store + dimension: + is_time: false + ai_context: + synonyms: + - "store ID" + - "store number" + + - name: s_store_name + expression: + dialects: + - dialect: ANSI_SQL + expression: s_store_name + description: Store name + dimension: + is_time: false + ai_context: + synonyms: + - "store name" + - "location name" + + - name: s_city + expression: + dialects: + - dialect: ANSI_SQL + expression: s_city + description: City where store is located + dimension: + is_time: false + ai_context: + synonyms: + - "city" + - "location" + + - name: s_state + expression: + dialects: + - dialect: ANSI_SQL + expression: s_state + description: State where store is located + dimension: + is_time: false + ai_context: + synonyms: + - "state" + - "region" + + - name: s_number_employees + expression: + dialects: + - dialect: ANSI_SQL + expression: s_number_employees + description: Number of employees at the store + ai_context: + synonyms: + - "employee count" + - "staff size" + + # Relationships between datasets + relationships: + - name: store_sales_to_date + from: store_sales + to: date_dim + from_columns: [ss_sold_date_sk] + to_columns: [d_date_sk] + ai_context: + synonyms: + - "sales date relationship" + - "when sale occurred" + + - name: store_sales_to_customer + from: store_sales + to: customer + from_columns: [ss_customer_sk] + to_columns: [c_customer_sk] + ai_context: + synonyms: + - "customer purchase relationship" + - "who bought" + + - name: store_sales_to_item + from: store_sales + to: item + from_columns: [ss_item_sk] + to_columns: [i_item_sk] + ai_context: + synonyms: + - "product sold relationship" + - "what was sold" + + - name: store_sales_to_store + from: store_sales + to: store + from_columns: [ss_store_sk] + to_columns: [s_store_sk] + ai_context: + synonyms: + - "store location relationship" + - "where sale occurred" + + # Semantic model-level metrics spanning multiple datasets + metrics: + - name: total_sales + expression: + dialects: + - dialect: ANSI_SQL + expression: SUM(store_sales.ss_ext_sales_price) + description: Total sales revenue across all transactions + ai_context: + synonyms: + - "total revenue" + - "gross sales" + - "sales amount" + + - name: total_profit + expression: + dialects: + - dialect: ANSI_SQL + expression: SUM(store_sales.ss_net_profit) + description: Total net profit from store sales + ai_context: + synonyms: + - "net profit" + - "total earnings" + - "profit" + + - name: customer_lifetime_value + expression: + dialects: + - dialect: ANSI_SQL + expression: SUM(store_sales.ss_ext_sales_price) / COUNT(DISTINCT customer.c_customer_sk) + description: Average lifetime sales value per customer + ai_context: + synonyms: + - "CLV" + - "LTV" + - "customer value" + - "lifetime revenue" + + - name: sales_by_brand + expression: + dialects: + - dialect: ANSI_SQL + expression: SUM(store_sales.ss_ext_sales_price) + description: Total sales by brand (requires grouping by item.i_brand) + ai_context: + synonyms: + - "brand sales" + - "brand performance" + - "brand revenue" + + - name: store_productivity + expression: + dialects: + - dialect: ANSI_SQL + expression: SUM(store_sales.ss_ext_sales_price) / NULLIF(SUM(store.s_number_employees), 0) + description: Sales per employee across stores + ai_context: + synonyms: + - "sales per employee" + - "employee productivity" + - "revenue per employee" + + custom_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" + } + } + + - vendor_name: DBT + data: '{"project_name": "tpcds_analytics", "models_path": "models/semantic"}'