From 1f4054cf31b35cd185b09ab7c21a6908fe0ef3fb Mon Sep 17 00:00:00 2001 From: yvonneyx <55794321+yvonneyx@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:23:56 +0800 Subject: [PATCH 1/6] refactor: remove unnecessary codes --- src/index.browser.ts | 2 -- src/index.ts | 2 -- src/types.ts | 3 +-- 3 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/index.browser.ts b/src/index.browser.ts index 12724dd24..91af0a606 100644 --- a/src/index.browser.ts +++ b/src/index.browser.ts @@ -46,8 +46,6 @@ export type { View, Cube, Measure, - CubeDimension, - TimeDimension, TableReference, PrimaryKey, Properties, diff --git a/src/index.ts b/src/index.ts index 78febca3f..d61b07fb7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,8 +57,6 @@ export type { View, Cube, Measure, - CubeDimension, - TimeDimension, TableReference, PrimaryKey, Properties, diff --git a/src/types.ts b/src/types.ts index b2f121bd9..243bd2903 100644 --- a/src/types.ts +++ b/src/types.ts @@ -57,6 +57,7 @@ export type ProfileOptions = z.input; export type Profile = z.output; export type SemanticOptions = z.input; export type Semantic = z.output; + export type ExecutionOptions = NonNullable['options']>; export type QueryColumn = z.output['schema'][number]; export type ExecutionResult> = Omit< @@ -95,8 +96,6 @@ export type JoinType = Relationship['joinType']; export type View = NonNullable[number]; export type Cube = NonNullable[number]; export type Measure = Cube['measures'][number]; -export type CubeDimension = Measure; -export type TimeDimension = CubeDimension; export type DataSourceConfig = z.input; export type ParsedDataSourceConfig = z.output & { name: string }; From 2cb459d12b7aee0ea2f9140711bce7ccc15fa240 Mon Sep 17 00:00:00 2001 From: yvonneyx <55794321+yvonneyx@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:26:36 +0800 Subject: [PATCH 2/6] feat(semantic): validate Ossie models against the JSON schema --- package.json | 1 + src/util/semantic/ossie/DISCLAIMER | 16 + src/util/semantic/ossie/LICENSE | 201 +++++++++++ src/util/semantic/ossie/NOTICE | 5 + src/util/semantic/ossie/ossie-schema.json | 391 ++++++++++++++++++++++ src/util/semantic/ossie/util.ts | 24 ++ 6 files changed, 638 insertions(+) create mode 100644 src/util/semantic/ossie/DISCLAIMER create mode 100644 src/util/semantic/ossie/LICENSE create mode 100644 src/util/semantic/ossie/NOTICE create mode 100644 src/util/semantic/ossie/ossie-schema.json create mode 100644 src/util/semantic/ossie/util.ts diff --git a/package.json b/package.json index 6f0bb8a20..19090f033 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,7 @@ "@supabase/pg-parser": "^0.1.7", "adm-zip": "^0.6.1", "ai": "^7.0.112", + "ajv": "^8.20.0", "antlr4ts": "^0.5.0-alpha.4", "antlr4ts-sql": "^1.1.0", "csv-parse": "^7.0.3", diff --git a/src/util/semantic/ossie/DISCLAIMER b/src/util/semantic/ossie/DISCLAIMER new file mode 100644 index 000000000..62af36e86 --- /dev/null +++ b/src/util/semantic/ossie/DISCLAIMER @@ -0,0 +1,16 @@ +Apache Ossie is an effort undergoing incubation at the Apache Software +Foundation (ASF), sponsored by the Apache Incubator PMC. + +Incubation is required of all newly accepted projects until a further review +indicates that the infrastructure, communications, and decision making process +have stabilized in a manner consistent with other successful ASF projects. + +While incubation status is not necessarily a reflection of the completeness +or stability of the code, it does indicate that the project has yet to be +fully endorsed by the ASF. + +If you are planning to incorporate this work into your product/project, please +be aware that you will need to conduct a thorough licensing review to determine +the overall implications of including this work. For the current status of this +project through the Apache Incubator visit: +https://incubator.apache.org/projects/ossie.html diff --git a/src/util/semantic/ossie/LICENSE b/src/util/semantic/ossie/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/src/util/semantic/ossie/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/src/util/semantic/ossie/NOTICE b/src/util/semantic/ossie/NOTICE new file mode 100644 index 000000000..e4bc78e2b --- /dev/null +++ b/src/util/semantic/ossie/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/src/util/semantic/ossie/ossie-schema.json b/src/util/semantic/ossie/ossie-schema.json new file mode 100644 index 000000000..e9f720a8d --- /dev/null +++ b/src/util/semantic/ossie/ossie-schema.json @@ -0,0 +1,391 @@ +{ + "$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/src/util/semantic/ossie/util.ts b/src/util/semantic/ossie/util.ts new file mode 100644 index 000000000..3517c7488 --- /dev/null +++ b/src/util/semantic/ossie/util.ts @@ -0,0 +1,24 @@ +import { Ajv2020 } from 'ajv/dist/2020'; + +import ossieSchema from './ossie-schema.json'; + +import type { ErrorObject } from 'ajv'; + +const validate = new Ajv2020({ allErrors: true }).compile(ossieSchema); + +/** + * @param value A parsed value to check against the bundled Ossie JSON Schema. + * @returns Whether the value conforms to the schema. + */ +export function isOssieModel(value: unknown): boolean { + return validate(value); +} + +/** + * @param value A parsed value to check against the bundled Ossie JSON Schema. + * @returns All Ajv errors with their JSON Pointer paths, or an empty array for a valid model. + */ +export function getOssieModelErrors(value: unknown): ErrorObject[] { + validate(value); + return validate.errors ?? []; +} From 28eb6c47e8145a583d003a2b7dc413205fa7eef4 Mon Sep 17 00:00:00 2001 From: yvonneyx <55794321+yvonneyx@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:00:31 +0800 Subject: [PATCH 3/6] feat(semantic): add local Ossie document types --- src/util/semantic/ossie/types.ts | 179 +++++++++++++++++++++++++++++++ src/util/semantic/ossie/util.ts | 5 +- 2 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 src/util/semantic/ossie/types.ts diff --git a/src/util/semantic/ossie/types.ts b/src/util/semantic/ossie/types.ts new file mode 100644 index 000000000..43ac1dc72 --- /dev/null +++ b/src/util/semantic/ossie/types.ts @@ -0,0 +1,179 @@ +/** + * SPDX-License-Identifier: Apache-2.0 + * Source: https://www.npmjs.com/package/@lovable.dev/lovsem/v/0.1.1 + */ + +type JsonValue = number | string | boolean | Array | { [key in string]: JsonValue } | null; + +/** + * Structured AI context with known fields plus arbitrary extension properties. + */ +type AiContextStructured = { + instructions?: string | null; + synonyms?: Array | null; + examples?: Array | null; +} & { [key in string]: number | string | boolean | Array | { [key in string]: JsonValue } | null }; + +/** + * Additional context for AI tools: plain string or structured object. + * + * The object form allows `instructions`, `synonyms`, `examples`, and any other keys + * (JSON Schema `additionalProperties: true` on the object branch). + */ +type AiContext = string | AiContextStructured; + +/** + * Logical value type of a field or metric (`$defs.DataType`). + * + * Declares the value type independently of role and physical representation. + * Omit when the type is unknown; use [`DataType::Opaque`] for a known type + * outside this vocabulary. + */ +type DataType = + | 'String' + | 'Integer' + | 'Decimal' + | 'Float' + | 'Boolean' + | 'Date' + | 'Time' + | 'DateTime' + | 'DateTimeTz' + | 'Opaque'; + +/** + * The language an expression is written in (`$defs.Dialect`). + * + * Any non-empty token is valid. The spec defines only + * [`OSSIE_SQL_2026`](Self::OSSIE_SQL_2026); the other constants are tokens + * from upstream's `extensions/dialects.md` that this crate's users read. + */ +type Dialect = string; + +/** + * Expression in a specific dialect. + */ +type DialectExpression = { + dialect: Dialect; + expression: string; +}; + +/** + * An expression: portable `sql`, dialect-specific entries, or both. + * + * `sql` is written in [`Dialect::OSSIE_SQL_2026`] and wins over an + * `OSSIE_SQL_2026` entry in `dialects`. The schema requires one of the two. + */ +type Expression = { + sql?: string | null; + dialects?: Array; +}; + +/** + * Dimension metadata on a field (`$defs.Dimension`). + */ +type FieldDimension = { + /** + * Temporal-**role** marker, independent of the field's data type. + * + * When unset the effective value is derived from `datatype`; see + * [`Field::is_time_dimension`]. + */ + is_time?: boolean | null; +}; + +/** + * Vendor-specific state that Ossie carries and does not interpret. + * + * `vendor_name` is any non-empty string, and the keys under `data` are the + * vendor's own. + */ +type NonportableExtension = { + vendor_name: string; + data: { [key in string]: JsonValue }; +}; + +/** + * Row-level attribute for grouping, filtering, and metric expressions. + */ +type Field = { + name: string; + expression: Expression; + dimension?: FieldDimension | null; + label?: string | null; + description?: string | null; + /** + * Logical value type. Omit when unknown or unspecified. + */ + datatype?: DataType | null; + ai_context?: AiContext | null; + nonportable_extensions?: Array; +}; + +/** + * Quantitative measure defined on business data. + */ +type Metric = { + name: string; + expression: Expression; + description?: string | null; + /** + * Logical value type. Omit when unknown or unspecified. + */ + datatype?: DataType | null; + ai_context?: AiContext | null; + nonportable_extensions?: Array; +}; + +/** + * Logical dataset (fact or dimension table). + */ +type Dataset = { + name: string; + source: string; + primary_key?: Array; + unique_keys?: Array>; + description?: string | null; + ai_context?: AiContext | null; + fields?: Array; + /** + * Dataset-scoped metrics: aggregates over this dataset's declared fields, + * referenced from outside as `dataset.metric`. Fields and these metrics + * share one namespace. + */ + metrics?: Array; + nonportable_extensions?: Array; +}; + +/** + * Foreign key relationship between logical datasets. + */ +type Relationship = { + name: string; + from: string; + to: string; + from_columns: Array; + to_columns: Array; + ai_context?: AiContext | null; + nonportable_extensions?: Array; +}; + +/** + * Root document for the Ossie core metadata spec. + * + * Since `0.3.0.dev0` a standalone document carries **exactly one** model, with + * the model's properties at the document root — the `semantic_model` array and + * the root-level `dialects` / `vendors` declarations were removed. The reusable + * [`SemanticModel`] shape is unchanged and is still what an ontology map embeds + * under its own `semantic_model` property, so it stays a distinct type here. + */ +export type OssieDocument = { + version: string; + name: string; + description?: string | null; + ai_context?: AiContext | null; + datasets: Array; + relationships?: Array; + metrics?: Array; + nonportable_extensions?: Array; +}; diff --git a/src/util/semantic/ossie/util.ts b/src/util/semantic/ossie/util.ts index 3517c7488..cf5128a5c 100644 --- a/src/util/semantic/ossie/util.ts +++ b/src/util/semantic/ossie/util.ts @@ -2,15 +2,16 @@ import { Ajv2020 } from 'ajv/dist/2020'; import ossieSchema from './ossie-schema.json'; +import type { OssieDocument } from './types'; import type { ErrorObject } from 'ajv'; -const validate = new Ajv2020({ allErrors: true }).compile(ossieSchema); +const validate = new Ajv2020({ allErrors: true }).compile(ossieSchema); /** * @param value A parsed value to check against the bundled Ossie JSON Schema. * @returns Whether the value conforms to the schema. */ -export function isOssieModel(value: unknown): boolean { +export function isOssieModel(value: unknown): value is OssieDocument { return validate(value); } From 216e5c4faeb43dff43fa09eb040c9a48ed8428e6 Mon Sep 17 00:00:00 2001 From: yvonneyx <55794321+yvonneyx@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:52:37 +0800 Subject: [PATCH 4/6] feat: introduce apache ossie modal --- README.md | 6 +- README.zh-CN.md | 6 +- __tests__/ava.test.ts | 58 +- __tests__/cli-session.test.ts | 6 +- __tests__/cli.test.ts | 10 +- __tests__/contracts.test.ts | 3 +- __tests__/query/clickhouse-sql.test.ts | 8 +- __tests__/query/duckdb-sql.test.ts | 8 +- __tests__/query/interpreters.test.ts | 21 +- __tests__/query/postgresql.test.ts | 17 +- __tests__/query/tsql.test.ts | 8 +- .../__snapshots__/data-model.test.ts.snap | 153 +---- __tests__/util/data-model.test.ts | 545 ++++------------ data/retail-semantics/README.md | 7 +- data/retail-semantics/semantic-finance.json | 581 +++++++++--------- data/retail-semantics/semantic-trading.json | 581 +++++++++--------- evals/ava-workflow/README.md | 2 +- evals/ava-workflow/workflow.ts | 4 +- site/ai/core/session.ts | 2 +- site/ai/core/tools.ts | 2 +- site/content/docs/en/data/schema.mdx | 17 +- site/content/docs/en/data/semantic.mdx | 78 +-- site/content/docs/en/engines/custom.mdx | 12 +- site/content/docs/en/reference/api.mdx | 233 +------ site/content/docs/zh/data/schema.mdx | 17 +- site/content/docs/zh/data/semantic.mdx | 78 +-- site/content/docs/zh/engines/custom.mdx | 10 +- site/content/docs/zh/reference/api.mdx | 233 +------ site/public/llms.txt | 2 +- skills/ava/references/semantic.md | 142 ++--- src/cli/commands/semantic.ts | 2 +- src/contracts/semantic.ts | 149 ++++- src/contracts/shared/data-model.ts | 134 ++-- src/index.browser.ts | 10 - src/index.ts | 10 - src/types.ts | 21 +- src/util/data-model.ts | 121 ++-- src/util/semantic/ossie/types.ts | 249 +++++--- 38 files changed, 1388 insertions(+), 2158 deletions(-) diff --git a/README.md b/README.md index fc8aeae61..9c7034730 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,11 @@ Inspect the structure and data quality, then add [business definitions](https:// const schema = await ava.schema(); const profile = await ava.profile({ metrics: ['row_count', 'null_count'] }); await ava.semantic(undefined, () => ({ - description: 'Use the sales column for amounts after discounts and order_date for monthly comparisons.', + models: [{ + name: 'sales', + description: 'Use sales for amounts after discounts and order_date for monthly comparisons.', + datasets: [{ name: 'orders', source: 'data' }], + }], })); ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index ab792ac49..6d9e7fafd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -127,7 +127,11 @@ await ava.source({ type: 'csv-file', options: { path: './sales.csv' } }); const schema = await ava.schema(); const profile = await ava.profile({ metrics: ['row_count', 'null_count'] }); await ava.semantic(undefined, () => ({ - description: 'sales 字段表示折后销售额,月度比较使用 order_date 字段。', + models: [{ + name: 'sales', + description: 'sales 表示折后销售额,按月比较时使用 order_date。', + datasets: [{ name: 'orders', source: 'data' }], + }], })); ``` diff --git a/__tests__/ava.test.ts b/__tests__/ava.test.ts index 27b7f16d6..de226bc5d 100644 --- a/__tests__/ava.test.ts +++ b/__tests__/ava.test.ts @@ -530,6 +530,10 @@ describe('AVA metadata setters', () => { ], }; + function semanticDescription(description: string): Semantic { + return { models: [{ name: 'sales', description, datasets: [{ name: 'values', source: 'data' }] }] }; + } + afterEach(() => vi.restoreAllMocks()); it.each(['duckdb', 'javascript'])( @@ -540,26 +544,28 @@ describe('AVA metadata setters', () => { await ava.source(source); const discover = vi.spyOn(ava.engine!, 'schema'); expect(await ava.semantic()).toEqual({}); - const definitions: Semantic = { - description: 'Sales definitions', - properties: { currency: 'USD' }, + const definitions = { models: [ { - ...schema.models[0], - properties: { description: 'Values' }, - columns: [{ name: 'value', type: 'number', properties: { unit: 'USD' } }], - }, - ], - relationships: [], - views: [{ name: 'positive_values', statement: 'SELECT * FROM data WHERE value > 0' }], - cubes: [ - { - name: 'values', - baseObject: 'data', - measures: [{ name: 'total', expression: 'SUM(value)', type: 'DOUBLE' }], + name: 'sales', + description: 'Sales definitions', + datasets: [ + { + name: 'values', + source: 'data', + fields: [ + { + name: 'value', + expression: { sql: 'value' }, + description: 'Values in USD', + }, + ], + metrics: [{ name: 'total', expression: { sql: 'SUM(value)' } }], + }, + ], }, ], - }; + } satisfies Semantic; const expected = structuredClone(definitions); const options = {}; const setter = vi.fn(() => definitions); @@ -573,8 +579,8 @@ describe('AVA metadata setters', () => { { type: 'semanticstart', data: {} }, { type: 'semanticend', data: {} }, ]); - definitions.description = 'changed'; - definitions.models[0].columns[0].properties.unit = 'changed'; + definitions.models[0].description = 'changed'; + definitions.models[0].datasets[0].fields[0].description = 'changed'; expect(await ava.semantic()).toEqual(expected); expect(onSemantic).toHaveBeenCalledTimes(2); @@ -589,11 +595,11 @@ describe('AVA metadata setters', () => { await ava.translate('Total'); const context = getDSL.mock.calls[0][1]; const snapshot = structuredClone(context); - expect(context).toMatchObject(expected); + expect(context.semantic).toEqual(expected); expect(context.models[0].metrics).toEqual({ row_count: 2 }); expect(context.models[0].columns[0]).toMatchObject({ metrics: { mean: 3 }, - properties: { logicalType: 'numeric', unit: 'USD' }, + logicalType: 'numeric', }); expect( (await ava.analyze('Total', { includeSummary: false, strategy: { type: 'direct', maxRetries: 0 } })).data @@ -608,7 +614,7 @@ describe('AVA metadata setters', () => { await ava.semantic(undefined, () => ({})); await ava.translate('Total'); - expect(getDSL.mock.calls.at(-1)[1]).not.toHaveProperty('cubes'); + expect(getDSL.mock.calls.at(-1)[1]).not.toHaveProperty('semantic'); expect(getDSL.mock.calls[0][1]).toEqual(snapshot); } finally { await ava.dispose(); @@ -620,7 +626,7 @@ describe('AVA metadata setters', () => { const ava = new AVA({ llm, engine: { type: 'javascript' } }); try { await ava.source(source); - const setter = vi.fn(() => ({ description: 'Original' })); + const setter = vi.fn(() => semanticDescription('Original')); await ava.semantic(undefined, setter); expect(setter).toHaveBeenCalledExactlyOnceWith({}); const onEnd = vi.fn(); @@ -636,7 +642,7 @@ describe('AVA metadata setters', () => { ).rejects.toThrow(); expect(onEnd.mock.calls[0][0].data.error.message).toBe(error.message); expect(onEnd.mock.calls[1][0].data.error.name).toBe('ZodError'); - expect(await ava.semantic()).toEqual({ description: 'Original' }); + expect(await ava.semantic()).toEqual(semanticDescription('Original')); } finally { await ava.dispose(); } @@ -805,7 +811,7 @@ describe('AVA metadata setters', () => { await ava.source(source); await ava.schema(undefined, () => schema); await ava.profile(undefined, () => profile); - await ava.semantic(undefined, () => ({ description: 'Previous source' })); + await ava.semantic(undefined, () => semanticDescription('Previous source')); await ava.source(source); expect(await ava.semantic()).toEqual({}); const discover = vi.spyOn(ava.engine!, 'schema'); @@ -816,13 +822,13 @@ describe('AVA metadata setters', () => { expect(getDSL).toHaveBeenLastCalledWith('Rows', schema); await ava.schema(undefined, () => schema); await ava.profile(undefined, () => profile); - await ava.semantic(undefined, () => ({ description: 'Failed source' })); + await ava.semantic(undefined, () => semanticDescription('Failed source')); await expect(ava.source({ type: 'parquet', options: { path: 'unsupported.parquet' } })).rejects.toThrow(); expect(ava.engine).toBeNull(); await expect(ava.schema()).rejects.toThrow('No data loaded'); await ava.source(source); expect(await ava.semantic()).toEqual({}); - await ava.semantic(undefined, () => ({ description: 'Disposed source' })); + await ava.semantic(undefined, () => semanticDescription('Disposed source')); } finally { await ava.dispose(); } diff --git a/__tests__/cli-session.test.ts b/__tests__/cli-session.test.ts index 5ef4e6008..53cb60d8d 100644 --- a/__tests__/cli-session.test.ts +++ b/__tests__/cli-session.test.ts @@ -9,7 +9,7 @@ import { buildDataModel } from '../src/util/data-model'; import { startupSchema, requestSchema } from '../src/cli/session/protocol'; import { sessionDirectory } from '../src/cli/session/transport'; -import type { DataSourceConfig, EngineConfig, Schema } from '../src/types'; +import type { DataSourceConfig, EngineConfig, Schema, Semantic } from '../src/types'; vi.mock('child_process', async (importOriginal) => ({ ...(await importOriginal()), @@ -265,7 +265,9 @@ describe('dataset engine and language', () => { ], }; await datasets.createDataset([source], llm, 'javascript'); - const semantic = { description: 'Sales are in USD.', properties: { confirmedBy: 'user' } }; + const semantic = { + models: [{ name: 'sales', description: 'Sales are in USD.', datasets: [{ name: 'orders', source: 'data' }] }], + } satisfies Semantic; expect(await datasets.withDataset((ava) => ava.semantic())).toEqual({}); await datasets.withDataset((ava) => ava.semantic(undefined, () => semantic)); expect(await datasets.describeDataset(schema)).toMatchObject(schema); diff --git a/__tests__/cli.test.ts b/__tests__/cli.test.ts index ac123bb3e..230d451bf 100644 --- a/__tests__/cli.test.ts +++ b/__tests__/cli.test.ts @@ -93,6 +93,12 @@ describe('help and validation', () => { }); describe('metadata input', () => { + const semantic = { + models: [ + { name: 'sales', description: 'Revenue excludes refunds.', datasets: [{ name: 'orders', source: 'data' }] }, + ], + }; + describe.each(['schema', 'profile', 'semantic'])('%s from stdin', (kind) => { const args = [kind, datasetId, '--file', '-']; @@ -102,7 +108,7 @@ describe('metadata input', () => { } it('imports valid metadata', async () => { - const value = kind === 'semantic' ? { description: 'Revenue excludes refunds.' } : { models: [] }; + const value = kind === 'semantic' ? semantic : { models: [] }; mockStdin(JSON.stringify(value)); const output = await execute(args); @@ -138,7 +144,7 @@ describe('metadata input', () => { it.each(['schema', 'profile', 'semantic'])('sets %s from a plain file path', async (kind) => { const directory = await mkdtemp(join(tmpdir(), 'ava-cli-test-')); try { - const value = kind === 'semantic' ? { description: 'Revenue excludes refunds.' } : { models: [] }; + const value = kind === 'semantic' ? semantic : { models: [] }; const file = join(directory, 'metadata.json'); await writeFile(file, JSON.stringify(value)); await execute([kind, datasetId, '--file', file]); diff --git a/__tests__/contracts.test.ts b/__tests__/contracts.test.ts index 1a673b207..fa4f78662 100644 --- a/__tests__/contracts.test.ts +++ b/__tests__/contracts.test.ts @@ -179,7 +179,8 @@ describe('source-to-chart contract flow', () => { } expect(contracts.schemaOutputSchema.parse({ models: [] })).toEqual({ models: [] }); expect(contracts.profileOutputSchema.parse({ models: [] })).toEqual({ models: [] }); - expect(contracts.semanticOutputSchema.parse({ description: 'Sales' })).toEqual({ description: 'Sales' }); + const semantic = { models: [{ name: 'sales', datasets: [{ name: 'orders', source: 'data' }] }] }; + expect(contracts.semanticOutputSchema.parse(semantic)).toEqual(semantic); }); it('loads, queries and renders real SQL results through the public contracts', async () => { diff --git a/__tests__/query/clickhouse-sql.test.ts b/__tests__/query/clickhouse-sql.test.ts index ea1599cea..5a8568a3e 100644 --- a/__tests__/query/clickhouse-sql.test.ts +++ b/__tests__/query/clickhouse-sql.test.ts @@ -57,9 +57,13 @@ describe('ClickHouse SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new ClickHouseSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/duckdb-sql.test.ts b/__tests__/query/duckdb-sql.test.ts index 316b2b06d..d8a939bae 100644 --- a/__tests__/query/duckdb-sql.test.ts +++ b/__tests__/query/duckdb-sql.test.ts @@ -114,9 +114,13 @@ describe('DuckDB SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new DuckDBSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/interpreters.test.ts b/__tests__/query/interpreters.test.ts index 47a8c70ef..c02f12caf 100644 --- a/__tests__/query/interpreters.test.ts +++ b/__tests__/query/interpreters.test.ts @@ -16,10 +16,7 @@ describe.each([ create: () => new JavaScriptDialect({ model: 'test', maxRetries: 0 }), fence: 'js', code: "const result = '```';", - sources: [ - '// 中文😀\nconst result = `value: ${data[0]?.value ?? 0}`;', - 'const result =', - ], + sources: ['// 中文😀\nconst result = `value: ${data[0]?.value ?? 0}`;', 'const result ='], invalid: ['', ' \n\t'], notExecuted: "throw new Error('must not execute');", }, @@ -49,9 +46,13 @@ describe.each([ it('extracts code and preserves rules, context and usage', async () => { const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`${fence}\n${code}\n\`\`\``, finishReason: 'stop', usage } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`${fence}\n${code}\n\`\`\``, + finishReason: 'stop', + usage, + } as never); const result = await dialect.getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: code, usage }); expect(generateText).toHaveBeenCalledWith(expect.objectContaining({ maxRetries: 0 })); @@ -63,7 +64,10 @@ describe.each([ { finishReason: 'length', empty: false, error: 'did not complete' }, { finishReason: 'stop', empty: true, error: 'empty code' }, ])('rejects unusable generation: $error', async ({ finishReason, empty, error }) => { - vi.mocked(generateText).mockResolvedValue({ text: empty ? `\`\`\`${fence}\n\n\`\`\`` : code, finishReason } as never); + vi.mocked(generateText).mockResolvedValue({ + text: empty ? `\`\`\`${fence}\n\n\`\`\`` : code, + finishReason, + } as never); await expect(dialect.getDSL('one', { models: [] })).rejects.toThrow(error); }); @@ -93,7 +97,8 @@ describe.skipIf(process.env.AVA_PYTHON_LOCAL_TEST !== '1')('Python official comp const dialect = new PythonDialect({ model: 'unused' }); it('preserves source without executing code or resolving data bindings', async () => { - const code = "# 中文😀\ndef total(frame):\n return frame['value'].sum()\nresult = total(df)\nraise RuntimeError('must not execute')\n"; + const code = + "# 中文😀\ndef total(frame):\n return frame['value'].sum()\nresult = total(df)\nraise RuntimeError('must not execute')\n"; await expect(dialect.validateDSL(code)).resolves.toBe(code); }); diff --git a/__tests__/query/postgresql.test.ts b/__tests__/query/postgresql.test.ts index ded4095ed..10cfa84db 100644 --- a/__tests__/query/postgresql.test.ts +++ b/__tests__/query/postgresql.test.ts @@ -45,12 +45,9 @@ describe('PostgreSQL validation', () => { await expect(dialect.validateDSL(`;;${sql}; ; -- tail`)).resolves.toBe(sql); }); - it.each(['SELECT (', 'SELECT 1\0; DELETE FROM orders'])( - 'rejects invalid or truncated input: %s', - async (sql) => { - await expect(dialect.validateDSL(sql)).rejects.toThrow(); - } - ); + it.each(['SELECT (', 'SELECT 1\0; DELETE FROM orders'])('rejects invalid or truncated input: %s', async (sql) => { + await expect(dialect.validateDSL(sql)).rejects.toThrow(); + }); it.each([ '', @@ -69,9 +66,13 @@ describe('PostgreSQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new PostgreSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/tsql.test.ts b/__tests__/query/tsql.test.ts index 7cf9fcf7c..644f0cfaf 100644 --- a/__tests__/query/tsql.test.ts +++ b/__tests__/query/tsql.test.ts @@ -61,9 +61,13 @@ describe('T-SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT N'```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`tsql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`tsql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new TSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/util/__snapshots__/data-model.test.ts.snap b/__tests__/util/__snapshots__/data-model.test.ts.snap index c900da43f..cb1122053 100644 --- a/__tests__/util/__snapshots__/data-model.test.ts.snap +++ b/__tests__/util/__snapshots__/data-model.test.ts.snap @@ -1,151 +1,36 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`stringifyDataModel > describes cube members and drill-down paths without nesting their definitions in JSON 1`] = ` +exports[`stringifyDataModel > includes physical structure, profiling observations, and separately scoped semantic definitions 1`] = ` "# Data Model -## Cubes - -### Cube: revenue - -| Attribute | Value | -| --- | --- | -| baseObject | orders | - -Properties: - -| Attribute | Value | -| --- | --- | -| description | Sales reporting | - -#### Measures - -- total (DOUBLE) - -| Attribute | Value | -| --- | --- | -| expression | SUM(amount - refund) | -| description | Net revenue | - -Properties: - -| Attribute | Value | -| --- | --- | -| unit | USD | - -#### Dimensions - -- region (VARCHAR) - -| Attribute | Value | -| --- | --- | -| expression | region | - -#### Time dimensions - -- month (DATE) - -| Attribute | Value | -| --- | --- | -| expression | DATE_TRUNC('month', ordered_at) | - -#### Hierarchies - -- calendar: year → month - -### Cube: counts - -| Attribute | Value | -| --- | --- | -| baseObject | orders | - -#### Measures - -- count (BIGINT) - -| Attribute | Value | -| --- | --- | -| expression | COUNT(*) |" -`; - -exports[`stringifyDataModel > renders model sources, constraints, columns and metadata as Markdown tables 1`] = ` -"# Data Model - -## Properties - -| Attribute | Value | -| --- | --- | -| description | Sales data | - ## Models ### Model: orders | Attribute | Value | | --- | --- | -| tableReference | {"schema":"public","table":"raw_orders"} | -| primaryKey | ["id","customer_id"] | -| uniqueKeys | ["id"] | - -Properties: - -| Attribute | Value | -| --- | --- | -| description | Confirmed orders | +| tableReference | {"catalog":"sales","schema":"public","table":"raw_orders"} | +| primaryKey | id | Metrics: | Attribute | Value | | --- | --- | -| row_count | 0 | +| row_count | 42 | #### Columns -- id (INTEGER) NOT NULL - -| Attribute | Value | -| --- | --- | -| notNull | true | - -- amount (DOUBLE) [calculated: price * quantity] - -| Attribute | Value | -| --- | --- | -| notNull | false | -| isCalculated | true | -| expression | price * quantity | - -Properties: +- amount (DOUBLE) NOT NULL | Attribute | Value | | --- | --- | -| unit | USD | +| logicalType | numeric | Metrics: | Attribute | Value | | --- | --- | -| min | null | -| max | 0 | -| top_values | [] | - -- customer (customers) [relationship: order_customer] - -| Attribute | Value | -| --- | --- | -| relationship | order_customer | -| expression | null | - -### Model: customers - -| Attribute | Value | -| --- | --- | -| baseObject | raw_customers | - -### Model: recent_orders - -| Attribute | Value | -| --- | --- | -| refSql | SELECT * FROM orders
WHERE id > 0 | +| min | 0 | ## Relationships @@ -157,21 +42,29 @@ orders → customers (MANY_TO_ONE) | --- | --- | | models | ["orders","customers"] | | joinType | MANY_TO_ONE | -| condition | orders.customer_id = customers.id | -| custom | false | +| condition | orders.id = customers.id | -Properties: +## Views + +### View: recent | Attribute | Value | | --- | --- | -| description | Buyer | +| statement | SELECT * FROM orders WHERE id > 0 | -## Views +## Semantic Models + +### Semantic Model: sales + +| Attribute | Value | +| --- | --- | +| description | Sales definitions | +| datasets | [{"name":"orders","source":"sales.public.raw_orders","fields":[{"name":"amount","expression":{"sql":"amount"},"datatype":"Decimal"}],"metrics":[{"name":"total","expression":{"sql":"SUM(amount)"}}]}] | +| metrics | [{"name":"gross","expression":{"sql":"AGG(orders.total)"}}] | -### View: all_orders +### Semantic Model: support | Attribute | Value | | --- | --- | -| statement | SELECT * FROM orders | -| custom | {"enabled":true} |" +| datasets | [{"name":"orders","source":"SELECT order_id FROM tickets"}] |" `; diff --git a/__tests__/util/data-model.test.ts b/__tests__/util/data-model.test.ts index b3cf51b60..866a0fddd 100644 --- a/__tests__/util/data-model.test.ts +++ b/__tests__/util/data-model.test.ts @@ -6,390 +6,148 @@ import { semanticOutputSchema, profileOutputSchema } from '../../src/contracts'; import type { DataModel, Profile, Schema, Semantic } from '../../src/types'; -describe('stringifyDataModel', () => { - it('renders model sources, constraints, columns and metadata as Markdown tables', () => { - const input: DataModel = { - properties: { description: 'Sales data' }, - models: [ +const semantic = { + models: [ + { + name: 'sales', + description: 'Sales definitions', + datasets: [ { name: 'orders', - tableReference: { schema: 'public', table: 'raw_orders' }, - primaryKey: ['id', 'customer_id'], - uniqueKeys: ['id'], - metrics: { row_count: 0 }, - properties: { description: 'Confirmed orders' }, - columns: [ - { name: 'id', type: 'INTEGER', notNull: true }, - { - name: 'amount', - type: 'DOUBLE', - notNull: false, - isCalculated: true, - expression: 'price * quantity', - metrics: { min: null, max: 0, top_values: [] }, - properties: { unit: 'USD' }, - }, - { name: 'customer', type: 'customers', relationship: 'order_customer', expression: null }, - ], - }, - { name: 'customers', baseObject: 'raw_customers' }, - { name: 'recent_orders', refSql: 'SELECT * FROM orders\nWHERE id > 0' }, - ], - relationships: [ - { - name: 'order_customer', - models: ['orders', 'customers'], - joinType: 'MANY_TO_ONE', - condition: 'orders.customer_id = customers.id', - properties: { description: 'Buyer' }, - custom: false, + source: 'sales.public.raw_orders', + fields: [{ name: 'amount', expression: { sql: 'amount' }, datatype: 'Decimal' }], + metrics: [{ name: 'total', expression: { sql: 'SUM(amount)' } }], }, ], - views: [{ name: 'all_orders', statement: 'SELECT * FROM orders', custom: { enabled: true } }], - }; - const original = structuredClone(input); - const result = stringifyDataModel(input); - - expect(result).toMatchSnapshot(); - expect(input).toEqual(original); - }); - - it('accepts empty and partial descriptions without inventing metadata', () => { - expect(stringifyDataModel({})).toBe('# Data Model'); - expect(stringifyDataModel({ properties: {}, models: [], relationships: [], views: [], cubes: [] })).toBe( - '# Data Model' - ); - expect(stringifyDataModel({ models: [{ name: 'data', baseObject: 'source' }] })).toBe( - '# Data Model\n\n## Models\n\n### Model: data\n\n| Attribute | Value |\n| --- | --- |\n| baseObject | source |' - ); - }); - - it('escapes Markdown, HTML, pipes and line breaks in headings and table cells', () => { - const result = stringifyDataModel({ - properties: { 'a|b': '