World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14831] test(semantic): Validate and document source lookup (#14832)
mchadeseead9d70abf6
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.javaindex 72ceedf795..fc822a8678 100644--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/lance/integration/test/CatalogGenericCatalogLanceIT.java@@ -78,6 +78,8 @@ import org.apache.gravitino.rel.indexes.Indexes;import org.apache.gravitino.rel.partitions.Partitions;import org.apache.gravitino.rel.partitions.RangePartition;import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.semantic.SemanticModelChange;+import org.apache.gravitino.semantic.SemanticModelDefinition;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;@@ -157,6 +159,59 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {createSchema();}+ /** Verifies dataset lookup for a managed Lance table in the Generic catalog. */+ @Test+ public void testSemanticModelLookupForManagedTable() {+ NameIdentifier source = NameIdentifier.of(schemaName, tableName);+ catalog+ .asTableCatalog()+ .createTable(+ source,+ new Column[] {Column.of("id", Types.LongType.get())},+ null,+ Map.of(+ Table.PROPERTY_TABLE_FORMAT,+ LANCE_TABLE_FORMAT,+ Table.PROPERTY_LOCATION,+ tempDirectory + "/source_lookup.lance"));+ SemanticModelDefinition definition =+ SemanticModelDefinition.builder()+ .withDatasets(+ new org.apache.gravitino.semantic.Dataset[] {+ org.apache.gravitino.semantic.Dataset.builder()+ .withName("managed.alias")+ .withSource(NameIdentifier.of(catalogName, schemaName, tableName))+ .build()+ })+ .build();+ NameIdentifier model = NameIdentifier.of(schemaName, "source_lookup_model");+ try {+ catalog.asSemanticModelCatalog().createSemanticModel(model, null, definition, Map.of());+ Assertions.assertArrayEquals(+ new NameIdentifier[] {+ NameIdentifier.of(metalakeName, catalogName, schemaName, model.name(), "managed.alias")+ },+ catalog+ .asTableCatalog()+ .loadTable(source)+ .supportsSemanticModels()+ .listSemanticModelDatasets());+ catalog+ .asSemanticModelCatalog()+ .alterSemanticModel(model, SemanticModelChange.replaceDefinition(definition));+ Assertions.assertEquals(+ 1,+ catalog+ .asTableCatalog()+ .loadTable(source)+ .supportsSemanticModels()+ .listSemanticModelDatasets()+ .length);+ } finally {+ catalog.asSemanticModelCatalog().dropSemanticModel(model);+ }+ }+@Testvoid testExistingCatalogConnectionIsUnsupported() {Assertions.assertThrows(diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.javaindex a57eb253b7..a59ebb5cb7 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java@@ -57,6 +57,7 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;import org.apache.gravitino.exceptions.NoSuchTagException;@@ -68,7 +69,13 @@ import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyContents;import org.apache.gravitino.policy.SupportsPolicies;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.View;+import org.apache.gravitino.rel.ViewCatalog;+import org.apache.gravitino.rel.ViewChange;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.semantic.AIContext;import org.apache.gravitino.semantic.AIContextObject;@@ -89,6 +96,7 @@ import org.apache.gravitino.semantic.SemanticModelCatalog;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SupportsSemanticModels;import org.apache.gravitino.tag.SupportsTags;import org.apache.gravitino.tag.Tag;import org.apache.gravitino.tag.TagValue;@@ -194,6 +202,151 @@ public class SemanticModelIT extends BaseIT {}}+ /** Verifies source identity, definition replacement, and model lifecycle through the Java SDK. */+ @Test+ public void testSourceLookupLifecycleAndIdenticalDefinitionRebinding() {+ TableCatalog tables = catalog.asTableCatalog();+ NameIdentifier source = NameIdentifier.of(SCHEMA_NAME, "lookup_orders");+ NameIdentifier renamedSource = NameIdentifier.of(SCHEMA_NAME, "lookup_orders_v2");+ NameIdentifier model = NameIdentifier.of(SCHEMA_NAME, "lookup_model");+ NameIdentifier renamedModel = NameIdentifier.of(SCHEMA_NAME, "lookup_model_v2");+ Column[] columns = {Column.of("id", Types.LongType.get())};+ try {+ SupportsSemanticModels lookup =+ tables.createTable(source, columns, null, Map.of()).supportsSemanticModels();+ assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());+ SemanticModelDefinition definition =+ sourceDefinition(source.name(), "manager", "employee.raw");+ semanticModelCatalog.createSemanticModel(model, null, definition, Map.of());+ assertArrayEquals(+ sourceDatasetIds(model.name(), "employee.raw", "manager"),+ lookup.listSemanticModelDatasets());++ tables.alterTable(source, TableChange.rename(renamedSource.name()));+ assertThrows(NoSuchMetadataObjectException.class, lookup::listSemanticModelDatasets);+ lookup = tables.loadTable(renamedSource).supportsSemanticModels();+ assertArrayEquals(+ sourceDatasetIds(model.name(), "employee.raw", "manager"),+ lookup.listSemanticModelDatasets());+ assertEquals(+ source.name(),+ semanticModelCatalog.loadSemanticModel(model).definition().datasets()[0].source().name());+ semanticModelCatalog.alterSemanticModel(+ model,+ SemanticModelChange.rename(renamedModel.name()),+ SemanticModelChange.updateComment("source name drift is preserved"));+ assertArrayEquals(+ sourceDatasetIds(renamedModel.name(), "employee.raw", "manager"),+ lookup.listSemanticModelDatasets());++ SemanticModelDefinition replacement = sourceDefinition(renamedSource.name(), "orders");+ semanticModelCatalog.alterSemanticModel(+ renamedModel, SemanticModelChange.replaceDefinition(replacement));+ assertArrayEquals(+ sourceDatasetIds(renamedModel.name(), "orders"), lookup.listSemanticModelDatasets());+ assertThrows(+ IllegalSemanticModelException.class,+ () ->+ semanticModelCatalog.alterSemanticModel(+ renamedModel,+ SemanticModelChange.replaceDefinition(+ sourceDefinition("missing_lookup_source", "invalid"))));+ assertArrayEquals(+ sourceDatasetIds(renamedModel.name(), "orders"), lookup.listSemanticModelDatasets());++ tables.dropTable(renamedSource);+ lookup = tables.createTable(renamedSource, columns, null, Map.of()).supportsSemanticModels();+ assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());+ semanticModelCatalog.alterSemanticModel(+ renamedModel, SemanticModelChange.setProperty("reviewed", "true"));+ assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());+ semanticModelCatalog.alterSemanticModel(+ renamedModel, SemanticModelChange.replaceDefinition(replacement));+ assertArrayEquals(+ sourceDatasetIds(renamedModel.name(), "orders"), lookup.listSemanticModelDatasets());+ semanticModelCatalog.dropSemanticModel(renamedModel);+ assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());+ } finally {+ tables.dropTable(source);+ tables.dropTable(renamedSource);+ }+ }++ /**+ * Verifies direct View references across catalogs and cleanup after the model catalog is dropped.+ */+ @Test+ public void testViewSourceLookupAcrossCatalogs() {+ ViewCatalog views = catalog.asViewCatalog();+ NameIdentifier source = NameIdentifier.of(SCHEMA_NAME, "lookup_view");+ NameIdentifier renamedSource = NameIdentifier.of(SCHEMA_NAME, "lookup_view_v2");+ String otherCatalogName = "source_lookup_models";+ String otherSchema = "semantic";+ String modelName = "cross_catalog_model";+ try {+ View view =+ views.createView(+ source,+ null,+ new Column[] {Column.of("id", Types.LongType.get())},+ new Representation[] {+ SQLRepresentation.builder()+ .withDialect("trino")+ .withSql("SELECT id FROM customers")+ .build()+ },+ CATALOG_NAME,+ SCHEMA_NAME,+ Map.of());+ Catalog other =+ metalake.createCatalog(+ otherCatalogName,+ Catalog.Type.RELATIONAL,+ "lakehouse-iceberg",+ null,+ Map.of(+ "catalog-backend",+ "jdbc",+ "warehouse",+ System.getProperty("java.io.tmpdir") + "/" + METALAKE_NAME + "_lookup",+ "uri",+ "jdbc:h2:mem:" + METALAKE_NAME + "_lookup;DB_CLOSE_DELAY=-1;MODE=MYSQL",+ "jdbc-driver",+ "org.h2.Driver",+ "jdbc-initialize",+ "true"));+ other.asSchemas().createSchema(otherSchema, null, Map.of());+ other+ .asSemanticModelCatalog()+ .createSemanticModel(+ NameIdentifier.of(otherSchema, modelName),+ null,+ sourceDefinition(source.name(), "view.alias"),+ Map.of());+ NameIdentifier[] expected = {+ NameIdentifier.of(METALAKE_NAME, otherCatalogName, otherSchema, modelName, "view.alias")+ };+ assertArrayEquals(expected, view.supportsSemanticModels().listSemanticModelDatasets());+ // A View reference is direct: its underlying table does not inherit the model association.+ assertArrayEquals(+ new NameIdentifier[0],+ catalog+ .asTableCatalog()+ .loadTable(NameIdentifier.of(SCHEMA_NAME, CUSTOMERS_TABLE))+ .supportsSemanticModels()+ .listSemanticModelDatasets());+ views.alterView(source, ViewChange.rename(renamedSource.name()));+ SupportsSemanticModels lookup = views.loadView(renamedSource).supportsSemanticModels();+ assertArrayEquals(expected, lookup.listSemanticModelDatasets());+ metalake.dropCatalog(otherCatalogName, true);+ assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());+ } finally {+ metalake.dropCatalog(otherCatalogName, true);+ views.dropView(source);+ views.dropView(renamedSource);+ }+ }+@Testpublic void testSemanticModelLifecycleRoundTrip() {NameIdentifier modelIdent = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);@@ -1098,6 +1251,26 @@ public class SemanticModelIT extends BaseIT {.listTags());}+ private static SemanticModelDefinition sourceDefinition(String source, String... aliases) {+ return SemanticModelDefinition.builder()+ .withDatasets(+ Arrays.stream(aliases)+ .map(+ alias ->+ Dataset.builder()+ .withName(alias)+ .withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME, source))+ .build())+ .toArray(Dataset[]::new))+ .build();+ }++ private static NameIdentifier[] sourceDatasetIds(String model, String... aliases) {+ return Arrays.stream(aliases)+ .map(alias -> NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, model, alias))+ .toArray(NameIdentifier[]::new);+ }+private static ObjectNode ossieModelDocument() {ObjectNode root = JSON_MAPPER.createObjectNode();root.put("version", DEFAULT_VERSION);diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/SemanticModelSourceAuthorizationIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/SemanticModelSourceAuthorizationIT.javanew file mode 100644index 0000000000..64ee3e3f74--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/SemanticModelSourceAuthorizationIT.java@@ -0,0 +1,178 @@+/*+ * 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.gravitino.client.integration.test.authorization;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.stream.Stream;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.MetadataObjects;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.authorization.Owner;+import org.apache.gravitino.authorization.Privileges;+import org.apache.gravitino.authorization.SecurableObjects;+import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SupportsSemanticModels;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++/** Exercises source lookup with real source and containing-model authorization. */+public class SemanticModelSourceAuthorizationIT extends BaseRestApiAuthorizationIT {+ private static final String CATALOG = "source_lookup_a";+ private static final String OTHER_CATALOG = "source_lookup_b";+ private static final String ROLE = "source_lookup_reader";+ private static final String SOURCE_SCHEMA = "sources";+ private static final String MODEL_SCHEMA = "models";+ private GravitinoMetalake metalake;+ private SupportsSemanticModels readerSource;++ /** Creates sources and models in separate schemas and catalogs with distinct access grants. */+ @BeforeAll+ public void setUpSourceLookup() {+ metalake = client.loadMetalake(METALAKE);+ Catalog sourceCatalog = createCatalog(CATALOG);+ sourceCatalog.asSchemas().createSchema(SOURCE_SCHEMA, null, Map.of());+ sourceCatalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(SOURCE_SCHEMA, "orders"),+ new Column[] {Column.of("id", Types.LongType.get())},+ null,+ Map.of());+ SemanticModelDefinition definition =+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {dataset("employee.raw"), dataset("manager")})+ .build();+ for (Catalog catalog : List.of(sourceCatalog, createCatalog(OTHER_CATALOG))) {+ catalog.asSchemas().createSchema(MODEL_SCHEMA, null, Map.of());+ for (String model : List.of("hidden", "owned", "use")) {+ catalog+ .asSemanticModelCatalog()+ .createSemanticModel(+ NameIdentifier.of(MODEL_SCHEMA, model), null, definition, Map.of());+ }+ metalake.setOwner(model(catalog.name(), "owned"), NORMAL_USER, Owner.Type.USER);+ }+ metalake.createRole(+ ROLE,+ Map.of(),+ List.of(SecurableObjects.ofCatalog(CATALOG, List.of(Privileges.UseCatalog.allow()))));+ metalake.grantPrivilegesToRole(+ ROLE,+ MetadataObjects.of(CATALOG, SOURCE_SCHEMA, MetadataObject.Type.SCHEMA),+ List.of(Privileges.UseSchema.allow()));+ metalake.grantPrivilegesToRole(+ ROLE,+ MetadataObjects.of(List.of(CATALOG, SOURCE_SCHEMA, "orders"), MetadataObject.Type.TABLE),+ List.of(Privileges.SelectTable.allow()));+ metalake.grantRolesToUser(List.of(ROLE), NORMAL_USER);+ metalake.grantPrivilegesToRole(+ ROLE, model(CATALOG, "use"), List.of(Privileges.UseSemanticModel.allow()));+ readerSource =+ normalUserClient+ .loadMetalake(METALAKE)+ .loadCatalog(CATALOG)+ .asTableCatalog()+ .loadTable(NameIdentifier.of(SOURCE_SCHEMA, "orders"))+ .supportsSemanticModels();+ }++ @Test+ void testChecksSourceAndEachModelsOwnParents() {+ // Owning a model does not bypass missing access to its schema or catalog.+ assertArrayEquals(new NameIdentifier[0], readerSource.listSemanticModelDatasets());+ metalake.grantPrivilegesToRole(ROLE, schema(CATALOG), List.of(Privileges.UseSchema.allow()));+ assertArrayEquals(expected(CATALOG, "owned", "use"), readerSource.listSemanticModelDatasets());+ metalake.grantPrivilegesToRole(+ ROLE, schema(OTHER_CATALOG), List.of(Privileges.UseSchema.allow()));+ assertArrayEquals(expected(CATALOG, "owned", "use"), readerSource.listSemanticModelDatasets());+ metalake.grantPrivilegesToRole(+ ROLE,+ MetadataObjects.of(null, OTHER_CATALOG, MetadataObject.Type.CATALOG),+ List.of(Privileges.UseCatalog.allow()));+ NameIdentifier[] both =+ Stream.concat(+ Arrays.stream(expected(CATALOG, "owned", "use")),+ Arrays.stream(expected(OTHER_CATALOG, "owned")))+ .toArray(NameIdentifier[]::new);+ assertArrayEquals(both, readerSource.listSemanticModelDatasets());+ metalake.revokePrivilegesFromRole(+ ROLE,+ MetadataObjects.of(List.of(CATALOG, SOURCE_SCHEMA, "orders"), MetadataObject.Type.TABLE),+ Set.of(Privileges.SelectTable.allow()));+ assertThrows(ForbiddenException.class, readerSource::listSemanticModelDatasets);+ }++ private Catalog createCatalog(String name) {+ String database = GravitinoITUtils.genRandomName("source_auth");+ return metalake.createCatalog(+ name,+ Catalog.Type.RELATIONAL,+ "lakehouse-iceberg",+ null,+ Map.of(+ "catalog-backend",+ "jdbc",+ "warehouse",+ System.getProperty("java.io.tmpdir") + "/" + database,+ "uri",+ "jdbc:h2:mem:" + database + ";DB_CLOSE_DELAY=-1;MODE=MYSQL",+ "jdbc-driver",+ "org.h2.Driver",+ "jdbc-initialize",+ "true"));+ }++ private static Dataset dataset(String name) {+ return Dataset.builder()+ .withName(name)+ .withSource(NameIdentifier.of(CATALOG, SOURCE_SCHEMA, "orders"))+ .build();+ }++ private static MetadataObject model(String catalog, String name) {+ return MetadataObjects.of(+ List.of(catalog, MODEL_SCHEMA, name), MetadataObject.Type.SEMANTIC_MODEL);+ }++ private static MetadataObject schema(String catalog) {+ return MetadataObjects.of(catalog, MODEL_SCHEMA, MetadataObject.Type.SCHEMA);+ }++ private static NameIdentifier[] expected(String catalog, String... models) {+ return Arrays.stream(models)+ .flatMap(+ model ->+ Arrays.stream(new String[] {"employee.raw", "manager"})+ .map(name -> NameIdentifier.of(METALAKE, catalog, MODEL_SCHEMA, model, name)))+ .toArray(NameIdentifier[]::new);+ }+}diff --git a/clients/client-python/tests/integration/test_semantic_model_source_lookup.py b/clients/client-python/tests/integration/test_semantic_model_source_lookup.pynew file mode 100644index 0000000000..026bc4d91f--- /dev/null+++ b/clients/client-python/tests/integration/test_semantic_model_source_lookup.py@@ -0,0 +1,222 @@+# 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.++import shutil+import tempfile+from uuid import uuid4++import requests++from gravitino import Catalog, GravitinoAdminClient, NameIdentifier+from gravitino.api.rel.column import Column+from gravitino.api.rel.sql_representation import SQLRepresentation+from gravitino.api.rel.table_change import TableChange+from gravitino.api.rel.types.types import Types+from gravitino.api.rel.view_change import ViewChange+from gravitino.api.semantic.dataset import Dataset+from gravitino.api.semantic.semantic_model_change import SemanticModelChange+from gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition+from gravitino.exceptions.base import NoSuchMetadataObjectException+from tests.integration.integration_test_env import IntegrationTestEnv+++class TestSemanticModelSourceLookup(IntegrationTestEnv):+ """Exercise the source capability and REST contract against a real server."""++ def setUp(self):+ super().setUp()+ self.location = tempfile.mkdtemp(prefix="source_lookup_")+ self.addCleanup(shutil.rmtree, self.location)+ admin = GravitinoAdminClient(uri="http://localhost:8090")+ self.addCleanup(admin.close)+ self.metalake = "source_lookup_" + uuid4().hex+ self.client = self.create_metalake_client(admin, self.metalake)+ self.addCleanup(self.client.close)+ self.addCleanup(admin.drop_metalake, self.metalake, force=True)+ self.source_catalog = self.client.create_catalog(+ "sources",+ Catalog.Type.RELATIONAL,+ "lakehouse-iceberg",+ "",+ {+ "catalog-backend": "jdbc",+ "warehouse": self.location,+ "uri": f"jdbc:h2:mem:{self.metalake};DB_CLOSE_DELAY=-1;MODE=MYSQL",+ "jdbc-driver": "org.h2.Driver",+ "jdbc-initialize": "true",+ },+ )+ self.source_catalog.as_schemas().create_schema("raw", "", {})+ self.model_catalog = self.client.create_catalog(+ "models", Catalog.Type.RELATIONAL, "lakehouse-generic", "", {}+ )+ for schema in ("semantic", "other"):+ self.model_catalog.as_schemas().create_schema(schema, "", {})+ self.models = self.model_catalog.as_semantic_model_catalog()+ self.table = self._create_table("orders")++ def test_cross_catalog_identifiers_order_and_rest_parity(self):+ aliases = [+ "orders.raw",+ "Orders.raw",+ "dataset_" + "x" * 200,+ "\U00010000",+ "\ue000",+ ]+ expected_aliases = [aliases[1], aliases[2], aliases[0], aliases[3], aliases[4]]+ definition = self._definition("orders", *aliases)+ for schema, model in (("semantic", "a-b"), ("semantic", "a"), ("other", "a")):+ self.models.create_semantic_model(+ NameIdentifier.of(schema, model), "", definition, {}+ )+ expected = [+ self._dataset_id(schema, model, alias)+ for schema, model in (+ ("other", "a"),+ ("semantic", "a"),+ ("semantic", "a-b"),+ )+ for alias in expected_aliases+ ]+ self.assertEqual(expected, self._lookup(self.table))+ with requests.get(+ f"http://localhost:8090/api/metalakes/{self.metalake}/objects/"+ "table/sources.raw.orders/semantic-model-datasets",+ timeout=10,+ ) as response:+ response.raise_for_status()+ self.assertEqual(+ {+ "code": 0,+ "identifiers": [+ {"namespace": item.namespace().levels(), "name": item.name()}+ for item in expected+ ],+ },+ response.json(),+ )+ for dataset in expected:+ model = NameIdentifier.of(*dataset.namespace().levels())+ catalog = self.client.load_catalog(model.namespace().level(1))+ loaded = catalog.as_semantic_model_catalog().load_semantic_model(+ NameIdentifier.of(model.namespace().level(2), model.name())+ )+ self.assertIn(+ dataset.name(), [item.name() for item in loaded.definition().datasets()]+ )+ self.model_catalog.as_schemas().drop_schema("other", True)+ self.assertEqual(expected[5:], self._lookup(self.table))+ self.client.drop_catalog("models", True)+ self.assertEqual([], self._lookup(self.table))++ def test_source_rename_recreation_and_definition_rebinding(self):+ identifier = NameIdentifier.of("semantic", "sales")+ definition = self._definition("orders", "orders.raw")+ self.assertEqual([], self._lookup(self.table))+ self.models.create_semantic_model(identifier, "", definition, {})+ expected = [self._dataset_id("semantic", "sales", "orders.raw")]+ self.assertEqual(expected, self._lookup(self.table))+ tables = self.source_catalog.as_table_catalog()+ renamed = tables.alter_table(+ NameIdentifier.of("raw", "orders"), TableChange.rename("orders_v2")+ )+ with self.assertRaises(NoSuchMetadataObjectException):+ self._lookup(self.table)+ self.assertEqual(expected, self._lookup(renamed))+ self.assertEqual(+ "orders",+ self.models.load_semantic_model(identifier)+ .definition()+ .datasets()[0]+ .source()+ .name(),+ )+ self.models.alter_semantic_model(+ identifier, SemanticModelChange.rename("renamed")+ )+ identifier = NameIdentifier.of("semantic", "renamed")+ expected = [self._dataset_id("semantic", "renamed", "orders.raw")]+ self.assertEqual(expected, self._lookup(renamed))+ replacement = self._definition("orders_v2", "orders.raw")+ self.models.alter_semantic_model(+ identifier, SemanticModelChange.replace_definition(replacement)+ )+ tables.drop_table(NameIdentifier.of("raw", "orders_v2"))+ with self.assertRaises(NoSuchMetadataObjectException):+ self._lookup(renamed)+ recreated = self._create_table("orders_v2")+ self.assertEqual([], self._lookup(recreated))+ self.models.alter_semantic_model(+ identifier, SemanticModelChange.set_property("reviewed", "true")+ )+ self.assertEqual([], self._lookup(recreated))+ self.models.alter_semantic_model(+ identifier, SemanticModelChange.replace_definition(replacement)+ )+ self.assertEqual(expected, self._lookup(recreated))+ self.models.drop_semantic_model(identifier)+ self.assertEqual([], self._lookup(recreated))++ def test_view_lookup_is_direct_and_tracks_source_identity(self):+ views = self.source_catalog.as_view_catalog()+ view = views.create_view(+ NameIdentifier.of("raw", "order_view"),+ [Column.of("id", Types.LongType.get())],+ [SQLRepresentation("trino", "SELECT id FROM orders")],+ default_catalog="sources",+ default_schema="raw",+ )+ identifier = NameIdentifier.of("semantic", "view_model")+ self.models.create_semantic_model(+ identifier, "", self._definition("order_view", "view.raw"), {}+ )+ expected = [self._dataset_id("semantic", "view_model", "view.raw")]+ self.assertEqual(expected, self._lookup(view))+ self.assertEqual([], self._lookup(self.table))+ renamed = views.alter_view(+ NameIdentifier.of("raw", "order_view"), ViewChange.rename("order_view_v2")+ )+ with self.assertRaises(NoSuchMetadataObjectException):+ self._lookup(view)+ self.assertEqual(expected, self._lookup(renamed))+ views.drop_view(NameIdentifier.of("raw", "order_view_v2"))+ with self.assertRaises(NoSuchMetadataObjectException):+ self._lookup(renamed)+ self.models.drop_semantic_model(identifier)++ def _create_table(self, name):+ return self.source_catalog.as_table_catalog().create_table(+ NameIdentifier.of("raw", name),+ [Column.of("id", Types.LongType.get())],+ properties={},+ )++ def _dataset_id(self, schema, model, alias):+ return NameIdentifier.of(self.metalake, "models", schema, model, alias)++ @staticmethod+ def _definition(source, *aliases):+ return SemanticModelDefinition(+ [+ Dataset(alias, NameIdentifier.of("sources", "raw", source))+ for alias in aliases+ ]+ )++ @staticmethod+ def _lookup(source):+ return source.supports_semantic_models().list_semantic_model_datasets()diff --git a/docs/manage-semantic-model-metadata-using-gravitino.md b/docs/manage-semantic-model-metadata-using-gravitino.mdindex 12522ab169..3506589aca 100644--- a/docs/manage-semantic-model-metadata-using-gravitino.md+++ b/docs/manage-semantic-model-metadata-using-gravitino.md@@ -50,9 +50,11 @@ finished; Java file operations also require the calling method to handle or declimport java.nio.file.Files;import java.nio.file.Path;import java.util.Map;+import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.client.GravitinoClient;+import org.apache.gravitino.rel.Table;import org.apache.gravitino.semantic.DataType;import org.apache.gravitino.semantic.Dataset;import org.apache.gravitino.semantic.DialectExpression;@@ -71,7 +73,8 @@ import org.apache.gravitino.semantic.SemanticModelMetric;try (GravitinoClient client = GravitinoClient.builder("http://localhost:8090").withMetalake("example").build()) {- SemanticModelCatalog models = client.loadCatalog("sales").asSemanticModelCatalog();+ Catalog catalog = client.loadCatalog("sales");+ SemanticModelCatalog models = catalog.asSemanticModelCatalog();NameIdentifier ident = NameIdentifier.of("mart", "sales_model");// Run the Java operation examples here.@@ -99,7 +102,8 @@ from gravitino.namespace import Namespaceclient = GravitinoClient(uri="http://localhost:8090", metalake_name="example")try:- models = client.load_catalog("sales").as_semantic_model_catalog()+ catalog = client.load_catalog("sales")+ models = catalog.as_semantic_model_catalog()ident = NameIdentifier.of("mart", "sales_model")# Run the Python operation examples here.@@ -298,6 +302,90 @@ identifiers = models.list_semantic_models(Namespace.of("mart"))REST identifiers include the namespace `["example", "sales", "mart"]`. SDK identifiers are relativeto the loaded catalog, such as `mart.sales_model`.+### Find Semantic Model Datasets by Source++A table or View can list its directly associated datasets across catalogs and schemas in the same+metalake. The caller needs access to the source metadata. Results include only datasets from models+the caller can load, with the same catalog and schema access requirements as loading those models.++<Tabs groupId='language' queryString>+<TabItem value="shell" label="REST">++```shell+curl -X GET -H "Accept: application/vnd.gravitino.v1+json" \+ http://localhost:8090/api/metalakes/example/objects/table/sales.mart.orders/semantic-model-datasets+```++Use `view` instead of `table` for a View, and URL-encode the source's `catalog.schema.name` path+component when needed. Other source types are rejected.++</TabItem>+<TabItem value="java" label="Java">++```java+Table source = catalog.asTableCatalog().loadTable(NameIdentifier.of("mart", "orders"));+NameIdentifier[] datasets = source.supportsSemanticModels().listSemanticModelDatasets();+// A View returned by catalog.asViewCatalog().loadView(...) exposes the same capability.+```++</TabItem>+<TabItem value="python" label="Python">++```python+source = catalog.as_table_catalog().load_table(NameIdentifier.of("mart", "orders"))+datasets = source.supports_semantic_models().list_semantic_model_datasets()+# A View returned by catalog.as_view_catalog().load_view(...) exposes the same capability.+```++</TabItem>+</Tabs>++All three APIs return fully qualified identifiers, including the metalake and catalog. For example:++```json+{+ "code": 0,+ "identifiers": [+ {"namespace": ["example", "sales", "mart", "sales_model"], "name": "orders"}+ ]+}+```++* Each identifier's namespace is `[metalake, catalog, schema, semanticModel]`; `name` is the exact+ dataset alias in the model. Several datasets in one model can reference the same source and each+ appears separately. Preserve these components: a dataset name such as `orders.raw` is one name.+* Results are unique and sorted by namespace components, then dataset name, comparing each component+ case-sensitively by UTF-16 code units. Clients preserve that server order. An+ existing source with no visible matches returns an empty array. Missing sources and failed+ queries return errors.+* To list models only, derive model identifiers from the dataset namespaces and remove duplicates.+ In Java, use `NameIdentifier.of(dataset.namespace().levels())`; in Python, use+ `NameIdentifier.of(*dataset.namespace().levels())`. Select each result's catalog before loading+ its model through the catalog-scoped API.++Associations are stored atomically with a model definition. Creating or importing a model, and+explicitly replacing its definition, binds each dataset to the registered source ID resolved during+source validation. A replacement refreshes the binding even if the definition text is unchanged.+Model rename, comment, and property updates preserve existing bindings.++The lookup has these limits:++* **Source names can drift.** Renaming a source while preserving its registered ID retains the+ association, but does not rewrite `Dataset.source`. Inspect and explicitly replace affected model+ definitions when repairing references; a match does not prove that a model can execute.+* **Source name reuse does not transfer associations.** Dropping and recreating a source gives it a+ different ID. The new source has no inherited matches. Explicitly replace a model's definition+ to validate and bind it to the new source, if that is the intended reference.+* **Only current direct associations are indexed.** View dependencies are not followed, and old+ model snapshots do not retain historical associations. Models written before this feature have+ no indexed bindings until an authorized definition replacement; there is no automatic backfill.+* **Source addressing uses the existing object API format.** Literal dots in source namespace+ components have the same ambiguity as other metadata-object relationship routes. Dataset names+ in the response do not have that restriction.++For MCP usage, see the+[`list_semantic_model_datasets` tool](./gravitino-mcp-server.md#semantic-models).+### Load a Semantic ModelLoad returns the stored definition, properties, comment, and audit information.@@ -730,7 +818,8 @@ An authorized request for an absent model returns `false` (`dropped: false` in RThe [Gravitino MCP server](./gravitino-mcp-server.md#semantic-models) provides`list_of_semantic_models`, `load_semantic_model`, `create_semantic_model`, `alter_semantic_model`,-`drop_semantic_model`, `list_metrics`, and `list_metric_infos`. Enable the `semantic_model` tool tag-when filtering tools. Metric discovery tools return the same full namespaces as REST.+`drop_semantic_model`, `list_metrics`, `list_metric_infos`, and `list_semantic_model_datasets`.+Enable the `semantic_model` tool tag when filtering tools. Metric discovery tools return the same+full namespaces as REST.Create and alter use the native REST definition format. Use REST or the SDKs for Ossie import andexport. The current Web UI does not provide Semantic Model workflows.