This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 3281a1442e [spark] Query Ossie semantic views with native Metric Views
(#11132)
3281a1442e is described below
commit 3281a1442e4cfd1e24e10f4561202a3e513536ac
Author: Jingsong Lee <[email protected]>
AuthorDate: Fri Nov 13 13:17:19 2026 +0800
[spark] Query Ossie semantic views with native Metric Views (#11132)
---
docs/docs/concepts/rest/semantic-views.md | 89 +++-
docs/docs/spark/installation.mdx | 3 +
paimon-spark/paimon-spark-4.2/pom.xml | 33 ++
.../src/main/resources/META-INF/NOTICE | 7 +
.../apache/paimon/spark/ossie/ossie-schema.json | 396 +++++++++++++++++
.../org/apache/paimon/spark/ossie/OssieModel.scala | 152 +++++++
.../spark/sql/paimon/OssieToSparkMetricView.scala | 253 +++++++++++
.../sql/paimon/PaimonSemanticViewResolver.scala | 146 ++++++
.../apache/paimon/spark/ossie/OssieModelTest.scala | 136 ++++++
.../spark/sql/paimon/OssieSemanticViewTest.scala | 495 +++++++++++++++++++++
.../extensions/PaimonSparkSessionExtensions.scala | 5 +
11 files changed, 1709 insertions(+), 6 deletions(-)
diff --git a/docs/docs/concepts/rest/semantic-views.md
b/docs/docs/concepts/rest/semantic-views.md
index bc3469dd5a..0f5974c390 100644
--- a/docs/docs/concepts/rest/semantic-views.md
+++ b/docs/docs/concepts/rest/semantic-views.md
@@ -27,7 +27,8 @@ This experimental REST Catalog extension manages the object
and its definition.
preserves the original document text. Servers validate the model formats,
syntax versions,
and features they support; consumers provide query execution.
-Registration does not imply Spark/Flink execution support or grant access to
source data.
+Registration alone does not grant access to source data or guarantee engine
support.
+The Spark 4.2 connector supports the [Ossie query
profile](#spark-42-ossie-queries) below.
This implementation supplies Java clients, wire models, and the
[Catalog OpenAPI contract](/rest-catalog-open-api.yaml). REST server providers
must implement
persistence, validation, authorization, and the atomic operations described
below.
@@ -143,9 +144,9 @@ upsert/get/list/paged-list/delete operations; its read and
upsert methods return
deletion cleans up direct labels and permissions without deleting referenced
sources.
- Semantic views count when determining whether a database is empty. Database
cascade deletion
follows existing catalog rules and cleans up semantic metadata and its
direct bindings.
-- Unsupported model semantics must be rejected without side effects or
dropping fields. SQL
- analysis, source validation, dependencies, and execution authorization
belong to the server's
- model format adapter. The client exposes no generic executable-validation
status.
+- Servers validate the model formats and metadata they accept without dropping
fields. Execution
+ adapters additionally validate supported model semantics, expressions, and
source access when
+ querying an object. The management client exposes no generic
executable-validation status.
The HTTP client tests verify wire behavior and error propagation. They do not
prove a provider's
storage atomicity, permission enforcement, namespace isolation, or database
lifecycle behavior.
@@ -164,5 +165,81 @@ Errors use `ErrorResponse`; semantic view errors use
`resourceType=SEMANTIC_VIEW
| 501 | Server does not implement semantic views | `NotImplementedException` |
Client-side invalid input throws `IllegalArgumentException` before HTTP. An
unsupported endpoint
-never falls back to SQL views, labels, or table options. Query compilation,
measure rewriting,
-materialization, rename, and per-measure or per-field REST resources are
outside this version.
+never falls back to SQL views, labels, or table options. Materialization,
rename, and per-measure
+or per-field REST resources are outside this version.
+
+## Spark 4.2 Ossie queries
+
+The `paimon-spark-4.2_2.13` connector can query an `ossie-yaml` definition
through the configured
+Paimon REST Catalog. Enable `PaimonSparkSessionExtensions` as described in the
+[Spark installation guide](../../spark/installation.mdx). The REST server must
implement semantic
+view management; the connector does not provide production REST persistence or
validation.
+
+Register a definition whose content is a flat Ossie document, for example:
+
+```yaml
+version: 0.3.0.dev0
+name: order_metrics
+datasets:
+ - name: orders
+ source: orders
+ fields:
+ - name: region
+ expression:
+ sql: region_code
+ - name: net_amount
+ expression:
+ sql: amount - discount
+ metrics:
+ - name: revenue
+ expression:
+ sql: SUM(net_amount)
+```
+
+For a definition registered as `sales.order_metrics` in Spark catalog
`paimon`, query it with:
+
+```sql
+SELECT region, MEASURE(revenue) AS revenue
+FROM paimon.sales.order_metrics
+WHERE region = 'CN'
+GROUP BY region;
+```
+
+The connector reads the definition at analysis time, compiles it into a Spark
Metric View, and
+uses Spark's native `MEASURE` rewrite and execution. It does not persist a
converted copy or cache
+definitions across queries. Reanalyzing a query sees the current committed
definition; an already
+analyzed DataFrame keeps its existing plan.
+
+This experimental execution profile supports:
+
+- Exactly one dataset backed by a physical Paimon table in the same Spark
catalog. A one-part
+ source resolves in the semantic view's database; two parts specify database
and table;
+ three parts specify catalog, database and table. SQL queries as sources are
not supported.
+- Declared scalar fields and dataset-scoped metrics. A dataset metric's
unqualified reference
+ resolves to a declared field; `source.column` reaches the original source
column. A field
+ named `source` prevents that source-column qualification, following Ossie's
scoping rule.
+- Model-scoped metrics referencing that dataset's qualified fields. Field and
metric names must
+ be unique, ignoring case, in the resulting Spark relation.
+- Portable `expression.sql` or an `OSSIE_SQL_2026` dialect expression;
arithmetic, comparisons,
+ boolean logic, `CASE`, `IN`, numeric/string/boolean/date casts, `SUM`,
`COUNT` (including
+ distinct), `AVG`, `MIN`, `MAX`, `ABS`, `ROUND`, `FLOOR`, `CEIL`, `CEILING`,
and `COALESCE`.
+
+Other expressions, relationships, multiple datasets, external joins, streaming
reads and writes
+are rejected. SQL Semantic View DDL and SQL discovery are not added; use the
management API to
+register and list definitions. Ordinary tables and SQL views retain their
existing lookup paths.
+Source table authorization is required independently of permission to read the
semantic definition.
+When using a CTE, evaluate measures inside its definition (for example,
+`WITH m AS (SELECT MEASURE(revenue) AS revenue FROM
paimon.sales.order_metrics) SELECT revenue FROM m`).
+Forwarding raw measure columns through a CTE or temporary view is not
supported by Spark 4.2's
+Metric View resolver; evaluate measures inside the defining query block before
reusing its results.
+
+The bundled schema is pinned to Ossie commit
+[`2692b1cc4708fdcf6a91e597ca928a9bc9d0da60`](https://github.com/apache/ossie/tree/2692b1cc4708fdcf6a91e597ca928a9bc9d0da60).
+The `0.3.0.dev0` version string is a development version and does not imply
compatibility with
+future changes under that same string. `ai_context` and
`nonportable_extensions` remain in the
+original document and do not alter query execution.
+Extension data must contain JSON values with string keys. Quote date and
timestamp strings;
+unquoted dates, timestamps, non-finite numbers, and recursive YAML aliases are
rejected.
+Alias expansion is also bounded before JSON validation to prevent small
documents from expanding
+into unbounded in-memory models. Portable SQL string literals follow ANSI
quoting, independently
+of Spark's `spark.sql.parser.escapedStringLiterals` setting.
diff --git a/docs/docs/spark/installation.mdx b/docs/docs/spark/installation.mdx
index 737e2e1515..e223cebe28 100644
--- a/docs/docs/spark/installation.mdx
+++ b/docs/docs/spark/installation.mdx
@@ -96,6 +96,9 @@ the same names, but Spark 4.2 changes internal binary
interfaces such as `Catalo
For Spark 3.5, you can find the bundled jar in
`./paimon-spark/paimon-spark-3.5/target/paimon-spark-3.5_2.12-@@VERSION@@.jar`.
+The Spark 4.2 connector can also query [Ossie Semantic
Views](../concepts/rest/semantic-views.md#spark-42-ossie-queries)
+registered in a Paimon REST Catalog.
+
## Add the Connector to Spark
Pass `--jars /path/to/paimon-connector.jar` when starting `spark-sql` or
`spark-shell`, or put the
diff --git a/paimon-spark/paimon-spark-4.2/pom.xml
b/paimon-spark/paimon-spark-4.2/pom.xml
index 34298028c3..61ce11252b 100644
--- a/paimon-spark/paimon-spark-4.2/pom.xml
+++ b/paimon-spark/paimon-spark-4.2/pom.xml
@@ -38,6 +38,27 @@ under the License.
</properties>
<dependencies>
+ <dependency>
+ <groupId>com.networknt</groupId>
+ <artifactId>json-schema-validator</artifactId>
+ <version>2.0.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-yaml</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.paimon</groupId>
<artifactId>paimon-format</artifactId>
@@ -127,8 +148,20 @@ under the License.
<artifactSet>
<includes combine.children="append">
<include>org.apache.paimon:paimon-spark4-common_${scala.binary.version}</include>
+
<include>com.networknt:json-schema-validator</include>
+ <include>com.ethlo.time:itu</include>
</includes>
</artifactSet>
+ <relocations>
+ <relocation>
+ <pattern>com.networknt</pattern>
+
<shadedPattern>org.apache.paimon.spark.shade.networknt</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.ethlo.time</pattern>
+
<shadedPattern>org.apache.paimon.spark.shade.time</shadedPattern>
+ </relocation>
+ </relocations>
</configuration>
</execution>
</executions>
diff --git a/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
b/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
index 6b79772894..2a73a7bc6b 100644
--- a/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
+++ b/paimon-spark/paimon-spark-4.2/src/main/resources/META-INF/NOTICE
@@ -3,3 +3,10 @@ Copyright 2023-2026 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
+
+This project bundles the following dependencies under the Apache Software
License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt)
+- com.networknt:json-schema-validator:2.0.0
+- com.ethlo.time:itu:1.14.0
+
+The bundled Ossie JSON Schema is from Apache Ossie (incubating), commit
+2692b1cc4708fdcf6a91e597ca928a9bc9d0da60, under the Apache Software License
2.0.
diff --git
a/paimon-spark/paimon-spark-4.2/src/main/resources/org/apache/paimon/spark/ossie/ossie-schema.json
b/paimon-spark/paimon-spark-4.2/src/main/resources/org/apache/paimon/spark/ossie/ossie-schema.json
new file mode 100644
index 0000000000..ac15741121
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/main/resources/org/apache/paimon/spark/ossie/ossie-schema.json
@@ -0,0 +1,396 @@
+{
+ "$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 vend [...]
+ },
+ "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`, `Ti [...]
+ }
+ },
+ "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,
+ "description": "Dataset fields that uniquely identify rows"
+ },
+ "unique_keys": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "minItems": 1
+ },
+ "minItems": 1,
+ "description": "Array of unique key definitions, each a list of
dataset fields"
+ },
+ "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: aggregations evaluated at
this dataset's row level, for measures that semantically belong to the dataset.
The expression references this dataset's declared fields by single-part
(unqualified) name, and columns of the dataset's source as source.column. It
must resolve entirely within this dataset; an expression that must reference
another dataset belongs in the model-scoped metrics instead. Within the
dataset, field names and metric names [...]
+ },
+ "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. 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/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/paimon/spark/ossie/OssieModel.scala
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/paimon/spark/ossie/OssieModel.scala
new file mode 100644
index 0000000000..f133099ddf
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/paimon/spark/ossie/OssieModel.scala
@@ -0,0 +1,152 @@
+/*
+ * 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.
+ */
+
+package org.apache.paimon.spark.ossie
+
+import org.apache.paimon.view.SemanticViewDefinition
+
+import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
+import com.networknt.schema.{SchemaRegistry, SpecificationVersion}
+import org.yaml.snakeyaml.{LoaderOptions, Yaml}
+import org.yaml.snakeyaml.constructor.SafeConstructor
+
+import java.nio.charset.StandardCharsets.UTF_8
+import java.util.{Collections, IdentityHashMap, Locale}
+
+import scala.collection.JavaConverters._
+
+case class OssieField(name: String, sql: String)
+case class OssieMetric(name: String, sql: String, modelScoped: Boolean)
+case class OssieModel(
+ dataset: String,
+ source: String,
+ fields: Seq[OssieField],
+ metrics: Seq[OssieMetric])
+
+/** Read-only execution profile of Ossie 0.3.0.dev0; the original document is
never rewritten. */
+object OssieModel {
+ // The development version is mutable. Keep this schema and the execution
profile together.
+ val schemaCommit: String = "2692b1cc4708fdcf6a91e597ca928a9bc9d0da60"
+
+ private val mapper = new ObjectMapper()
+
+ private lazy val schema = {
+ val stream = getClass.getResourceAsStream("ossie-schema.json")
+ require(stream != null, "Missing bundled Ossie schema")
+ try {
+
SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12).getSchema(stream)
+ } finally {
+ stream.close()
+ }
+ }
+
+ def parse(definition: SemanticViewDefinition): OssieModel = {
+ require(definition.getFormat == "ossie-yaml", "Semantic query requires
format ossie-yaml")
+ val options = new LoaderOptions()
+ options.setAllowDuplicateKeys(false)
+ val document = new Yaml(new
SafeConstructor(options)).load[AnyRef](definition.getContent)
+ require(document != null, "Empty Ossie document")
+ checkJson(document)
+ val root = mapper.valueToTree[JsonNode](document)
+ val errors = schema.validate(root).asScala
+ require(errors.isEmpty, "Invalid Ossie 0.3.0.dev0 model: " +
errors.take(5).mkString("; "))
+ val datasets = elements(root, "datasets")
+ require(datasets.size == 1, "Ossie queries currently require exactly one
dataset")
+ require(elements(root, "relationships").isEmpty, "Ossie relationships are
not supported yet")
+ val dataset = datasets.head
+ val fields = elements(dataset, "fields").map(f => OssieField(text(f,
"name"), expression(f)))
+ require(fields.nonEmpty, "Ossie queries require declared dataset fields")
+ val metrics = elements(dataset, "metrics").map(
+ m => OssieMetric(text(m, "name"), expression(m), modelScoped = false)) ++
+ elements(root, "metrics").map(
+ m => OssieMetric(text(m, "name"), expression(m), modelScoped = true))
+ require(metrics.nonEmpty, "Ossie queries require at least one metric")
+ val names = (fields.map(_.name) ++ metrics.map(_.name)).map(normalize)
+ require(names.distinct.size == names.size, "Ossie field and metric names
must be unique")
+ val fieldNames = fields.map(f => normalize(f.name)).toSet
+ val keys = elements(dataset, "primary_key") ++
+ elements(dataset, "unique_keys").flatMap(_.elements().asScala)
+ require(
+ keys.forall(k => fieldNames.contains(normalize(k.asText()))),
+ "Ossie keys must reference declared dataset fields")
+ OssieModel(text(dataset, "name"), text(dataset, "source"), fields, metrics)
+ }
+
+ def normalize(name: String): String = name.toLowerCase(Locale.ROOT)
+
+ private def expression(node: JsonNode): String = {
+ val expr = node.get("expression")
+ if (expr.has("sql")) {
+ text(expr, "sql")
+ } else {
+ val portable = elements(expr, "dialects").filter(d => text(d, "dialect")
== "OSSIE_SQL_2026")
+ require(portable.size == 1, "Ossie query requires an OSSIE_SQL_2026
expression")
+ text(portable.head, "expression")
+ }
+ }
+
+ private def text(node: JsonNode, name: String): String =
node.get(name).asText()
+
+ private def elements(node: JsonNode, name: String): Seq[JsonNode] =
+
Option(node.get(name)).map(_.elements().asScala.toVector).getOrElse(Vector.empty)
+
+ // Preserve YAML scalar types until validation: Jackson's YAML reader turns
timestamps into
+ // strings and map keys into strings, hiding values that Ossie forbids in
extension data.
+ private def checkJson(root: AnyRef): Unit = {
+ val ancestors = Collections.newSetFromMap(new IdentityHashMap[AnyRef,
java.lang.Boolean]())
+ // Charge every occurrence, including aliases: a small YAML graph can
expand exponentially.
+ // The budget bounds JSON node count plus UTF-8 scalar/key content before
valueToTree allocates.
+ var remaining = SemanticViewDefinition.MAX_CONTENT_BYTES
+ def charge(size: Int): Unit = {
+ require(size <= remaining, "Ossie expanded YAML exceeds the supported
size")
+ remaining -= size
+ }
+ def text(value: String): Unit = charge(value.getBytes(UTF_8).length)
+ def visit(value: AnyRef): Unit = {
+ charge(1)
+ value match {
+ case null | _: java.lang.Boolean =>
+ case s: String => text(s)
+ case n: java.lang.Double =>
+ require(java.lang.Double.isFinite(n), "Ossie values must be finite
JSON numbers")
+ text(n.toString)
+ case n: java.lang.Float =>
+ require(java.lang.Float.isFinite(n), "Ossie values must be finite
JSON numbers")
+ text(n.toString)
+ case n: java.lang.Number => text(n.toString)
+ case map: java.util.Map[_, _] =>
+ require(ancestors.add(map), "Ossie YAML cannot contain recursive
aliases")
+ try {
+ map.asScala.foreach {
+ case (key, item) =>
+ require(key.isInstanceOf[String], "Ossie JSON object keys must
be strings")
+ text(key.asInstanceOf[String])
+ visit(item.asInstanceOf[AnyRef])
+ }
+ } finally { ancestors.remove(map) }
+ case list: java.util.List[_] =>
+ require(ancestors.add(list), "Ossie YAML cannot contain recursive
aliases")
+ try { list.asScala.foreach(item => visit(item.asInstanceOf[AnyRef]))
}
+ finally { ancestors.remove(list) }
+ case _ =>
+ throw new IllegalArgumentException("Ossie YAML values must be
representable as JSON")
+ }
+ }
+ visit(root)
+ }
+}
diff --git
a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/OssieToSparkMetricView.scala
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/OssieToSparkMetricView.scala
new file mode 100644
index 0000000000..6e5e861a3b
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/OssieToSparkMetricView.scala
@@ -0,0 +1,253 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.paimon
+
+import org.apache.paimon.spark.ossie.OssieModel
+import org.apache.paimon.utils.StringUtils
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.analysis.{UnresolvedAttribute,
UnresolvedFunction, UnresolvedStar}
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.parser.CatalystSqlParser
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+
+import scala.collection.mutable
+
+/** Compile field references before Spark sees the model, preserving
source/field shadowing. */
+private[paimon] object OssieToSparkMetricView {
+ private val aggregates = Set("sum", "count", "avg", "min", "max")
+ private val functions = aggregates ++ Set("abs", "round", "floor", "ceil",
"ceiling", "coalesce")
+
+ def convert(
+ spark: SparkSession,
+ model: OssieModel,
+ source: Seq[String],
+ sourceColumns: Seq[String]): String = {
+ val sourceNames = sourceColumns.map(n => OssieModel.normalize(n) ->
n).toMap
+ require(sourceNames.size == sourceColumns.size, "Ambiguous
case-insensitive source columns")
+ val publicNames =
+ (model.fields.map(_.name) ++
model.metrics.map(_.name)).map(OssieModel.normalize)
+ val prefix = Iterator
+ .from(0)
+ .map(i => s"__ossie_${i}_")
+ .find(p => !publicNames.exists(_.startsWith(p)))
+ .get
+ val fieldNames = model.fields.zipWithIndex.map {
+ case (f, i) => OssieModel.normalize(f.name) -> s"${prefix}f$i"
+ }.toMap
+ val rawColumns = mutable.LinkedHashMap[String, String]()
+
+ def sourceColumn(name: String): String = sourceNames.getOrElse(
+ OssieModel.normalize(name),
+ throw new IllegalArgumentException(s"Unknown Ossie source column:
$name"))
+
+ def field(name: String): Expression = UnresolvedAttribute(
+ Seq(
+ fieldNames.getOrElse(
+ OssieModel.normalize(name),
+ throw new IllegalArgumentException(s"Unknown Ossie dataset field:
$name"))))
+
+ val projections = model.fields.zipWithIndex.map {
+ case (f, i) =>
+ val expr = parse(spark, f.sql, metric = false).transformUp {
+ case a: UnresolvedAttribute =>
+ require(a.nameParts.size == 1, "Ossie field expressions must
reference source columns")
+ UnresolvedAttribute(Seq(sourceColumn(a.nameParts.head)))
+ }
+ s"${render(expr)} AS ${quote(s"${prefix}f$i")}"
+ }
+
+ val measures = model.metrics.map {
+ m =>
+ val expr = parse(spark, m.sql, metric = true).transformUp {
+ case a: UnresolvedAttribute =>
+ a.nameParts match {
+ case Seq(name) if !m.modelScoped => field(name)
+ case Seq(dataset, name)
+ if m.modelScoped &&
+ OssieModel.normalize(dataset) ==
OssieModel.normalize(model.dataset) =>
+ field(name)
+ case Seq(qualifier, name)
+ if !m.modelScoped &&
+ qualifier.equalsIgnoreCase("source") &&
!fieldNames.contains("source") =>
+ val actual = sourceColumn(name)
+ val alias = rawColumns.getOrElseUpdate(actual,
s"${prefix}s${rawColumns.size}")
+ UnresolvedAttribute(Seq(alias))
+ case _ =>
+ throw new IllegalArgumentException(s"Invalid Ossie metric
reference: ${a.sql}")
+ }
+ }
+ m.name -> render(expr)
+ }
+ val rawProjections = rawColumns.toSeq.map {
+ case (name, alias) => s"${quote(name)} AS ${quote(alias)}"
+ }
+ val sql = "SELECT " + (projections ++ rawProjections).mkString(", ") +
+ " FROM " + source.map(quote).mkString(".")
+ val mapper = new ObjectMapper()
+ val root = mapper.createObjectNode()
+ root.put("version", "0.1")
+ root.put("source", sql)
+ val dimensions = root.putArray("dimensions")
+ model.fields.zipWithIndex.foreach {
+ case (f, i) => dimensions.addObject().put("name", f.name).put("expr",
quote(s"${prefix}f$i"))
+ }
+ val metricNodes = root.putArray("measures")
+ measures.foreach {
+ case (name, expr) => metricNodes.addObject().put("name",
name).put("expr", expr)
+ }
+ // JSON is a YAML subset, and avoids another serialization path for SQL
strings.
+ mapper.writeValueAsString(root)
+ }
+
+ private def parse(spark: SparkSession, sql: String, metric: Boolean):
Expression = {
+ val conf = new SQLConf()
+ spark.sessionState.conf.getAllConfs.foreach { case (k, v) =>
conf.setConfString(k, v) }
+ conf.setConf(SQLConf.ANSI_ENABLED, true)
+ conf.setConf(SQLConf.DOUBLE_QUOTED_IDENTIFIERS, true)
+ conf.setConf(SQLConf.ESCAPED_STRING_LITERALS, false)
+ val expr =
+
SQLConf.withExistingConf(conf)(CatalystSqlParser.parseExpression(normalizeStrings(sql)))
+ var aggregate = false
+ expr.foreach {
+ case f: UnresolvedFunction =>
+ require(
+ f.ignoreNulls.isEmpty && f.orderingWithinGroup.isEmpty,
+ "Ossie null treatment and ordered-set aggregates are not supported")
+ require(
+ f.nameParts.size == 1 &&
functions.contains(OssieModel.normalize(f.nameParts.head)),
+ s"Unsupported OSSIE_SQL_2026 function: ${f.nameParts.mkString(".")}"
+ )
+ val name = OssieModel.normalize(f.nameParts.head)
+ if (aggregates.contains(name)) {
+ require(metric, "Ossie field expressions cannot contain aggregates")
+ aggregate = true
+ }
+ require(
+ !f.arguments.exists(_.isInstanceOf[UnresolvedStar]) || name ==
"count",
+ "Only COUNT(*) supports a star in Ossie expressions")
+ case _: Literal | _: UnresolvedAttribute | _: UnresolvedStar =>
+ case _: Add | _: Subtract | _: Multiply | _: Divide | _: Remainder | _:
UnaryMinus |
+ _: UnaryPositive | _: CaseWhen | _: EqualTo | _: LessThan | _:
LessThanOrEqual |
+ _: GreaterThan | _: GreaterThanOrEqual | _: And | _: Or | _: Not |
_: IsNull |
+ _: IsNotNull | _: In =>
+ case c: Cast =>
+ require(
+ c.dataType.isInstanceOf[NumericType] || c.dataType == StringType ||
+ c.dataType == BooleanType || c.dataType == DateType,
+ s"Unsupported Ossie cast type: ${c.dataType}"
+ )
+ case other =>
+ throw new IllegalArgumentException(s"Unsupported OSSIE_SQL_2026
expression: ${other.sql}")
+ }
+ require(!metric || aggregate, "Ossie metrics must contain a supported
aggregate")
+ expr
+ }
+
+ // Ossie strings use ANSI doubled quotes and literal backslashes. Normalize
only string tokens
+ // into Spark's escape syntax, leaving typed literals, identifiers and
comment boundaries intact.
+ private def normalizeStrings(sql: String): String = {
+ val result = new StringBuilder
+ var pos = 0
+ def quoted(delimiter: Char): String = {
+ val value = new StringBuilder
+ var closed = false
+ pos += 1
+ while (pos < sql.length && !closed) {
+ val c = sql.charAt(pos)
+ pos += 1
+ if (c == delimiter) {
+ if (pos < sql.length && sql.charAt(pos) == delimiter) {
+ value.append(c)
+ pos += 1
+ } else { closed = true }
+ } else { value.append(c) }
+ }
+ require(closed, "Unterminated quoted Ossie expression")
+ value.toString
+ }
+ while (pos < sql.length) {
+ val c = sql.charAt(pos)
+ if (sql.startsWith("--", pos)) {
+ while (pos < sql.length && sql.charAt(pos) != '\n' && sql.charAt(pos)
!= '\r') {
+ pos += 1
+ }
+ result.append(' ')
+ } else if (sql.startsWith("/*", pos)) {
+ var depth = 1
+ pos += 2
+ while (pos < sql.length && depth > 0) {
+ if (sql.startsWith("/*", pos)) { depth += 1; pos += 2 }
+ else if (sql.startsWith("*/", pos)) { depth -= 1; pos += 2 }
+ else { pos += 1 }
+ }
+ require(depth == 0, "Unterminated Ossie SQL comment")
+ result.append(' ')
+ } else if (c == '"') {
+ result.append(quote(quoted(c)))
+ } else if (c == '`') {
+ val start = pos
+ quoted(c)
+ result.append(sql.substring(start, pos))
+ } else if (c == '\'') {
+ val rawPrefix = pos > 0 && (sql.charAt(pos - 1) == 'r' ||
sql.charAt(pos - 1) == 'R') &&
+ (pos == 1 || !Character.isJavaIdentifierPart(sql.charAt(pos - 2)))
+ require(!rawPrefix, "Ossie requires ANSI string literals")
+ val value = quoted(c)
+ result.append('\'')
+ value.foreach {
+ case '\\' => result.append("\\\\")
+ case '\'' => result.append("\\'")
+ case other => result.append(other)
+ }
+ result.append('\'')
+ } else {
+ result.append(c)
+ pos += 1
+ }
+ }
+ result.toString
+ }
+
+ private def quote(name: String): String = "`" + name.replace("`", "``") + "`"
+
+ // UnresolvedFunction inherits Expression.sql, which drops DISTINCT and
FILTER. Render those
+ // explicitly before asking the surrounding scalar expressions to render
their own syntax.
+ private def render(expr: Expression): String = expr.transformUp {
+ case l: Literal if l.value != null && l.dataType.isInstanceOf[StringType]
=>
+ val hex =
StringUtils.byteToHexString(l.value.asInstanceOf[UTF8String].getBytes)
+ // Native Metric View parsing uses session settings; binary literals
avoid a second round
+ // of string escaping regardless of escapedStringLiterals.
+ RenderedSQL(s"CAST(X'$hex' AS STRING)")
+ case f: UnresolvedFunction =>
+ val distinct = if (f.isDistinct) "DISTINCT " else ""
+ val filter = f.filter.map(p => s" FILTER (WHERE ${p.sql})").getOrElse("")
+ RenderedSQL(
+
s"${f.nameParts.map(quote).mkString(".")}($distinct${f.arguments.map(_.sql).mkString(",
")})$filter")
+ }.sql
+
+ private case class RenderedSQL(text: String) extends LeafExpression with
Unevaluable {
+ override def dataType: org.apache.spark.sql.types.DataType = NullType
+ override def nullable: Boolean = true
+ override def sql: String = text
+ }
+}
diff --git
a/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/PaimonSemanticViewResolver.scala
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/PaimonSemanticViewResolver.scala
new file mode 100644
index 0000000000..d3a0ca25ec
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/main/scala/org/apache/spark/sql/paimon/PaimonSemanticViewResolver.scala
@@ -0,0 +1,146 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.paimon
+
+import org.apache.paimon.catalog.{DelegateCatalog, Identifier =>
PaimonIdentifier}
+import org.apache.paimon.rest.RESTCatalog
+import org.apache.paimon.rest.exceptions.NoSuchResourceException
+import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.ossie.OssieModel
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.view.SemanticViewDefinition
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.analysis.UnresolvedRelation
+import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat,
CatalogTable, CatalogTableType}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef,
CTERelationRef, Join, LateralJoin, LogicalPlan, SubqueryAlias}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.connector.catalog.PaimonLookupCatalog
+import org.apache.spark.sql.execution.command.MetricViewHelper
+import org.apache.spark.sql.metricview.util.MetricViewPlanner
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+/** Resolve REST semantic definitions through Spark's Metric View engine
without persisting a copy. */
+class PaimonSemanticViewResolver(spark: SparkSession)
+ extends Rule[LogicalPlan]
+ with PaimonLookupCatalog {
+
+ protected lazy val catalogManager = spark.sessionState.catalogManager
+
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ val definitions = mutable.Map[(RESTCatalog, PaimonIdentifier),
Option[SemanticViewDefinition]]()
+ plan.resolveOperatorsDown {
+ case u @ UnresolvedRelation(
+ parts @ CatalogAndIdentifier(catalog: SparkCatalog, ident),
+ _,
+ _) =>
+ DelegateCatalog.rootCatalog(catalog.paimonCatalog()) match {
+ // An ordinary view expanded by the preceding rule may introduce
unresolved source
+ // tables after Spark's relation resolution has run. Leave those for
the next iteration.
+ case rest: RESTCatalog if !catalog.tableExists(ident) =>
+ val id = PaimonIdentifier.create(ident.namespace().head,
ident.name())
+ val definition = definitions.getOrElseUpdate(
+ (rest, id),
+ try {
+ Some(
+ rest
+ .semanticViewManagement()
+ .getSemanticView(id)
+ .getDefinition)
+ } catch {
+ case _: NoSuchResourceException => None
+ })
+ definition
+ .map {
+ definition =>
+ require(!u.isStreaming, "Ossie Semantic Views support batch
queries only")
+ require(
+
u.options.get(UnresolvedRelation.REQUIRED_WRITE_PRIVILEGES) == null,
+ "Ossie Semantic Views are read-only")
+ require(
+ !isJoined(plan, u),
+ "Joins against Ossie Semantic Views are not supported yet")
+ val model = OssieModel.parse(definition)
+ val source =
+
spark.sessionState.sqlParser.parseMultipartIdentifier(model.source) match {
+ case Seq(table) => Seq(catalog.name(),
ident.namespace().head, table)
+ case Seq(db, table) => Seq(catalog.name(), db, table)
+ case Seq(cat, db, table) if cat == catalog.name() =>
Seq(cat, db, table)
+ case _ =>
+ throw new IllegalArgumentException(
+ "Ossie source must be a table in the same Paimon
catalog")
+ }
+ val table =
+
catalog.paimonCatalog().getTable(PaimonIdentifier.create(source(1), source(2)))
+ require(
+ table.isInstanceOf[FileStoreTable],
+ "Ossie source must be a physical Paimon table")
+ val yaml = OssieToSparkMetricView.convert(
+ spark,
+ model,
+ source,
+ table.rowType().getFieldNames.asScala.toSeq)
+ val (analyzed, _) =
MetricViewHelper.analyzeMetricViewText(spark, parts, yaml)
+ val metadata = CatalogTable(
+ identifier = TableIdentifier(
+ ident.name(),
+ Some(ident.namespace().head),
+ Some(catalog.name())),
+ tableType = CatalogTableType.VIEW,
+ storage = CatalogStorageFormat.empty,
+ schema = analyzed.schema,
+ viewText = Some(yaml)
+ )
+ SubqueryAlias(
+ parts,
+ MetricViewPlanner
+ .planRead(metadata, yaml, spark.sessionState.sqlParser,
analyzed.schema))
+ }
+ .getOrElse(u)
+ case _ => u
+ }
+ }
+ }
+
+ private def isJoined(plan: LogicalPlan, relation: UnresolvedRelation):
Boolean = {
+ val ctes = plan.collectWithSubqueries { case cte: CTERelationDef => cte }
+ val semanticCtes = mutable.Set.empty[Long]
+ def dependsOnSemantic(node: LogicalPlan): Boolean =
+ node.collectFirstWithSubqueries {
+ case n if n eq relation => true
+ case ref: CTERelationRef if semanticCtes.contains(ref.cteId) => true
+ }.isDefined
+
+ // CTE definitions are siblings of their consumers, and can reference
other CTEs. Resolve
+ // those dependencies before inspecting joins, including joins inside
scalar subqueries.
+ var changed = true
+ while (changed) {
+ val previousSize = semanticCtes.size
+ ctes.foreach(cte => if (dependsOnSemantic(cte.child)) { semanticCtes +=
cte.id })
+ changed = semanticCtes.size != previousSize
+ }
+ plan.collectFirstWithSubqueries {
+ case join: Join if dependsOnSemantic(join) => true
+ case join: LateralJoin if dependsOnSemantic(join) => true
+ }.isDefined
+ }
+}
diff --git
a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/ossie/OssieModelTest.scala
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/ossie/OssieModelTest.scala
new file mode 100644
index 0000000000..da267139fe
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/ossie/OssieModelTest.scala
@@ -0,0 +1,136 @@
+/*
+ * 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.
+ */
+
+package org.apache.paimon.spark.ossie
+
+import org.apache.paimon.view.SemanticViewDefinition
+
+import org.scalatest.funsuite.AnyFunSuite
+
+class OssieModelTest extends AnyFunSuite {
+ private val model =
+ """version: 0.3.0.dev0
+ |name: revenue
+ |datasets:
+ | - name: orders
+ | source: orders
+ | fields:
+ | - name: amount
+ | expression: {sql: price}
+ | metrics:
+ | - name: revenue
+ | expression: {sql: SUM(amount)}
+ |""".stripMargin
+
+ private def parse(text: String): OssieModel =
+ OssieModel.parse(new SemanticViewDefinition("ossie-yaml", text))
+
+ test("parse the flat document and ignore preserved nonportable metadata") {
+ val text = model +
+ "nonportable_extensions:\n - vendor_name: example\n data: {nested:
[1, true, null]}\n"
+ val result = parse(text)
+ assert(result.dataset == "orders")
+ assert(result.fields == Seq(OssieField("amount", "price")))
+ assert(result.metrics == Seq(OssieMetric("revenue", "SUM(amount)",
modelScoped = false)))
+ val portable = parse(
+ model.replace(
+ "{sql: SUM(amount)}",
+ "{dialects: [{dialect: OSSIE_SQL_2026, expression: SUM(amount)}]}"))
+ assert(portable == result)
+ }
+
+ test("validate the pinned schema and reject old document shapes and unknown
core fields") {
+ Seq(
+ model.replace("version: 0.3.0.dev0", "version: 0.2.0.dev0"),
+ model + "semantic_model: []\n",
+ model + "custom_extensions: []\n",
+ model.replace("expression: {sql: price}", "expression: {sql: 42}"),
+ model.replace("source: orders", "source: orders\n primary_key:
[missing]"),
+ model.replace("name: revenue\n expression", "name: AMOUNT\n
expression")
+ ).foreach(text => intercept[IllegalArgumentException](parse(text)))
+ }
+
+ test("reject multiple datasets and relationships instead of flattening
joins") {
+ // Add the second dataset before the first dataset's fields, retaining a
valid document.
+ val second =
+ model.replace("datasets:\n", "datasets:\n - name: customers\n
source: customers\n")
+
assert(intercept[IllegalArgumentException](parse(second)).getMessage.contains("exactly
one"))
+ val relationship = model + "relationships:\n - name: self\n from:
orders\n" +
+ " to: orders\n from_columns: [amount]\n to_columns: [amount]\n"
+ assert(
+
intercept[IllegalArgumentException](parse(relationship)).getMessage.contains("relationships"))
+ }
+
+ test("reject duplicate YAML keys, trailing documents, and nonfinite
extension values") {
+ Seq(
+ model + "name: duplicate\n",
+ model + "---\n" + model,
+ model + "nonportable_extensions:\n - vendor_name: test\n data:
{value: .inf}\n"
+ ).foreach(text => intercept[Exception](parse(text)))
+ }
+
+ test("reject dialect-only expressions without a portable form") {
+ val text = model.replace(
+ "{sql: SUM(amount)}",
+ "{dialects: [{dialect: UNKNOWN, expression: SUM(amount)}]}")
+
assert(intercept[IllegalArgumentException](parse(text)).getMessage.contains("OSSIE_SQL_2026"))
+ assert(
+ intercept[IllegalArgumentException](
+ OssieModel.parse(new SemanticViewDefinition("databricks-yaml",
model))).getMessage
+ .contains("ossie-yaml"))
+ }
+
+ test("extension data must be JSON values with string keys") {
+ Seq(
+ "2026-11-13",
+ "2026-11-13T01:02:03Z",
+ ".nan",
+ "!!binary SGVsbG8=",
+ "!!set {a: null}",
+ "&cycle [*cycle]")
+ .foreach {
+ value =>
+ val text =
+ model + s"nonportable_extensions:\n - vendor_name: test\n
data: {value: $value}\n"
+ intercept[Exception](parse(text))
+ }
+ intercept[Exception](
+ parse(model +
+ "nonportable_extensions:\n - vendor_name: test\n data: {123:
value}\n"))
+ assert(parse(model +
+ "nonportable_extensions:\n - vendor_name: test\n data: {date:
'2026-11-13', nested: [null, true, 1]}\n").dataset == "orders")
+ }
+
+ test("bound expanded alias graphs and repeated scalar aliases") {
+ val graph = " p0: &p0 [0]\n" + (1 to 20).map {
+ i => s" p$i: &p$i [*p${i - 1}, *p${i - 1}]\n"
+ }.mkString
+ val scalar = " text: &text '" + ("x" * 4096) + "'\n copies: [" +
+ Seq.fill(300)("*text").mkString(", ") + "]\n"
+ Seq(graph, scalar).foreach {
+ data =>
+ val text = model + "nonportable_extensions:\n - vendor_name: test\n
data:\n" + data
+ assert(text.length < SemanticViewDefinition.MAX_CONTENT_BYTES)
+ val error = intercept[IllegalArgumentException](parse(text))
+ assert(error.getMessage.contains("expanded YAML"))
+ }
+ val ordinaryAlias = model +
+ "nonportable_extensions:\n - vendor_name: test\n data: {original:
&value [1, null], copy: *value}\n"
+ assert(parse(ordinaryAlias).dataset == "orders")
+ }
+}
diff --git
a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/spark/sql/paimon/OssieSemanticViewTest.scala
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/spark/sql/paimon/OssieSemanticViewTest.scala
new file mode 100644
index 0000000000..c408b1e674
--- /dev/null
+++
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/spark/sql/paimon/OssieSemanticViewTest.scala
@@ -0,0 +1,495 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.paimon
+
+import org.apache.paimon.catalog.{DelegateCatalog, Identifier}
+import org.apache.paimon.management.SemanticViewManagement
+import org.apache.paimon.rest.{RESTApi, RESTCatalog, RESTCatalogServer}
+import org.apache.paimon.rest.auth.{AuthProvider, BearTokenAuthProvider}
+import org.apache.paimon.rest.requests.UpsertSemanticViewRequest
+import org.apache.paimon.rest.responses.{ConfigResponse,
GetSemanticViewResponse}
+import org.apache.paimon.spark.SparkCatalog
+import org.apache.paimon.spark.extensions.PaimonSparkSessionExtensions
+import org.apache.paimon.view.SemanticViewDefinition
+
+import okhttp3.mockwebserver.{Dispatcher, MockResponse, RecordedRequest}
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.{QueryTest, Row}
+import org.apache.spark.sql.test.SharedSparkSession
+
+import java.nio.file.Files
+import java.util.Collections
+import java.util.concurrent.ConcurrentHashMap
+
+/** Real Spark queries, real REST client, and physical Paimon source files. */
+class OssieSemanticViewTest extends QueryTest with SharedSparkSession {
+ private val id = Identifier.create("sales", "order_metrics")
+ private val directory = Files.createTempDirectory("paimon-ossie-").toFile
+ private lazy val server = {
+ val s = new SemanticServer(directory.toURI.toString)
+ s.start()
+ s
+ }
+ private def models: SemanticViewManagement = {
+ val catalog =
spark.sessionState.catalogManager.catalog("paimon").asInstanceOf[SparkCatalog]
+ DelegateCatalog
+ .rootCatalog(catalog.paimonCatalog())
+ .asInstanceOf[RESTCatalog]
+ .semanticViewManagement()
+ }
+
+ override protected def sparkConf: SparkConf = super.sparkConf
+ .set("spark.sql.catalog.paimon", classOf[SparkCatalog].getName)
+ .set("spark.sql.catalog.paimon.metastore", "rest")
+ .set("spark.sql.catalog.paimon.uri", server.getUrl)
+ .set("spark.sql.catalog.paimon.warehouse", "ossie-tests")
+ .set("spark.sql.catalog.paimon.token.provider", "bear")
+ .set("spark.sql.catalog.paimon.token", "test-token")
+ .set("spark.sql.catalog.paimon.cache-enabled", "false")
+ .set("spark.sql.extensions", classOf[PaimonSparkSessionExtensions].getName)
+
+ override protected def beforeAll(): Unit = {
+ super.beforeAll()
+ spark.sql("CREATE DATABASE paimon.sales")
+ spark.sql(
+ "CREATE TABLE paimon.sales.orders (region_code STRING, amount
DECIMAL(12, 2), " +
+ "discount DECIMAL(12, 2)) TBLPROPERTIES ('bucket'='-1',
'file.format'='avro')")
+ spark.sql(
+ "INSERT INTO paimon.sales.orders VALUES ('CN', 100, 10), ('CN', 100,
20), ('SG', 80, 20)")
+ }
+
+ override protected def afterAll(): Unit = {
+ try {
+ super.afterAll()
+ } finally {
+ server.shutdown()
+ org.apache.spark.util.Utils.deleteRecursively(directory)
+ }
+ }
+
+ private def register(yaml: String = model): Unit = {
+ server.semanticStatus = 200
+ server.denySource = false
+ models.upsertSemanticView(id, new SemanticViewDefinition("ossie-yaml",
yaml))
+ }
+
+ test("query dataset and model metrics with field/source shadowing and
distinct aggregates") {
+ register()
+ checkAnswer(
+ spark.sql(
+ "SELECT region, MEASURE(revenue), MEASURE(gross), MEASURE(orders), " +
+ "MEASURE(average), MEASURE(distinct_amounts), MEASURE(model_revenue)
" +
+ "FROM paimon.sales.order_metrics GROUP BY region"),
+ Seq(
+ Row("CN", BigDecimal(170), BigDecimal(200), 2L, BigDecimal(85), 1L,
BigDecimal(170)),
+ Row("SG", BigDecimal(60), BigDecimal(80), 1L, BigDecimal(60), 1L,
BigDecimal(60))
+ )
+ )
+ checkAnswer(
+ spark.sql(
+ "SELECT MEASURE(revenue), MEASURE(orders) " +
+ "FROM paimon.sales.order_metrics WHERE region = 'CN'"),
+ Seq(Row(BigDecimal(170), 2L)))
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(230))))
+ assert(server.authorizedSemanticReads > 0)
+ checkAnswer(
+ spark.sql(
+ "SELECT MEASURE(revenue), MEASURE(orders) " +
+ "FROM paimon.sales.order_metrics WHERE region = 'missing'"),
+ Seq(Row(null, 0L)))
+ }
+
+ test("public field names cannot shadow private metric input aliases") {
+ Seq("__ossie_f1", "__ossie_0_f1").foreach {
+ name =>
+ register(model.replace("name: region", s"name: $name"))
+ checkAnswer(
+ spark.sql(
+ s"SELECT MEASURE(revenue) FROM paimon.sales.order_metrics " +
+ s"WHERE $name = 'CN'"),
+ Seq(Row(BigDecimal(170))))
+ }
+ }
+
+ test("preserve FILTER, quoted identifiers, true division, and
half-away-from-zero rounding") {
+ register(
+ model
+ .replace("sql: SUM(amount)", "sql: ROUND(SUM(amount) / COUNT(*), 0)")
+ .replace(
+ "sql: COUNT(DISTINCT source.amount)",
+ "sql: COUNT(DISTINCT source.amount) FILTER (WHERE region = 'CN')")
+ .replace(
+ "sql: AVG(amount)",
+ "sql: AVG(CASE WHEN \"region\" = 'CN' THEN \"amount\" ELSE NULL
END)")
+ .replace("sql: SUM(source.amount)", "sql: ROUND(MIN(CAST(-2.5 AS
DECIMAL(3, 1))), 0)")
+ .replace("sql: SUM(orders.amount)", "sql: COUNT(*) / COUNT(DISTINCT
orders.region)"))
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue), MEASURE(distinct_amounts), " +
+ "MEASURE(average), MEASURE(gross), MEASURE(model_revenue) FROM
paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(77), 1L, BigDecimal(85), BigDecimal(-3), 1.5d))
+ )
+ }
+
+ test("new analysis sees REST replacement and is independent of the current
database") {
+ register()
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(230))))
+ register(model.replace("sql: SUM(amount)", "sql: MAX(amount)"))
+ withSQLConf("spark.sql.caseSensitive" -> "true") {
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(90))))
+ }
+ checkAnswer(spark.sql("SELECT SUM(amount) FROM paimon.sales.orders"),
Seq(Row(BigDecimal(280))))
+ spark.sql(
+ "CREATE OR REPLACE VIEW paimon.sales.ordinary AS SELECT region_code FROM
paimon.sales.orders")
+ checkAnswer(
+ spark.sql("SELECT * FROM paimon.sales.ordinary"),
+ Seq(Row("CN"), Row("CN"), Row("SG")))
+ assert(spark.sql("DESCRIBE
paimon.sales.orders").collect().exists(_.getString(0) == "amount"))
+ spark.sql("CREATE OR REPLACE FUNCTION paimon.sales.add_one(x INT) RETURNS
INT RETURN x + 1")
+ checkAnswer(spark.sql("SELECT paimon.sales.add_one(4)"), Seq(Row(5)))
+ }
+
+ test("portable string literals keep backslashes and apostrophes under either
Spark setting") {
+ Seq(false, true).foreach {
+ escaped =>
+ withSQLConf("spark.sql.parser.escapedStringLiterals" ->
escaped.toString) {
+ Seq("C:\\new\\tab\\%\\path's", "O'Brien", "", "路径\\new").foreach {
+ value =>
+ val literal = "'" + value.replace("'", "''") + "'"
+ register(
+ model
+ .replace("sql: region_code", s"sql: |-\n
$literal")
+ .replace(
+ "sql: COUNT(DISTINCT source.amount)",
+ s"sql: COUNT(*) FILTER (WHERE region = $literal)"))
+ checkAnswer(
+ spark.sql("SELECT region, MEASURE(revenue),
MEASURE(distinct_amounts) " +
+ "FROM paimon.sales.order_metrics GROUP BY region"),
+ Seq(Row(value, BigDecimal(230), 3L))
+ )
+ }
+ register(model
+ .replace("sql: region_code", "sql: |-\n CAST(DATE
'2026-11-13' AS STRING)"))
+ checkAnswer(
+ spark.sql(
+ "SELECT region, MEASURE(revenue) FROM paimon.sales.order_metrics
GROUP BY region"),
+ Seq(Row("2026-11-13", BigDecimal(230))))
+ register(
+ model.replace(
+ "sql: region_code",
+ "sql: |-\n CASE WHEN \"region_code\" = 'CN' /* '
ignored */ " +
+ "THEN 'O''Brien' -- ' ignored\n ELSE '路径\\new' END"
+ ))
+ checkAnswer(
+ spark.sql(
+ "SELECT region, MEASURE(revenue) FROM paimon.sales.order_metrics
GROUP BY region"),
+ Seq(Row("O'Brien", BigDecimal(170)), Row("路径\\new",
BigDecimal(60)))
+ )
+ }
+ }
+ }
+
+ test("CTE aliases and lateral syntax cannot hide unsupported semantic
joins") {
+ register()
+ Seq(
+ "SELECT m.region, MEASURE(m.revenue) FROM paimon.sales.order_metrics m "
+
+ "JOIN LATERAL (SELECT 1 AS x) t ON true GROUP BY m.region",
+ "WITH m AS (SELECT * FROM paimon.sales.order_metrics) " +
+ "SELECT MEASURE(m.revenue) FROM m JOIN paimon.sales.orders o " +
+ "ON m.region=o.region_code GROUP BY m.region",
+ "WITH m AS (SELECT * FROM paimon.sales.order_metrics), n AS (SELECT *
FROM m) " +
+ "SELECT MEASURE(n.revenue) FROM n JOIN paimon.sales.orders o " +
+ "ON n.region=o.region_code GROUP BY n.region",
+ "WITH m AS (SELECT * FROM paimon.sales.order_metrics) " +
+ "SELECT (SELECT MEASURE(m.revenue) FROM m JOIN paimon.sales.orders o "
+
+ "ON m.region=o.region_code) AS revenue"
+ ).foreach {
+ query =>
+ val error = intercept[Exception](spark.sql(query).collect())
+ assert(error.toString.contains("Joins against Ossie"), error.toString)
+ }
+ checkAnswer(
+ spark.sql(
+ "WITH m AS (SELECT MEASURE(revenue) AS revenue " +
+ "FROM paimon.sales.order_metrics) SELECT revenue FROM m"),
+ Seq(Row(BigDecimal(230))))
+ checkAnswer(
+ spark.sql(
+ "WITH ordinary AS (SELECT o.region_code FROM paimon.sales.orders o " +
+ "JOIN paimon.sales.orders p ON o.region_code=p.region_code) " +
+ "SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(230)))
+ )
+ }
+
+ test("portable SQL line comments end at CR, LF and CRLF") {
+ Seq("\r", "\n", "\r\n").foreach {
+ newline =>
+ val expression = RESTApi.toJson("SUM(amount) -- a comment" + newline +
" + COUNT(*)")
+ register(model.replace("sql: SUM(amount)", "sql: " + expression))
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(233))))
+ }
+ }
+
+ test("ANSI quoted source columns retain backslashes and embedded double
quotes") {
+ val columns = Seq("tail\\", "back\\\"quote", "apostrophe'name")
+ def quoted(name: String): String = "`" + name.replace("`", "``") + "`"
+ val schema = columns.map(name => quoted(name) + " STRING").mkString(", ")
+ spark.sql(
+ "CREATE TABLE paimon.sales.quoted_columns (" + schema +
+ ", amount DECIMAL(12, 2), discount DECIMAL(12, 2)) " +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='parquet')")
+ spark.sql("INSERT INTO paimon.sales.quoted_columns VALUES ('v0', 'v1',
'v2', 100, 10)")
+ Seq(false, true).foreach {
+ escaped =>
+ withSQLConf("spark.sql.parser.escapedStringLiterals" ->
escaped.toString) {
+ columns.zipWithIndex.foreach {
+ case (column, index) =>
+ val expression = RESTApi.toJson("\"" + column.replace("\"",
"\"\"") + "\"")
+ register(
+ model
+ .replace("source: orders", "source: quoted_columns")
+ .replace("sql: region_code", "sql: " + expression))
+ checkAnswer(
+ spark.sql(
+ "SELECT region, MEASURE(revenue) FROM
paimon.sales.order_metrics GROUP BY region"),
+ Seq(Row("v" + index, BigDecimal(90))))
+ }
+ }
+ }
+ }
+
+ test("all semantic view write targets fail without changing the source") {
+ register()
+ val statements = Seq(
+ "DELETE FROM paimon.sales.order_metrics",
+ "UPDATE paimon.sales.order_metrics SET region='changed'",
+ "MERGE INTO paimon.sales.order_metrics m USING (SELECT 'CN' AS region) s
" +
+ "ON m.region=s.region WHEN MATCHED THEN DELETE"
+ )
+ statements.foreach {
+ statement =>
+ intercept[Exception](spark.sql(statement).collect())
+ checkAnswer(
+ spark.sql("SELECT SUM(amount), COUNT(*) FROM paimon.sales.orders"),
+ Seq(Row(BigDecimal(280), 3L)))
+ }
+ }
+
+ test("preserve REST and source authorization errors") {
+ register()
+ Seq(403, 501).foreach {
+ status =>
+ server.semanticStatus = status
+ checkAnswer(
+ spark.sql("SELECT SUM(amount) FROM paimon.sales.orders"),
+ Seq(Row(BigDecimal(280))))
+ val error = intercept[Exception] {
+ spark.sql("SELECT MEASURE(revenue) FROM
paimon.sales.order_metrics").collect()
+ }
+ assert(error.toString.contains("semantic access failed"))
+ }
+ server.semanticStatus = 200
+ server.denySource = true
+ val error = intercept[Exception] {
+ spark.sql("SELECT MEASURE(revenue) FROM
paimon.sales.order_metrics").collect()
+ }
+ assert(error.toString.contains("source access denied"))
+ server.denySource = false
+ val missing = intercept[Exception] {
+ spark.sql("SELECT * FROM paimon.sales.missing_model").collect()
+ }
+ assert(missing.toString.contains("TABLE_OR_VIEW_NOT_FOUND"))
+ }
+
+ test("reject unsupported models, joins, and invalid metric references") {
+ Seq(
+ model.replace("version: 0.3.0.dev0", "version: 0.1.1") -> "Invalid
Ossie",
+ model.replace("sql: SUM(amount)", "sql: SUM(discount)") -> "Unknown
Ossie dataset field",
+ model.replace(
+ "sql: SUM(amount)",
+ "sql: SUM(orders.amount)") -> "Invalid Ossie metric reference",
+ model.replace("sql: SUM(amount)", "sql: SUM(gross)") -> "Unknown Ossie
dataset field",
+ model.replace("sql: SUM(amount)", "sql: MEDIAN(amount)") -> "Unsupported
OSSIE_SQL_2026",
+ model.replace("sql: SUM(amount)", "sql: SUM(amount) OVER ()") ->
"Unsupported OSSIE_SQL_2026",
+ model.replace("sql: region_code", "sql: |-\n r'raw'") ->
"ANSI string literals",
+ model.replace("source: orders", "source: other.sales.orders") -> "same
Paimon catalog",
+ model.replace("source: orders", "source: order_metrics") ->
"order_metrics"
+ ).foreach {
+ case (yaml, message) =>
+ register(yaml)
+ val error = intercept[Exception] {
+ spark.sql("SELECT MEASURE(revenue) FROM
paimon.sales.order_metrics").collect()
+ }
+ assert(error.toString.contains(message), error.toString)
+ }
+ register()
+ val join = intercept[Exception] {
+ spark
+ .sql("SELECT MEASURE(m.revenue) FROM paimon.sales.order_metrics m " +
+ "JOIN paimon.sales.orders o ON m.region = o.region_code GROUP BY
m.region")
+ .collect()
+ }
+ assert(join.toString.contains("Joins against Ossie"))
+ val write = intercept[Exception] {
+ spark.sql("INSERT INTO paimon.sales.order_metrics SELECT 'CN', 1, 2, 3,
4, 5, 6, 7").collect()
+ }
+ assert(
+ write.toString.contains("read-only") ||
+ write.toString.contains("TABLE_OR_VIEW_NOT_FOUND"),
+ write.toString)
+ intercept[Exception] {
+ spark.readStream.table("paimon.sales.order_metrics")
+ }
+ }
+
+ test(
+ "source identifiers bind to the view catalog and database instead of the
current namespace") {
+ val manager = spark.sessionState.catalogManager
+ val previous = manager.currentCatalog.name() +:
manager.currentNamespace.toSeq
+ spark.sql("CREATE DATABASE paimon.elsewhere")
+ spark.sql(
+ "CREATE TABLE paimon.elsewhere.orders " +
+ "(region_code STRING, amount DECIMAL(12, 2), discount DECIMAL(12, 2))
" +
+ "TBLPROPERTIES ('bucket'='-1', 'file.format'='avro')")
+ spark.sql("INSERT INTO paimon.elsewhere.orders VALUES ('CN', 999, 0)")
+ try {
+ spark.sql("USE paimon.elsewhere")
+ Seq("orders", "sales.orders", "paimon.sales.orders").foreach {
+ source =>
+ register(model.replace("source: orders", s"source: $source"))
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM
paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(230))))
+ }
+ } finally {
+ spark.sql("USE " + previous.map(p => "`" + p.replace("`", "``") +
"`").mkString("."))
+ }
+ }
+
+ test("analyzed queries retain their definition and queries preserve original
metadata") {
+ val original = model +
+ "nonportable_extensions:\n - vendor_name: unknown\n data: {date:
'2026-11-13', nested: [null, true]}\n"
+ register(original)
+ val writes = server.semanticWrites
+ val retained = spark.sql("SELECT MEASURE(revenue) FROM
paimon.sales.order_metrics")
+ retained.queryExecution.analyzed
+ checkAnswer(retained, Seq(Row(BigDecimal(230))))
+ assert(models.getSemanticView(id).getDefinition.getContent == original)
+ assert(server.semanticWrites == writes)
+ register(model.replace("sql: SUM(amount)", "sql: MAX(amount)"))
+ checkAnswer(retained, Seq(Row(BigDecimal(230))))
+ checkAnswer(
+ spark.sql("SELECT MEASURE(revenue) FROM paimon.sales.order_metrics"),
+ Seq(Row(BigDecimal(90))))
+ }
+
+ private def model: String =
+ """version: 0.3.0.dev0
+ |name: order_metrics
+ |datasets:
+ | - name: orders
+ | source: orders
+ | fields:
+ | - name: region
+ | expression:
+ | sql: region_code
+ | - name: amount
+ | expression:
+ | sql: amount - discount
+ | metrics:
+ | - name: revenue
+ | expression:
+ | sql: SUM(amount)
+ | - name: gross
+ | expression:
+ | sql: SUM(source.amount)
+ | - name: orders
+ | expression:
+ | sql: COUNT(*)
+ | - name: average
+ | expression:
+ | sql: AVG(amount)
+ | - name: distinct_amounts
+ | expression:
+ | sql: COUNT(DISTINCT source.amount)
+ |metrics:
+ | - name: model_revenue
+ | expression:
+ | sql: SUM(orders.amount)
+ |""".stripMargin
+}
+
+private class SemanticServer(path: String)
+ extends RESTCatalogServer(
+ path,
+ new BearTokenAuthProvider("test-token"),
+ new ConfigResponse(Collections.singletonMap("prefix", "paimon"),
Collections.emptyMap()),
+ "ossie-tests") {
+ private val definitions = new ConcurrentHashMap[String,
SemanticViewDefinition]()
+ @volatile var semanticStatus: Int = 200
+ @volatile var denySource: Boolean = false
+ @volatile var authorizedSemanticReads: Int = 0
+ @volatile var semanticWrites: Int = 0
+
+ override def initDispatcher(auth: AuthProvider): Dispatcher = {
+ val delegate = super.initDispatcher(auth)
+ new Dispatcher {
+ override def dispatch(request: RecordedRequest): MockResponse = {
+ val route = request.getRequestUrl.encodedPath()
+ def response(status: Int, body: String): MockResponse = new
MockResponse()
+ .setResponseCode(status)
+ .setHeader("Content-Type", "application/json")
+ .setBody(body)
+ if (route.contains("/semantic-views/")) {
+ val name = request.getRequestUrl
+ .pathSegments()
+ .get(request.getRequestUrl.pathSegments().size() - 1)
+ if (request.getMethod == "POST") {
+ semanticWrites += 1
+ val value =
+ RESTApi.fromJson(request.getBody.readUtf8(),
classOf[UpsertSemanticViewRequest])
+ definitions.put(name, value.getDefinition)
+ } else {
+ if (semanticStatus != 200) {
+ return response(semanticStatus, "{\"message\":\"semantic access
failed\"}")
+ }
+ if (request.getHeader("Authorization") == "Bearer test-token") {
+ authorizedSemanticReads += 1
+ }
+ }
+ val definition = definitions.get(name)
+ if (definition == null) response(404, "{\"message\":\"missing
semantic view\"}")
+ else response(200, RESTApi.toJson(new GetSemanticViewResponse(name,
definition)))
+ } else if (denySource && route.endsWith("/tables/orders")) {
+ response(403, "{\"message\":\"source access denied\"}")
+ } else {
+ delegate.dispatch(request)
+ }
+ }
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
index 4390c4207d..e3254f0e34 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/extensions/PaimonSparkSessionExtensions.scala
@@ -42,6 +42,11 @@ class PaimonSparkSessionExtensions extends
(SparkSessionExtensions => Unit) {
extensions.injectResolutionRule(spark => PaimonProcedureResolver(spark))
extensions.injectResolutionRule(spark => PaimonViewResolver(spark))
if (org.apache.spark.SPARK_VERSION.startsWith("4.2.")) {
+ val resolver = Class
+ .forName("org.apache.spark.sql.paimon.PaimonSemanticViewResolver")
+ .getConstructor(classOf[org.apache.spark.sql.SparkSession])
+ extensions.injectResolutionRule(
+ spark => resolver.newInstance(spark).asInstanceOf[Rule[LogicalPlan]])
val module =
Class.forName("org.apache.spark.sql.catalyst.analysis.Spark42RowLevelCommandRewrite$")
val rule =
module.getField("MODULE$").get(null).asInstanceOf[Rule[LogicalPlan]]