World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15248] feat: Expose Semantic Model revision APIs and guard updates (#15252)
mchades60d372f8b452
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.javaindex ceaf23ad57..f2ef980edb 100644--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java@@ -32,6 +32,9 @@ import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;@Evolvingpublic interface SemanticModelCatalog {+ /** Alias of the newest saved revision. */+ String LATEST_REVISION = "latest";+/*** Lists the Semantic Models in a schema namespace.*@@ -81,6 +84,38 @@ public interface SemanticModelCatalog {*/SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException;+ /**+ * Loads a retained revision by number.+ *+ * @param ident The Semantic Model identifier.+ * @param revision The positive revision number.+ * @return The requested snapshot.+ */+ default SemanticModel loadSemanticModel(NameIdentifier ident, int revision) {+ throw new UnsupportedOperationException("Loading Semantic Model revisions is not supported");+ }++ /**+ * Loads the latest saved revision.+ *+ * @param ident The Semantic Model identifier.+ * @param alias The alias {@link #LATEST_REVISION}.+ * @return The latest snapshot.+ */+ default SemanticModel loadSemanticModel(NameIdentifier ident, String alias) {+ throw new UnsupportedOperationException("Loading Semantic Model revisions is not supported");+ }++ /**+ * Lists the retained revision summaries visible to the caller, newest first.+ *+ * @param ident The Semantic Model identifier.+ * @return The revision summaries.+ */+ default SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ throw new UnsupportedOperationException("Listing Semantic Model revisions is not supported");+ }+/*** Returns whether a Semantic Model exists.*@@ -165,6 +200,32 @@ public interface SemanticModelCatalog {throw new UnsupportedOperationException("Ossie export is not supported");}+ /**+ * Exports a retained revision.+ *+ * @param ident The Semantic Model identifier.+ * @param revision The positive revision number.+ * @param format The requested document format.+ * @return The Ossie document for that revision.+ */+ default OssieDocument exportOssieDocument(+ NameIdentifier ident, int revision, OssieFormat format) {+ throw new UnsupportedOperationException("Exporting Semantic Model revisions is not supported");+ }++ /**+ * Exports the latest saved revision.+ *+ * @param ident The Semantic Model identifier.+ * @param alias The alias {@link #LATEST_REVISION}.+ * @param format The requested document format.+ * @return The Ossie document for the latest revision.+ */+ default OssieDocument exportOssieDocument(+ NameIdentifier ident, String alias, OssieFormat format) {+ throw new UnsupportedOperationException("Exporting Semantic Model revisions is not supported");+ }+/*** Applies changes atomically to a Semantic Model.*@@ -182,6 +243,20 @@ public interface SemanticModelCatalog {throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException;+ /**+ * Alters a Semantic Model only if the expected revision is still the latest saved revision.+ *+ * @param ident The Semantic Model identifier.+ * @param expectedRevision The positive revision number from which the changes were prepared.+ * @param changes The changes to apply.+ * @return The resulting snapshot.+ */+ default SemanticModel alterSemanticModel(+ NameIdentifier ident, int expectedRevision, SemanticModelChange... changes) {+ throw new UnsupportedOperationException(+ "Conditional Semantic Model alteration is not supported");+ }+/*** Drops a Semantic Model.*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 348fb6a38d..2366e8d8fe 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,7 @@ 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.SemanticModelCatalog;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.junit.jupiter.api.AfterAll;@@ -185,8 +186,9 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {}).build();NameIdentifier model = NameIdentifier.of(schemaName, "source_lookup_model");+ SemanticModelCatalog models = catalog.asSemanticModelCatalog();try {- catalog.asSemanticModelCatalog().createSemanticModel(model, null, definition, Map.of());+ int revision = models.createSemanticModel(model, null, definition, Map.of()).revision();Assertions.assertArrayEquals(new NameIdentifier[] {NameIdentifier.of(metalakeName, catalogName, schemaName, model.name(), "managed.alias")@@ -196,9 +198,7 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {.loadTable(source).supportsSemanticModels().listSemanticModelDatasets());- catalog- .asSemanticModelCatalog()- .alterSemanticModel(model, SemanticModelChange.replaceDefinition(definition));+ models.alterSemanticModel(model, revision, SemanticModelChange.replaceDefinition(definition));Assertions.assertEquals(1,catalog@@ -208,7 +208,7 @@ public class CatalogGenericCatalogLanceIT extends BaseIT {.listSemanticModelDatasets().length);} finally {- catalog.asSemanticModelCatalog().dropSemanticModel(model);+ models.dropSemanticModel(model);}}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.javaindex 781e07427e..f136686b36 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java@@ -68,6 +68,7 @@ import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.NoSuchRoleException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelRevisionException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.NoSuchTagException;import org.apache.gravitino.exceptions.NoSuchTopicException;@@ -1594,6 +1595,11 @@ public class ErrorHandlers {.equals(errorResponse.getType())) {throw new NoSuchSemanticModelException(errorMessage);}+ if (NoSuchSemanticModelRevisionException.class+ .getSimpleName()+ .equals(errorResponse.getType())) {+ throw new NoSuchSemanticModelRevisionException(errorMessage);+ }throw new NotFoundException(errorMessage);case ErrorConstants.ALREADY_EXISTS_CODE:diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.javaindex c822f38950..5c29e29fb1 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java@@ -80,6 +80,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.SemanticModelRevision;/*** Relational catalog is a catalog implementation that supports relational database like metadata@@ -150,6 +151,24 @@ class RelationalCatalog extends BaseSchemaCatalogreturn semanticModelOperations.loadSemanticModel(ident);}+ /** {@inheritDoc} */+ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident, int revision) {+ return semanticModelOperations.loadSemanticModel(ident, revision);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident, String alias) {+ return semanticModelOperations.loadSemanticModel(ident, alias);+ }++ /** {@inheritDoc} */+ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ return semanticModelOperations.listSemanticModelRevisions(ident);+ }+/** {@inheritDoc} */@Overridepublic SemanticModel createSemanticModel(@@ -172,12 +191,31 @@ class RelationalCatalog extends BaseSchemaCatalogreturn semanticModelOperations.exportOssieDocument(ident, format);}+ /** {@inheritDoc} */+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, int revision, OssieFormat format) {+ return semanticModelOperations.exportOssieDocument(ident, revision, format);+ }++ /** {@inheritDoc} */+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, String alias, OssieFormat format) {+ return semanticModelOperations.exportOssieDocument(ident, alias, format);+ }+/** {@inheritDoc} */@Overridepublic SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes) {return semanticModelOperations.alterSemanticModel(ident, changes);}+ /** {@inheritDoc} */+ @Override+ public SemanticModel alterSemanticModel(+ NameIdentifier ident, int expectedRevision, SemanticModelChange... changes) {+ return semanticModelOperations.alterSemanticModel(ident, expectedRevision, changes);+ }+/** {@inheritDoc} */@Overridepublic boolean dropSemanticModel(NameIdentifier ident) {diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.java b/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.javaindex cef17d9743..23f1485dd8 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/SemanticModelCatalogOperations.java@@ -36,6 +36,7 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.MetricInfoListResponse;import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.responses.SemanticModelRevisionListResponse;import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.exceptions.IllegalSemanticModelException;import org.apache.gravitino.exceptions.NoSuchSchemaException;@@ -49,6 +50,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.SemanticModelRevision;import org.apache.hc.core5.http.HttpHeaders;/** Implements schema-scoped Semantic Model operations through the Gravitino REST API. */@@ -127,20 +129,31 @@ class SemanticModelCatalogOperations implements SemanticModelCatalog {/** {@inheritDoc} */@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {- checkSemanticModelNameIdentifier(ident);+ return load(ident, "");+ }+ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident, int revision) {+ return load(ident, revisionPath(revision));+ }++ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident, String alias) {+ return load(ident, revisionPath(alias));+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ checkSemanticModelNameIdentifier(ident);Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());- SemanticModelResponse response =+ SemanticModelRevisionListResponse response =restClient.get(- formatSemanticModelRequestPath(fullNamespace)- + "/"- + RESTUtils.encodeString(ident.name()),- SemanticModelResponse.class,+ modelPath(fullNamespace, ident) + "/revisions",+ SemanticModelRevisionListResponse.class,Collections.emptyMap(),ErrorHandlers.semanticModelErrorHandler());response.validate();-- return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ return response.revisions();}/** {@inheritDoc} */@@ -202,21 +215,17 @@ class SemanticModelCatalogOperations implements SemanticModelCatalog {@Overridepublic OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format)throws NoSuchSemanticModelException, IllegalSemanticModelException {- checkSemanticModelNameIdentifier(ident);- Preconditions.checkArgument(format != null, "Ossie format must not be null");+ return export(ident, "", format);+ }- Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());- String content =- restClient.getRaw(- formatSemanticModelRequestPath(fullNamespace)- + "/"- + RESTUtils.encodeString(ident.name())- + "/ossie",- Collections.singletonMap("format", format.name().toLowerCase(Locale.ROOT)),- Collections.singletonMap(HttpHeaders.ACCEPT, ossieMediaType(format)),- ErrorHandlers.semanticModelErrorHandler());+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, int revision, OssieFormat format) {+ return export(ident, revisionPath(revision), format);+ }- return format == OssieFormat.JSON ? OssieDocument.json(content) : OssieDocument.yaml(content);+ @Override+ public OssieDocument exportOssieDocument(NameIdentifier ident, String alias, OssieFormat format) {+ return export(ident, revisionPath(alias), format);}/** {@inheritDoc} */@@ -224,29 +233,13 @@ class SemanticModelCatalogOperations implements SemanticModelCatalog {public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {- checkSemanticModelNameIdentifier(ident);- Preconditions.checkArgument(changes != null, "Semantic Model changes must not be null");-- List<SemanticModelUpdateRequest> updates =- Arrays.stream(changes)- .map(DTOConverters::toSemanticModelUpdateRequest)- .collect(Collectors.toList());- SemanticModelUpdatesRequest request = new SemanticModelUpdatesRequest(updates);- request.validate();-- Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());- SemanticModelResponse response =- restClient.put(- formatSemanticModelRequestPath(fullNamespace)- + "/"- + RESTUtils.encodeString(ident.name()),- request,- SemanticModelResponse.class,- Collections.emptyMap(),- ErrorHandlers.semanticModelErrorHandler());- response.validate();+ return alter(ident, null, changes);+ }- return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ @Override+ public SemanticModel alterSemanticModel(+ NameIdentifier ident, int expectedRevision, SemanticModelChange... changes) {+ return alter(ident, expectedRevision, changes);}/** {@inheritDoc} */@@ -257,9 +250,7 @@ class SemanticModelCatalogOperations implements SemanticModelCatalog {Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());DropResponse response =restClient.delete(- formatSemanticModelRequestPath(fullNamespace)- + "/"- + RESTUtils.encodeString(ident.name()),+ modelPath(fullNamespace, ident),DropResponse.class,Collections.emptyMap(),ErrorHandlers.semanticModelErrorHandler());@@ -295,10 +286,81 @@ class SemanticModelCatalogOperations implements SemanticModelCatalog {checkSemanticModelNamespace(ident.namespace());}+ private SemanticModel load(NameIdentifier ident, String suffix) {+ checkSemanticModelNameIdentifier(ident);++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ SemanticModelResponse response =+ restClient.get(+ modelPath(fullNamespace, ident) + suffix,+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }++ private OssieDocument export(NameIdentifier ident, String suffix, OssieFormat format) {+ checkSemanticModelNameIdentifier(ident);+ Preconditions.checkArgument(format != null, "Ossie format must not be null");++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ String content =+ restClient.getRaw(+ modelPath(fullNamespace, ident) + suffix + "/ossie",+ Collections.singletonMap("format", format.name().toLowerCase(Locale.ROOT)),+ Collections.singletonMap(HttpHeaders.ACCEPT, ossieMediaType(format)),+ ErrorHandlers.semanticModelErrorHandler());++ return format == OssieFormat.JSON ? OssieDocument.json(content) : OssieDocument.yaml(content);+ }++ private SemanticModel alter(+ NameIdentifier ident, @Nullable Integer expectedRevision, SemanticModelChange... changes) {+ checkSemanticModelNameIdentifier(ident);+ Preconditions.checkArgument(changes != null, "Semantic Model changes must not be null");++ List<SemanticModelUpdateRequest> updates =+ Arrays.stream(changes)+ .map(DTOConverters::toSemanticModelUpdateRequest)+ .collect(Collectors.toList());+ SemanticModelUpdatesRequest request =+ new SemanticModelUpdatesRequest(updates, expectedRevision);+ request.validate();++ Namespace fullNamespace = getSemanticModelFullNamespace(ident.namespace());+ SemanticModelResponse response =+ restClient.put(+ modelPath(fullNamespace, ident),+ request,+ SemanticModelResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.semanticModelErrorHandler());+ response.validate();++ return new GenericSemanticModel(response.getSemanticModel(), restClient, fullNamespace);+ }+private Namespace getSemanticModelFullNamespace(Namespace semanticModelNamespace) {return Namespace.of(catalogNamespace.level(0), catalogName, semanticModelNamespace.level(0));}+ private static String modelPath(Namespace namespace, NameIdentifier ident) {+ return formatSemanticModelRequestPath(namespace) + "/" + RESTUtils.encodeString(ident.name());+ }++ private static String revisionPath(int revision) {+ Preconditions.checkArgument(revision > 0, "Revision must be positive");+ return "/revisions/" + revision;+ }++ private static String revisionPath(String alias) {+ Preconditions.checkArgument(+ LATEST_REVISION.equals(alias), "Unsupported revision alias: %s", alias);+ return "/revisions/" + LATEST_REVISION;+ }+private static String formatMetricRequestPath(Namespace namespace) {return BaseSchemaCatalog.formatSchemaRequestPath(Namespace.of(namespace.level(0), namespace.level(1)))diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.javaindex 7388589260..4496cc3433 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSemanticModelCatalog.java@@ -57,10 +57,12 @@ import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.MetricInfoListResponse;import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.responses.SemanticModelRevisionListResponse;import org.apache.gravitino.dto.semantic.MetricDTO;import org.apache.gravitino.dto.semantic.SemanticModelDTO;import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.dto.semantic.SemanticModelMetricDTO;+import org.apache.gravitino.dto.semantic.SemanticModelRevisionDTO;import org.apache.gravitino.exceptions.AlreadyExistsException;import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.ConnectionFailedException;@@ -71,6 +73,7 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelRevisionException;import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.exceptions.NotInUseException;import org.apache.gravitino.exceptions.OptimisticLockException;@@ -95,6 +98,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.SemanticModelRevision;import org.apache.hc.core5.http.HttpHeaders;import org.apache.hc.core5.http.Method;import org.junit.jupiter.api.BeforeAll;@@ -417,19 +421,72 @@ public class TestSemanticModelCatalog extends TestBase {OssieDocument.json(json), semanticModels.exportOssieDocument(ident, OssieFormat.JSON));}+ @Test+ void testRevisionReadsAndMissingRevisionMapping() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, MODEL_NAME);+ String entityPath = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));+ SemanticModelDTO source = semanticModelDTO(MODEL_NAME);+ Instant publishedAt = Instant.parse("2026-01-02T00:00:00Z");+ SemanticModelRevisionDTO summary =+ new SemanticModelRevisionDTO(+ 2, SemanticModel.Status.PUBLISHED, "reviewer", publishedAt, source.auditInfo());+ SemanticModelDTO snapshot =+ SemanticModelDTO.builder()+ .withName(source.name())+ .withDefinition(SemanticModelDefinitionDTO.fromDefinition(source.definition()))+ .withAudit(source.auditInfo())+ .withRevision(summary)+ .build();++ buildMockResource(+ Method.GET,+ entityPath + "/revisions",+ null,+ new SemanticModelRevisionListResponse(new SemanticModelRevisionDTO[] {summary}),+ SC_OK);+ buildMockResource(+ Method.GET, entityPath + "/revisions/2", null, new SemanticModelResponse(snapshot), SC_OK);+ buildMockResource(+ Method.GET,+ entityPath + "/revisions/latest",+ null,+ new SemanticModelResponse(snapshot),+ SC_OK);+ buildMockResource(+ Method.GET,+ entityPath + "/revisions/9",+ null,+ ErrorResponse.notFound(+ NoSuchSemanticModelRevisionException.class.getSimpleName(), "No revision 9"),+ SC_NOT_FOUND);++ SemanticModelCatalog models = catalog.asSemanticModelCatalog();+ SemanticModelRevision[] history = models.listSemanticModelRevisions(ident);+ assertArrayEquals(new SemanticModelRevision[] {summary}, history);+ SemanticModel numbered = models.loadSemanticModel(ident, 2);+ assertEquals(2, numbered.revision());+ assertEquals("reviewer", numbered.publishedBy());+ assertEquals(publishedAt, numbered.publishedAt());+ assertEquals(numbered, models.loadSemanticModel(ident, SemanticModelCatalog.LATEST_REVISION));+ assertThrows(+ NoSuchSemanticModelRevisionException.class, () -> models.loadSemanticModel(ident, 9));+ assertThrows(IllegalArgumentException.class, () -> models.loadSemanticModel(ident, 0));+ assertThrows(IllegalArgumentException.class, () -> models.loadSemanticModel(ident, "active"));+ }+@Testpublic void testAlterSemanticModelConvertsAllChangeTypes() throws JsonProcessingException {SemanticModelDefinition replacement = definition();SemanticModelUpdatesRequest request =new SemanticModelUpdatesRequest(List.of(- new SemanticModelUpdateRequest.RenameSemanticModelRequest("renamed_model"),new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest(""),new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "analytics"),new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("deprecated"),new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(- SemanticModelDefinitionDTO.fromDefinition(replacement))));+ SemanticModelDefinitionDTO.fromDefinition(replacement))),+ 1);SemanticModelDTO responseDTO = semanticModelDTO("renamed_model");String path = withSlash(semanticModelPath() + "/" + RESTUtils.encodeString(MODEL_NAME));buildMockResource(Method.PUT, path, request, new SemanticModelResponse(responseDTO), SC_OK);@@ -439,7 +496,7 @@ public class TestSemanticModelCatalog extends TestBase {.asSemanticModelCatalog().alterSemanticModel(NameIdentifier.of(SCHEMA_NAME, MODEL_NAME),- SemanticModelChange.rename("renamed_model"),+ 1,SemanticModelChange.updateComment(""),SemanticModelChange.setProperty("owner", "analytics"),SemanticModelChange.removeProperty("deprecated"),@@ -447,15 +504,14 @@ public class TestSemanticModelCatalog extends TestBase {JsonNode serializedUpdates = MAPPER.valueToTree(request).path("updates");assertEquals(- List.of("rename", "updateComment", "setProperty", "removeProperty", "replaceDefinition"),+ List.of("updateComment", "setProperty", "removeProperty", "replaceDefinition"),Arrays.asList(serializedUpdates.get(0).path("@type").asText(),serializedUpdates.get(1).path("@type").asText(),serializedUpdates.get(2).path("@type").asText(),- serializedUpdates.get(3).path("@type").asText(),- serializedUpdates.get(4).path("@type").asText()));- assertEquals("", serializedUpdates.get(1).path("newComment").asText());- assertTrue(serializedUpdates.get(4).path("definition").has("datasets"));+ serializedUpdates.get(3).path("@type").asText()));+ assertEquals("", serializedUpdates.get(0).path("newComment").asText());+ assertTrue(serializedUpdates.get(3).path("definition").has("datasets"));assertSemanticModel(responseDTO, altered);}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 3b19444f06..9210e77f3e 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@@ -95,6 +95,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.SemanticModelRevision;import org.apache.gravitino.semantic.SupportsSemanticModels;import org.apache.gravitino.tag.SupportsTags;import org.apache.gravitino.tag.Tag;@@ -231,16 +232,18 @@ public class SemanticModelIT extends BaseIT {source.name(),semanticModelCatalog.loadSemanticModel(model).definition().datasets()[0].source().name());semanticModelCatalog.alterSemanticModel(- model,- SemanticModelChange.rename(renamedModel.name()),- SemanticModelChange.updateComment("source name drift is preserved"));+ model, SemanticModelChange.rename(renamedModel.name()));+ semanticModelCatalog.alterSemanticModel(+ renamedModel, 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));+ renamedModel,+ semanticModelCatalog.loadSemanticModel(renamedModel).revision(),+ SemanticModelChange.replaceDefinition(replacement));assertArrayEquals(sourceDatasetIds(renamedModel.name(), "orders"), lookup.listSemanticModelDatasets());assertThrows(@@ -248,6 +251,7 @@ public class SemanticModelIT extends BaseIT {() ->semanticModelCatalog.alterSemanticModel(renamedModel,+ semanticModelCatalog.loadSemanticModel(renamedModel).revision(),SemanticModelChange.replaceDefinition(sourceDefinition("missing_lookup_source", "invalid"))));assertArrayEquals(@@ -260,7 +264,9 @@ public class SemanticModelIT extends BaseIT {renamedModel, SemanticModelChange.setProperty("reviewed", "true"));assertArrayEquals(new NameIdentifier[0], lookup.listSemanticModelDatasets());semanticModelCatalog.alterSemanticModel(- renamedModel, SemanticModelChange.replaceDefinition(replacement));+ renamedModel,+ semanticModelCatalog.loadSemanticModel(renamedModel).revision(),+ SemanticModelChange.replaceDefinition(replacement));assertArrayEquals(sourceDatasetIds(renamedModel.name(), "orders"), lookup.listSemanticModelDatasets());semanticModelCatalog.dropSemanticModel(renamedModel);@@ -394,14 +400,23 @@ public class SemanticModelIT extends BaseIT {MODEL_NAME, "Governed sales metrics", definition, expectedProperties, loaded);SemanticModelDefinition replacement = replacementDefinition();- SemanticModel altered =+ SemanticModel changed =semanticModelCatalog.alterSemanticModel(modelIdent,- SemanticModelChange.rename(RENAMED_MODEL_NAME),+ loaded.revision(),SemanticModelChange.updateComment(""),SemanticModelChange.setProperty("owner", "analytics"),SemanticModelChange.removeProperty("deprecated"),SemanticModelChange.replaceDefinition(replacement));+ SemanticModel altered =+ semanticModelCatalog.alterSemanticModel(+ modelIdent, changed.revision(), SemanticModelChange.rename(RENAMED_MODEL_NAME));+ assertEquals(2, altered.revision());+ assertEquals(+ 1,+ semanticModelCatalog+ .loadSemanticModel(NameIdentifier.of(SCHEMA_NAME, RENAMED_MODEL_NAME), 1)+ .revision());Map<String, String> alteredProperties =Map.of("certified", "true", "owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);assertSemanticModel(RENAMED_MODEL_NAME, "", replacement, alteredProperties, altered);@@ -417,6 +432,16 @@ public class SemanticModelIT extends BaseIT {NameIdentifier renamedIdent = NameIdentifier.of(SCHEMA_NAME, RENAMED_MODEL_NAME);SemanticModel reloaded = semanticModelCatalog.loadSemanticModel(renamedIdent);assertSemanticModel(RENAMED_MODEL_NAME, "", replacement, alteredProperties, reloaded);+ assertEquals(+ 2,+ semanticModelCatalog+ .loadSemanticModel(renamedIdent, SemanticModelCatalog.LATEST_REVISION)+ .revision());+ SemanticModelRevision[] history = semanticModelCatalog.listSemanticModelRevisions(renamedIdent);+ assertArrayEquals(+ new int[] {2, 1},+ Arrays.stream(history).mapToInt(SemanticModelRevision::revision).toArray());+ assertEquals(SemanticModel.Status.PUBLISHED, history[0].status());assertTrue(semanticModelCatalog.dropSemanticModel(renamedIdent));assertFalse(semanticModelCatalog.dropSemanticModel(renamedIdent));@@ -475,7 +500,9 @@ public class SemanticModelIT extends BaseIT {Metric added =Metric.builder().withName("收入.total").withExpression(original.expression()).build();semanticModelCatalog.alterSemanticModel(- model, SemanticModelChange.replaceDefinition(metricDefinition(replacement, added)));+ model,+ semanticModelCatalog.loadSemanticModel(model).revision(),+ SemanticModelChange.replaceDefinition(metricDefinition(replacement, added)));assertMetricDiscovery(new NameIdentifier[] {NameIdentifier.of(SCHEMA_NAME, MODEL_NAME, replacement.name()),@@ -493,7 +520,9 @@ public class SemanticModelIT extends BaseIT {replacement,added);semanticModelCatalog.alterSemanticModel(- renamed, SemanticModelChange.replaceDefinition(metricDefinition(added)));+ renamed,+ semanticModelCatalog.loadSemanticModel(renamed).revision(),+ SemanticModelChange.replaceDefinition(metricDefinition(added)));assertMetricDiscovery(new NameIdentifier[] {NameIdentifier.of(SCHEMA_NAME, RENAMED_MODEL_NAME, added.name())},added);@@ -599,6 +628,7 @@ public class SemanticModelIT extends BaseIT {() ->semanticModelCatalog.alterSemanticModel(ident,+ created.revision(),SemanticModelChange.updateComment("Must not be persisted"),SemanticModelChange.setProperty("owner", "another-team"),SemanticModelChange.replaceDefinition(definition),@@ -880,6 +910,7 @@ public class SemanticModelIT extends BaseIT {() ->semanticModelCatalog.alterSemanticModel(ident,+ original.revision(),SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.setProperty("owner", "another-team"),SemanticModelChange.replaceDefinition(reserved)));@@ -914,6 +945,7 @@ public class SemanticModelIT extends BaseIT {() ->semanticModelCatalog.alterSemanticModel(ident,+ original.revision(),SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, " ")));assertSemanticModel(diff --git a/clients/client-python/gravitino/api/semantic/semantic_model.py b/clients/client-python/gravitino/api/semantic/semantic_model.pyindex 51c3458f23..d918367b7a 100644--- a/clients/client-python/gravitino/api/semantic/semantic_model.py+++ b/clients/client-python/gravitino/api/semantic/semantic_model.py@@ -18,15 +18,15 @@from abc import abstractmethodfrom typing import Optional-from gravitino.api.auditable import Auditablefrom gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition+from gravitino.api.semantic.semantic_model_revision import SemanticModelRevisionfrom gravitino.api.domain.supports_domains import SupportsDomainsfrom gravitino.api.policy.supports_policies import SupportsPoliciesfrom gravitino.api.tag.supports_tags import SupportsTagsfrom gravitino.exceptions.base import UnsupportedOperationException-class SemanticModel(Auditable):+class SemanticModel(SemanticModelRevision):"""A schema-scoped analytical semantic model compatible with Apache Ossie Core.A Semantic Model is always managed by Gravitino and is never persisted in andiff --git a/clients/client-python/gravitino/api/semantic/semantic_model_catalog.py b/clients/client-python/gravitino/api/semantic/semantic_model_catalog.pyindex 9c0c809493..bc8cccb6c1 100644--- a/clients/client-python/gravitino/api/semantic/semantic_model_catalog.py+++ b/clients/client-python/gravitino/api/semantic/semantic_model_catalog.py@@ -22,6 +22,7 @@ from gravitino.api.semantic.semantic_model import SemanticModelfrom gravitino.api.semantic.semantic_model_change import SemanticModelChangefrom gravitino.api.semantic.semantic_model_definition import SemanticModelDefinitionfrom gravitino.api.semantic.semantic_model_metric import SemanticModelMetric+from gravitino.api.semantic.semantic_model_revision import SemanticModelRevisionfrom gravitino.exceptions.base import (NoSuchSemanticModelException,UnsupportedOperationException,@@ -39,6 +40,8 @@ class SemanticModelCatalog(ABC):capability."""+ LATEST_REVISION = "latest"+@abstractmethoddef list_semantic_models(self, namespace: Namespace) -> list[NameIdentifier]:"""List the Semantic Models in a namespace from the catalog.@@ -96,11 +99,14 @@ class SemanticModelCatalog(ABC):raise UnsupportedOperationException("Metric info listing is not supported")@abstractmethod- def load_semantic_model(self, identifier: NameIdentifier) -> SemanticModel:- """Load Semantic Model metadata by `NameIdentifier` from the catalog.+ def load_semantic_model(+ self, identifier: NameIdentifier, revision: Optional[int | str] = None+ ) -> SemanticModel:+ """Load the active revision, a positive revision number, or "latest".Args:identifier (NameIdentifier): A Semantic Model identifier.+ revision: A positive revision number or "latest"; None selects active.Returns:SemanticModel: The Semantic Model metadata.@@ -109,6 +115,12 @@ class SemanticModelCatalog(ABC):NoSuchSemanticModelException: If the Semantic Model does not exist."""+ def list_semantic_model_revisions(+ self, identifier: NameIdentifier+ ) -> list[SemanticModelRevision]:+ """List visible, retained revision summaries newest first."""+ raise UnsupportedOperationException("Semantic Model history is not supported")+def semantic_model_exists(self, identifier: NameIdentifier) -> bool:"""Check if a Semantic Model with the given name exists in the catalog.@@ -185,7 +197,10 @@ class SemanticModelCatalog(ABC):raise UnsupportedOperationException("Ossie import is not supported")def export_ossie_document(- self, identifier: NameIdentifier, document_format: str = "yaml"+ self,+ identifier: NameIdentifier,+ document_format: str = "yaml",+ revision: Optional[int | str] = None,) -> str:"""Export a Semantic Model as standalone Apache Ossie document text.@@ -196,6 +211,7 @@ class SemanticModelCatalog(ABC):Args:identifier (NameIdentifier): The Semantic Model identifier.document_format (str): ``"yaml"`` (default) or ``"json"``.+ revision: A positive revision number or "latest"; None selects active.Returns:str: The serialized document in the requested format.@@ -210,15 +226,21 @@ class SemanticModelCatalog(ABC):@abstractmethoddef alter_semantic_model(- self, identifier: NameIdentifier, *changes: SemanticModelChange+ self,+ identifier: NameIdentifier,+ *changes: SemanticModelChange,+ expected_revision: Optional[int] = None,) -> SemanticModel:"""Alter a Semantic Model in the catalog.- All changes are applied atomically to the current Semantic Model.+ All changes are applied atomically to the latest saved revision.+ Rename must be the only change when requested.Args:identifier (NameIdentifier): A Semantic Model identifier.*changes: The Semantic Model changes to apply.+ expected_revision: The latest revision on which the changes are based.+ Required when replacing the definition.Returns:SemanticModel: The updated Semantic Model metadata.diff --git a/clients/client-python/gravitino/api/semantic/semantic_model_revision.py b/clients/client-python/gravitino/api/semantic/semantic_model_revision.pynew file mode 100644index 0000000000..a6f547e8d5--- /dev/null+++ b/clients/client-python/gravitino/api/semantic/semantic_model_revision.py@@ -0,0 +1,49 @@+# 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.++from datetime import datetime+from enum import Enum+from typing import Optional++from gravitino.api.auditable import Auditable+++class SemanticModelStatus(str, Enum):+ """The public publication status of a revision."""++ DRAFT = "DRAFT"+ PUBLISHED = "PUBLISHED"+++class SemanticModelRevision(Auditable):+ """Revision metadata, with audit information describing the writer."""++ def revision(self) -> int:+ """Returns the revision number, or zero if the server omitted it."""+ return 0++ def status(self) -> Optional[SemanticModelStatus]:+ """Returns the publication status when supplied by the server."""+ return None++ def published_by(self) -> Optional[str]:+ """Returns the publisher, or None for a draft."""+ return None++ def published_at(self) -> Optional[datetime]:+ """Returns the publication time, or None for a draft."""+ return Nonediff --git a/clients/client-python/gravitino/client/generic_semantic_model.py b/clients/client-python/gravitino/client/generic_semantic_model.pyindex 5a577d8516..196f3b7836 100644--- a/clients/client-python/gravitino/client/generic_semantic_model.py+++ b/clients/client-python/gravitino/client/generic_semantic_model.py@@ -15,6 +15,7 @@# specific language governing permissions and limitations# under the License.+from datetime import datetimefrom typing import Optionalfrom gravitino.api.audit import Audit@@ -25,6 +26,7 @@ from gravitino.api.policy.policy_list import PolicyListfrom gravitino.api.policy.supports_policies import SupportsPoliciesfrom gravitino.api.semantic.semantic_model import SemanticModelfrom gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition+from gravitino.api.semantic.semantic_model_revision import SemanticModelStatusfrom gravitino.api.domain.domain import Domainfrom gravitino.api.domain.supports_domains import SupportsDomainsfrom gravitino.client.metadata_object_domain_operations import (@@ -65,6 +67,10 @@ class GenericSemanticModel(self._definition = semantic_model_dto.definition()self._properties = dict(semantic_model_dto.properties())self._audit = semantic_model_dto.audit_info()+ self._revision = semantic_model_dto.revision()+ self._status = semantic_model_dto.status()+ self._published_by = semantic_model_dto.published_by()+ self._published_at = semantic_model_dto.published_at()model_object = MetadataObjects.of([semantic_model_ns.level(1), semantic_model_ns.level(2), self._name],MetadataObject.Type.SEMANTIC_MODEL,@@ -94,6 +100,18 @@ class GenericSemanticModel(def audit_info(self) -> Audit:return self._audit+ def revision(self) -> int:+ return self._revision++ def status(self) -> Optional[SemanticModelStatus]:+ return self._status++ def published_by(self) -> Optional[str]:+ return self._published_by++ def published_at(self) -> Optional[datetime]:+ return self._published_at+def __eq__(self, other: object) -> bool:if not isinstance(other, GenericSemanticModel):return False@@ -103,10 +121,16 @@ class GenericSemanticModel(and self._definition == other.definition()and self._properties == other.properties()and self._audit == other.audit_info()+ and self._revision == other.revision()+ and self._status == other.status()+ and self._published_by == other.published_by()+ and self._published_at == other.published_at())def __hash__(self) -> int:- return hash((self._name, self._comment, self._definition))+ return hash(+ (self._name, self._comment, self._definition, self._revision, self._status)+ )def __repr__(self) -> str:return (diff --git a/clients/client-python/gravitino/client/semantic_model_catalog_operations.py b/clients/client-python/gravitino/client/semantic_model_catalog_operations.pyindex f0e41ce709..633fe7fc27 100644--- a/clients/client-python/gravitino/client/semantic_model_catalog_operations.py+++ b/clients/client-python/gravitino/client/semantic_model_catalog_operations.py@@ -29,6 +29,7 @@ from gravitino.api.semantic.semantic_model_change import ()from gravitino.api.semantic.semantic_model_definition import SemanticModelDefinitionfrom gravitino.api.semantic.semantic_model_metric import SemanticModelMetric+from gravitino.api.semantic.semantic_model_revision import SemanticModelRevisionfrom gravitino.client.generic_semantic_model import GenericSemanticModelfrom gravitino.dto.requests.semantic_model_create_request import (SemanticModelCreateRequest,@@ -44,6 +45,9 @@ from gravitino.dto.responses.drop_response import DropResponsefrom gravitino.dto.responses.entity_list_response import EntityListResponsefrom gravitino.dto.responses.metric_info_list_response import MetricInfoListResponsefrom gravitino.dto.responses.semantic_model_response import SemanticModelResponse+from gravitino.dto.responses.semantic_model_revision_list_response import (+ SemanticModelRevisionListResponse,+)from gravitino.dto.semantic.semantic_model_definition_dto import (SemanticModelDefinitionDTO,)@@ -124,16 +128,34 @@ class SemanticModelCatalogOperations(SemanticModelCatalog):for info in response.metrics()]- def load_semantic_model(self, identifier: NameIdentifier) -> SemanticModel:+ def load_semantic_model(+ self, identifier: NameIdentifier, revision: Optional[int | str] = None+ ) -> SemanticModel:self._check_semantic_model_name_identifier(identifier)full_namespace = self._get_semantic_model_full_namespace(identifier.namespace())resp = self._rest_client.get(f"{self._format_semantic_model_request_path(full_namespace)}"- f"/{encode_string(identifier.name())}",+ f"/{encode_string(identifier.name())}{self._revision_path(revision)}",error_handler=SEMANTIC_MODEL_ERROR_HANDLER,)return self._to_semantic_model(resp, full_namespace)+ def list_semantic_model_revisions(+ self, identifier: NameIdentifier+ ) -> list[SemanticModelRevision]:+ self._check_semantic_model_name_identifier(identifier)+ full_namespace = self._get_semantic_model_full_namespace(identifier.namespace())+ resp = self._rest_client.get(+ f"{self._format_semantic_model_request_path(full_namespace)}"+ f"/{encode_string(identifier.name())}/revisions",+ error_handler=SEMANTIC_MODEL_ERROR_HANDLER,+ )+ history = SemanticModelRevisionListResponse.from_json(+ resp.body, infer_missing=True+ )+ history.validate()+ return list(history.revisions())+def create_semantic_model(self,identifier: NameIdentifier,@@ -178,14 +200,17 @@ class SemanticModelCatalogOperations(SemanticModelCatalog):return self._to_semantic_model(resp, full_namespace)def export_ossie_document(- self, identifier: NameIdentifier, document_format: str = "yaml"+ self,+ identifier: NameIdentifier,+ document_format: str = "yaml",+ revision: Optional[int | str] = None,) -> str:self._check_semantic_model_name_identifier(identifier)media_type = self._ossie_media_type(document_format)full_namespace = self._get_semantic_model_full_namespace(identifier.namespace())resp = self._rest_client.get(f"{self._format_semantic_model_request_path(full_namespace)}"- f"/{encode_string(identifier.name())}/ossie",+ f"/{encode_string(identifier.name())}{self._revision_path(revision)}/ossie",params={"format": document_format},headers={"Accept": media_type},error_handler=SEMANTIC_MODEL_ERROR_HANDLER,@@ -193,13 +218,17 @@ class SemanticModelCatalogOperations(SemanticModelCatalog):return resp.body.decode("utf-8")def alter_semantic_model(- self, identifier: NameIdentifier, *changes: SemanticModelChange+ self,+ identifier: NameIdentifier,+ *changes: SemanticModelChange,+ expected_revision: Optional[int] = None,) -> SemanticModel:self._check_semantic_model_name_identifier(identifier)updates_request = SemanticModelUpdatesRequest(_updates=[self._to_semantic_model_update_request(change) for change in changes- ]+ ],+ _expected_revision=expected_revision,)updates_request.validate()@@ -224,6 +253,20 @@ class SemanticModelCatalogOperations(SemanticModelCatalog):drop_resp.validate()return drop_resp.dropped()+ @classmethod+ def _revision_path(cls, revision: Optional[int | str]) -> str:+ if revision is None:+ return ""+ if revision == cls.LATEST_REVISION or (+ isinstance(revision, int)+ and not isinstance(revision, bool)+ and revision > 0+ ):+ return f"/revisions/{revision}"+ raise IllegalArgumentException(+ "Revision must be a positive integer or 'latest'"+ )+@staticmethoddef _ossie_media_type(document_format: str) -> str:if document_format not in ("yaml", "json"):diff --git a/clients/client-python/gravitino/dto/requests/semantic_model_updates_request.py b/clients/client-python/gravitino/dto/requests/semantic_model_updates_request.pyindex e1a0124b54..59d1c43216 100644--- a/clients/client-python/gravitino/dto/requests/semantic_model_updates_request.py+++ b/clients/client-python/gravitino/dto/requests/semantic_model_updates_request.py@@ -16,13 +16,16 @@# under the License.from dataclasses import dataclass, field+from typing import Optionalfrom dataclasses_json import configfrom gravitino.dto.requests.semantic_model_update_request import (+ SemanticModelUpdateRequest,SemanticModelUpdateRequestBase,)from gravitino.dto.semantic.json_serdes.semantic_json_mixin import SemanticJsonMixin+from gravitino.dto.semantic.semantic_dto_utils import is_nonefrom gravitino.rest.rest_message import RESTRequestfrom gravitino.utils.precondition import Precondition@@ -35,9 +38,37 @@ class SemanticModelUpdatesRequest(SemanticJsonMixin, RESTRequest):metadata=config(field_name="updates"))+ _expected_revision: Optional[int] = field(+ default=None, metadata=config(field_name="expectedRevision", exclude=is_none)+ )+def validate(self):Precondition.check_argument(self._updates is not None, "updates cannot be null")Precondition.check_argument(len(self._updates) > 0, "updates cannot be empty")+ Precondition.check_argument(+ self._expected_revision is None+ or (+ isinstance(self._expected_revision, int)+ and not isinstance(self._expected_revision, bool)+ and self._expected_revision > 0+ ),+ "expected_revision must be a positive integer",+ )for update in self._updates:Precondition.check_argument(update is not None, "update cannot be null")+ Precondition.check_argument(+ not isinstance(+ update,+ SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest,+ )+ or self._expected_revision is not None,+ "expected_revision is required when replacing the definition",+ )+ Precondition.check_argument(+ not isinstance(+ update, SemanticModelUpdateRequest.RenameSemanticModelRequest+ )+ or len(self._updates) == 1,+ "Rename must be the only Semantic Model change",+ )update.validate()diff --git a/clients/client-python/gravitino/dto/responses/semantic_model_revision_list_response.py b/clients/client-python/gravitino/dto/responses/semantic_model_revision_list_response.pynew file mode 100644index 0000000000..7a7801d6eb--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/semantic_model_revision_list_response.py@@ -0,0 +1,44 @@+# 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.++from dataclasses import dataclass, field++from dataclasses_json import config++from gravitino.dto.responses.base_response import BaseResponse+from gravitino.dto.semantic.json_serdes.semantic_json_mixin import SemanticJsonMixin+from gravitino.dto.semantic.semantic_model_revision_dto import SemanticModelRevisionDTO+from gravitino.utils.precondition import Precondition+++@dataclass+class SemanticModelRevisionListResponse(SemanticJsonMixin, BaseResponse):+ """Response containing visible Semantic Model revision summaries."""++ _revisions: list[SemanticModelRevisionDTO] = field(+ metadata=config(field_name="revisions")+ )++ def revisions(self) -> list[SemanticModelRevisionDTO]:+ """Returns the revision summaries, newest first."""+ return self._revisions++ def validate(self):+ super().validate()+ Precondition.check_argument(+ self._revisions is not None, "revisions must not be null"+ )diff --git a/clients/client-python/gravitino/dto/semantic/semantic_model_dto.py b/clients/client-python/gravitino/dto/semantic/semantic_model_dto.pyindex 28301b4cf0..ce63a17f3e 100644--- a/clients/client-python/gravitino/dto/semantic/semantic_model_dto.py+++ b/clients/client-python/gravitino/dto/semantic/semantic_model_dto.py@@ -22,17 +22,16 @@ from dataclasses_json import configfrom gravitino.api.semantic.semantic_model import SemanticModelfrom gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition-from gravitino.dto.semantic.json_serdes.semantic_json_mixin import SemanticJsonMixin-from gravitino.dto.audit_dto import AuditDTOfrom gravitino.dto.semantic.semantic_model_definition_dto import (SemanticModelDefinitionDTO,)+from gravitino.dto.semantic.semantic_model_revision_dto import SemanticModelRevisionDTOfrom gravitino.utils.precondition import Preconditionfrom gravitino.dto.semantic.semantic_dto_utils import is_none@dataclass-class SemanticModelDTO(SemanticModel, SemanticJsonMixin):+class SemanticModelDTO(SemanticModel, SemanticModelRevisionDTO):"""Represents a schema-scoped Semantic Model DTO."""_name: Optional[str] = field(@@ -48,9 +47,6 @@ class SemanticModelDTO(SemanticModel, SemanticJsonMixin):_properties: Optional[dict[str, str]] = field(default=None, metadata=config(field_name="properties", exclude=is_none))- _audit: Optional[AuditDTO] = field(- default=None, metadata=config(field_name="audit", exclude=is_none)- )def name(self) -> Optional[str]:return self._name@@ -70,6 +66,3 @@ class SemanticModelDTO(SemanticModel, SemanticJsonMixin):def properties(self) -> dict[str, str]:return self._properties or {}-- def audit_info(self) -> Optional[AuditDTO]:- return self._auditdiff --git a/clients/client-python/gravitino/dto/semantic/semantic_model_revision_dto.py b/clients/client-python/gravitino/dto/semantic/semantic_model_revision_dto.pynew file mode 100644index 0000000000..0262dc0a2f--- /dev/null+++ b/clients/client-python/gravitino/dto/semantic/semantic_model_revision_dto.py@@ -0,0 +1,76 @@+# 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.++from dataclasses import dataclass, field+from datetime import datetime+from typing import Optional++from dataclasses_json import config++from gravitino.api.semantic.semantic_model_revision import (+ SemanticModelRevision,+ SemanticModelStatus,+)+from gravitino.dto.audit_dto import (+ AuditDTO,+ _deserialize_datetime,+ _serialize_datetime,+)+from gravitino.dto.semantic.json_serdes.semantic_json_mixin import SemanticJsonMixin+from gravitino.dto.semantic.semantic_dto_utils import is_none+++@dataclass+class SemanticModelRevisionDTO(SemanticModelRevision, SemanticJsonMixin):+ """The wire representation of a Semantic Model revision summary."""++ _revision: Optional[int] = field(+ default=None, metadata=config(field_name="revision", exclude=is_none)+ )+ _status: Optional[SemanticModelStatus] = field(+ default=None, metadata=config(field_name="status", exclude=is_none)+ )+ _published_by: Optional[str] = field(+ default=None, metadata=config(field_name="publishedBy", exclude=is_none)+ )+ _published_at: Optional[datetime] = field(+ default=None,+ metadata=config(+ field_name="publishedAt",+ encoder=_serialize_datetime,+ decoder=_deserialize_datetime,+ exclude=is_none,+ ),+ )+ _audit: Optional[AuditDTO] = field(+ default=None, metadata=config(field_name="audit", exclude=is_none)+ )++ def revision(self) -> int:+ return self._revision or 0++ def status(self) -> Optional[SemanticModelStatus]:+ return self._status++ def published_by(self) -> Optional[str]:+ return self._published_by++ def published_at(self) -> Optional[datetime]:+ return self._published_at++ def audit_info(self) -> Optional[AuditDTO]:+ return self._auditdiff --git a/clients/client-python/gravitino/exceptions/base.py b/clients/client-python/gravitino/exceptions/base.pyindex 7257ed9cd3..2d13f800b2 100644--- a/clients/client-python/gravitino/exceptions/base.py+++ b/clients/client-python/gravitino/exceptions/base.py@@ -299,6 +299,10 @@ class NoSuchSemanticModelException(NotFoundException):"""An exception thrown when a Semantic Model with specified name is not found."""+class NoSuchSemanticModelRevisionException(NotFoundException):+ """The requested Semantic Model revision could not be found."""++class SemanticModelAlreadyExistsException(AlreadyExistsException):"""An exception thrown when a Semantic Model already exists."""diff --git a/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py b/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.pyindex 4f5f9ae8ae..6d3a43abd6 100644--- a/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py+++ b/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py@@ -29,6 +29,7 @@ from gravitino.exceptions.base import (NoSuchMetalakeException,NoSuchSchemaException,NoSuchSemanticModelException,+ NoSuchSemanticModelRevisionException,NotFoundException,NotInUseException,SemanticModelAlreadyExistsException,@@ -84,6 +85,9 @@ class SemanticModelErrorHandler(RestErrorHandler):if exception_type == NoSuchSemanticModelException.__name__:raise NoSuchSemanticModelException(error_message)+ if exception_type == NoSuchSemanticModelRevisionException.__name__:+ raise NoSuchSemanticModelRevisionException(error_message)+raise NotFoundException(error_message)@staticmethoddiff --git a/clients/client-python/tests/integration/test_semantic_model_authorization.py b/clients/client-python/tests/integration/test_semantic_model_authorization.pyindex 258e5f9db6..aae7f1ef63 100644--- a/clients/client-python/tests/integration/test_semantic_model_authorization.py+++ b/clients/client-python/tests/integration/test_semantic_model_authorization.py@@ -172,9 +172,11 @@ class TestSemanticModelAuthorization(AuthorizationIntegrationTestEnv):"iceberg").as_semantic_model_catalog()for model_name in ("sales", "hidden"):+ ident = NameIdentifier.of("semantic", model_name)models.alter_semantic_model(- NameIdentifier.of("semantic", model_name),+ ident,SemanticModelChange.replace_definition(definition),+ expected_revision=models.load_semantic_model(ident).revision(),)namespace = Namespace.of("semantic")expected = [diff --git a/clients/client-python/tests/integration/test_semantic_model_metric_discovery.py b/clients/client-python/tests/integration/test_semantic_model_metric_discovery.pyindex 5a41eac8b0..7f747f7296 100644--- a/clients/client-python/tests/integration/test_semantic_model_metric_discovery.py+++ b/clients/client-python/tests/integration/test_semantic_model_metric_discovery.py@@ -106,6 +106,7 @@ class TestSemanticModelMetricDiscovery(IntegrationTestEnv):self.models.alter_semantic_model(identifier,SemanticModelChange.replace_definition(self._definition([changed])),+ expected_revision=self.models.load_semantic_model(identifier).revision(),)self._assert_discovery([SemanticModelMetric(Namespace.of("semantic", "sales"), changed)]@@ -119,12 +120,15 @@ class TestSemanticModelMetricDiscovery(IntegrationTestEnv):[SemanticModelMetric(Namespace.of("semantic", "renamed"), changed)])self.models.alter_semantic_model(- identifier, SemanticModelChange.replace_definition(self._definition([]))+ identifier,+ SemanticModelChange.replace_definition(self._definition([])),+ expected_revision=self.models.load_semantic_model(identifier).revision(),)self._assert_discovery([])self.models.alter_semantic_model(identifier,SemanticModelChange.replace_definition(self._definition([original])),+ expected_revision=self.models.load_semantic_model(identifier).revision(),)self._assert_discovery([SemanticModelMetric(Namespace.of("semantic", "renamed"), original)]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.pyindex 026bc4d91f..a97d99fec3 100644--- a/clients/client-python/tests/integration/test_semantic_model_source_lookup.py+++ b/clients/client-python/tests/integration/test_semantic_model_source_lookup.py@@ -153,7 +153,9 @@ class TestSemanticModelSourceLookup(IntegrationTestEnv):self.assertEqual(expected, self._lookup(renamed))replacement = self._definition("orders_v2", "orders.raw")self.models.alter_semantic_model(- identifier, SemanticModelChange.replace_definition(replacement)+ identifier,+ SemanticModelChange.replace_definition(replacement),+ expected_revision=self.models.load_semantic_model(identifier).revision(),)tables.drop_table(NameIdentifier.of("raw", "orders_v2"))with self.assertRaises(NoSuchMetadataObjectException):@@ -165,7 +167,9 @@ class TestSemanticModelSourceLookup(IntegrationTestEnv):)self.assertEqual([], self._lookup(recreated))self.models.alter_semantic_model(- identifier, SemanticModelChange.replace_definition(replacement)+ identifier,+ SemanticModelChange.replace_definition(replacement),+ expected_revision=self.models.load_semantic_model(identifier).revision(),)self.assertEqual(expected, self._lookup(recreated))self.models.drop_semantic_model(identifier)diff --git a/clients/client-python/tests/unittests/api/semantic/test_semantic_model_catalog.py b/clients/client-python/tests/unittests/api/semantic/test_semantic_model_catalog.pyindex 75dff8ad96..05d1ae36c4 100644--- a/clients/client-python/tests/unittests/api/semantic/test_semantic_model_catalog.py+++ b/clients/client-python/tests/unittests/api/semantic/test_semantic_model_catalog.py@@ -63,7 +63,11 @@ class _InMemorySemanticModelCatalog(SemanticModelCatalog):NameIdentifier.of(namespace.level(0), name) for name in sorted(self._models)]- def load_semantic_model(self, identifier: NameIdentifier) -> SemanticModel:+ def load_semantic_model(+ self, identifier: NameIdentifier, revision: Optional[int | str] = None+ ) -> SemanticModel:+ if revision is not None:+ raise UnsupportedOperationException("Revision reads are not supported")model = self._models.get(identifier.name())if model is None:raise NoSuchSemanticModelException(@@ -83,8 +87,13 @@ class _InMemorySemanticModelCatalog(SemanticModelCatalog):return modeldef alter_semantic_model(- self, identifier: NameIdentifier, *changes: SemanticModelChange+ self,+ identifier: NameIdentifier,+ *changes: SemanticModelChange,+ expected_revision: Optional[int] = None,) -> SemanticModel:+ if expected_revision is not None:+ raise UnsupportedOperationException("Conditional updates are not supported")return self.load_semantic_model(identifier)def drop_semantic_model(self, identifier: NameIdentifier) -> bool:diff --git a/clients/client-python/tests/unittests/dto/test_semantic_model_rest.py b/clients/client-python/tests/unittests/dto/test_semantic_model_rest.pyindex 934ecc8edb..a28c76fea0 100644--- a/clients/client-python/tests/unittests/dto/test_semantic_model_rest.py+++ b/clients/client-python/tests/unittests/dto/test_semantic_model_rest.py@@ -72,9 +72,10 @@ class TestSemanticModelREST(unittest.TestCase):update = SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(_definition=self.dto)- request = SemanticModelUpdatesRequest(_updates=[update])+ request = SemanticModelUpdatesRequest(_updates=[update], _expected_revision=3)request.validate()payload = json.loads(request.to_json(), parse_float=Decimal)+ self.assertEqual(3, payload["expectedRevision"])self.assertEqual("replaceDefinition", payload["updates"][0]["@type"])restored = SemanticModelDefinitionDTO.from_dict(payload["updates"][0]["definition"]diff --git a/clients/client-python/tests/unittests/test_semantic_model_catalog.py b/clients/client-python/tests/unittests/test_semantic_model_catalog.pyindex 50030c1b49..2473abf2b2 100644--- a/clients/client-python/tests/unittests/test_semantic_model_catalog.py+++ b/clients/client-python/tests/unittests/test_semantic_model_catalog.py@@ -15,13 +15,16 @@# specific language governing permissions and limitations# under the License.+import jsonimport unittest+from datetime import datetime, timezonefrom unittest.mock import Mock, patchfrom gravitino.api.semantic.dataset import Datasetfrom gravitino.api.semantic.semantic_model_catalog import SemanticModelCatalogfrom gravitino.api.semantic.semantic_model_change import SemanticModelChangefrom gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition+from gravitino.api.semantic.semantic_model_revision import SemanticModelStatusfrom gravitino.client.relational_catalog import RelationalCatalogfrom gravitino.dto.audit_dto import AuditDTOfrom gravitino.dto.responses.drop_response import DropResponse@@ -256,6 +259,55 @@ class TestSemanticModelCatalog(unittest.TestCase):{},)+ def test_history_load_and_export_address_revisions(self):+ identifier = NameIdentifier.of(self.schema_name, self.model_name)+ models = self.catalog.as_semantic_model_catalog()+ metadata = {+ "revision": 4,+ "status": "PUBLISHED",+ "publishedBy": "reviewer",+ "publishedAt": "2026-01-02T00:00:00Z",+ "audit": {"creator": "author"},+ }+ snapshot = json.loads(self._mock_semantic_model_response().body)+ snapshot["semanticModel"].update(metadata)+ path = f"{self.request_path}/{self.model_name}/revisions"+ with patch("gravitino.utils.http_client.HTTPClient.get") as mock_get:+ mock_get.return_value = self._get_mock_http_resp(+ json.dumps({"code": 0, "revisions": [metadata]})+ )+ summary = models.list_semantic_model_revisions(identifier)[0]+ self.assertEqual(path, mock_get.call_args.args[0])+ self.assertEqual(4, summary.revision())+ self.assertEqual(SemanticModelStatus.PUBLISHED, summary.status())+ self.assertEqual("author", summary.audit_info().creator())+ self.assertEqual("reviewer", summary.published_by())+ self.assertEqual(+ datetime(2026, 1, 2, tzinfo=timezone.utc), summary.published_at()+ )++ mock_get.return_value = self._get_mock_http_resp(json.dumps(snapshot))+ loaded = models.load_semantic_model(identifier, "latest")+ self.assertEqual(f"{path}/latest", mock_get.call_args.args[0])+ self.assertEqual(summary.published_at(), loaded.published_at())+ self.assertEqual(4, loaded.revision())++ mock_get.return_value = self._get_mock_http_resp("name: sales_model")+ self.assertEqual(+ "name: sales_model",+ models.export_ossie_document(identifier, revision=4),+ )+ self.assertEqual(f"{path}/4/ossie", mock_get.call_args.args[0])++ def test_replacement_without_expected_revision_is_rejected(self):+ identifier = NameIdentifier.of(self.schema_name, self.model_name)+ with self.assertRaisesRegex(+ IllegalArgumentException, "expected_revision is required"+ ):+ self.catalog.as_semantic_model_catalog().alter_semantic_model(+ identifier, SemanticModelChange.replace_definition(_definition())+ )+def test_alter_semantic_model_sends_every_change(self):identifier = NameIdentifier.of(self.schema_name, self.model_name)@@ -265,20 +317,21 @@ class TestSemanticModelCatalog(unittest.TestCase):) as mock_put:model = self.catalog.as_semantic_model_catalog().alter_semantic_model(identifier,- SemanticModelChange.rename("renamed_model"),SemanticModelChange.update_comment("new comment"),SemanticModelChange.set_property("owner", "finance"),SemanticModelChange.remove_property("legacy"),SemanticModelChange.replace_definition(_definition()),+ expected_revision=1,)self.assertEqual(f"{self.request_path}/{self.model_name}", mock_put.call_args.args[0])- updates = mock_put.call_args.kwargs["json"].to_dict()["updates"]+ request = mock_put.call_args.kwargs["json"].to_dict()+ self.assertEqual(1, request["expectedRevision"])+ updates = request["updates"]self.assertEqual([- "rename","updateComment","setProperty","removeProperty",@@ -286,12 +339,11 @@ class TestSemanticModelCatalog(unittest.TestCase):],[update["@type"] for update in updates],)- self.assertEqual("renamed_model", updates[0]["newName"])- self.assertEqual("new comment", updates[1]["newComment"])- self.assertEqual("owner", updates[2]["property"])- self.assertEqual("finance", updates[2]["value"])- self.assertEqual("legacy", updates[3]["property"])- self.assertIn("datasets", updates[4]["definition"])+ self.assertEqual("new comment", updates[0]["newComment"])+ self.assertEqual("owner", updates[1]["property"])+ self.assertEqual("finance", updates[1]["value"])+ self.assertEqual("legacy", updates[2]["property"])+ self.assertIn("datasets", updates[3]["definition"])self.assertEqual(self.model_name, model.name())def test_alter_semantic_model_can_clear_the_comment(self):diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.javaindex 27f57f0a47..13a51e8c2b 100644--- a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java+++ b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java@@ -18,9 +18,17 @@*/package org.apache.gravitino.dto.requests;+import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.core.JsonParser;+import com.fasterxml.jackson.core.JsonToken;+import com.fasterxml.jackson.databind.DeserializationContext;+import com.fasterxml.jackson.databind.JsonDeserializer;+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;import com.google.common.base.Preconditions;+import java.io.IOException;import java.util.List;+import javax.annotation.Nullable;import lombok.EqualsAndHashCode;import lombok.Getter;import lombok.ToString;@@ -35,6 +43,12 @@ public class SemanticModelUpdatesRequest implements RESTRequest {@JsonProperty("updates")private final List<SemanticModelUpdateRequest> updates;+ @Nullable+ @JsonInclude(JsonInclude.Include.NON_NULL)+ @JsonProperty("expectedRevision")+ @JsonDeserialize(using = ExpectedRevisionDeserializer.class)+ private final Integer expectedRevision;+/** Default constructor for Jackson deserialization. */public SemanticModelUpdatesRequest() {this(null);@@ -46,16 +60,50 @@ public class SemanticModelUpdatesRequest implements RESTRequest {* @param updates The non-empty list of updates to apply.*/public SemanticModelUpdatesRequest(List<SemanticModelUpdateRequest> updates) {+ this(updates, null);+ }++ /**+ * Creates an alteration request with an optional revision precondition.+ *+ * @param updates The non-empty list of updates to apply.+ * @param expectedRevision The expected latest revision, or null if omitted.+ */+ public SemanticModelUpdatesRequest(+ List<SemanticModelUpdateRequest> updates, @Nullable Integer expectedRevision) {this.updates = updates;+ this.expectedRevision = expectedRevision;}@Overridepublic void validate() throws IllegalArgumentException {Preconditions.checkArgument(updates != null, "updates must not be null");Preconditions.checkArgument(!updates.isEmpty(), "updates must not be empty");+ Preconditions.checkArgument(+ expectedRevision == null || expectedRevision > 0, "expectedRevision must be positive");for (SemanticModelUpdateRequest update : updates) {Preconditions.checkArgument(update != null, "update must not be null");+ Preconditions.checkArgument(+ !(update instanceof SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest)+ || expectedRevision != null,+ "expectedRevision is required when replacing the definition");+ Preconditions.checkArgument(+ !(update instanceof SemanticModelUpdateRequest.RenameSemanticModelRequest)+ || updates.size() == 1,+ "Rename must be the only Semantic Model change");update.validate();}}++ private static class ExpectedRevisionDeserializer extends JsonDeserializer<Integer> {+ @Override+ public Integer deserialize(JsonParser parser, DeserializationContext context)+ throws IOException {+ if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {+ return context.reportInputMismatch(+ Integer.class, "expectedRevision must be a 32-bit integer");+ }+ return parser.getIntValue();+ }+ }}diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelRevisionListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelRevisionListResponse.javanew file mode 100644index 0000000000..80ebe25b0b--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/SemanticModelRevisionListResponse.java@@ -0,0 +1,60 @@+/*+ * 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.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import org.apache.gravitino.dto.semantic.SemanticModelRevisionDTO;++/** A response containing the visible Semantic Model revisions, newest first. */+public class SemanticModelRevisionListResponse extends BaseResponse {++ @JsonProperty("revisions")+ private final SemanticModelRevisionDTO[] revisions;++ /** Default constructor for Jackson deserialization. */+ public SemanticModelRevisionListResponse() {+ this(null);+ }++ /**+ * Creates a response with the revision summaries.+ *+ * @param revisions The revision summaries, newest first.+ */+ public SemanticModelRevisionListResponse(SemanticModelRevisionDTO[] revisions) {+ super(0);+ this.revisions = revisions;+ }++ /**+ * Returns the revision summaries.+ *+ * @return The revision summaries, newest first.+ */+ public SemanticModelRevisionDTO[] revisions() {+ return revisions;+ }++ @Override+ public void validate() {+ super.validate();+ Preconditions.checkArgument(revisions != null, "revisions must not be null");+ }+}diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.javaindex 485b042fd7..ec6b6fa1ca 100644--- a/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java@@ -36,66 +36,56 @@ public class TestSemanticModelUpdateRequest {@Testpublic void testAllUpdateTypesSerDeValidateAndConvert() throws JsonProcessingException {String json =- "{\"updates\":["- + "{\"@type\":\"rename\",\"newName\":\"sales_v2\"},"- + "{\"@type\":\"updateComment\",\"newComment\":null},"- + "{\"@type\":\"setProperty\",\"property\":\"owner\",\"value\":\"finance\"},"- + "{\"@type\":\"removeProperty\",\"property\":\"legacy\"},"- + "{\"@type\":\"replaceDefinition\",\"definition\":{"- + "\"datasets\":[{\"name\":\"orders\","- + "\"source\":{\"namespace\":[\"sales\",\"mart\"],\"name\":\"orders\"}}],"- + "\"relationships\":[],\"metrics\":[],\"customExtensions\":[]}}"- + "]}";-+ """+ {"expectedRevision": 4, "updates":[+ {"@type":"updateComment","newComment":null},+ {"@type":"setProperty","property":"owner","value":"finance"},+ {"@type":"removeProperty","property":"legacy"},+ {"@type":"replaceDefinition","definition":{+ "datasets":[{"name":"orders","source":{"namespace":["sales","mart"],"name":"orders"}}],+ "relationships":[],"metrics":[],"customExtensions":[]}}+ ]}+ """;SemanticModelUpdatesRequest request =JsonUtils.objectMapper().readValue(json, SemanticModelUpdatesRequest.class);request.validate();+ assertEquals(4, request.getExpectedRevision());- assertInstanceOf(- SemanticModelUpdateRequest.RenameSemanticModelRequest.class, request.getUpdates().get(0));- assertInstanceOf(- SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest.class,- request.getUpdates().get(1));- assertInstanceOf(- SemanticModelUpdateRequest.SetSemanticModelPropertyRequest.class,- request.getUpdates().get(2));- assertInstanceOf(- SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest.class,- request.getUpdates().get(3));- assertInstanceOf(- SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest.class,- request.getUpdates().get(4));-- SemanticModelChange.RenameSemanticModel rename =- (SemanticModelChange.RenameSemanticModel) request.getUpdates().get(0).semanticModelChange();- assertEquals("sales_v2", rename.getNewName());SemanticModelChange.UpdateComment updateComment =- (SemanticModelChange.UpdateComment) request.getUpdates().get(1).semanticModelChange();+ assertInstanceOf(+ SemanticModelChange.UpdateComment.class,+ request.getUpdates().get(0).semanticModelChange());assertNull(updateComment.getNewComment());SemanticModelChange.SetProperty setProperty =- (SemanticModelChange.SetProperty) request.getUpdates().get(2).semanticModelChange();+ assertInstanceOf(+ SemanticModelChange.SetProperty.class,+ request.getUpdates().get(1).semanticModelChange());assertEquals("owner", setProperty.getProperty());assertEquals("finance", setProperty.getValue());SemanticModelChange.RemoveProperty removeProperty =- (SemanticModelChange.RemoveProperty) request.getUpdates().get(3).semanticModelChange();+ assertInstanceOf(+ SemanticModelChange.RemoveProperty.class,+ request.getUpdates().get(2).semanticModelChange());assertEquals("legacy", removeProperty.getProperty());SemanticModelChange.ReplaceDefinition replaceDefinition =- (SemanticModelChange.ReplaceDefinition) request.getUpdates().get(4).semanticModelChange();+ assertInstanceOf(+ SemanticModelChange.ReplaceDefinition.class,+ request.getUpdates().get(3).semanticModelChange());assertEquals("orders", replaceDefinition.getDefinition().datasets()[0].name());assertEquals(0, replaceDefinition.getDefinition().relationships().length);JsonNode serialized =JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(request));- assertEquals("rename", serialized.path("updates").get(0).path("@type").textValue());- assertEquals("updateComment", serialized.path("updates").get(1).path("@type").textValue());- assertEquals("setProperty", serialized.path("updates").get(2).path("@type").textValue());- assertEquals("removeProperty", serialized.path("updates").get(3).path("@type").textValue());- assertEquals("replaceDefinition", serialized.path("updates").get(4).path("@type").textValue());+ assertEquals(4, serialized.path("expectedRevision").asInt());+ assertEquals("updateComment", serialized.path("updates").get(0).path("@type").textValue());+ assertEquals("setProperty", serialized.path("updates").get(1).path("@type").textValue());+ assertEquals("removeProperty", serialized.path("updates").get(2).path("@type").textValue());+ assertEquals("replaceDefinition", serialized.path("updates").get(3).path("@type").textValue());assertEquals("orders",serialized.path("updates")- .get(4)+ .get(3).path("definition").path("datasets").get(0)@@ -103,6 +93,21 @@ public class TestSemanticModelUpdateRequest {.textValue());}+ @Test+ void testRenameRequestRoundTrip() throws JsonProcessingException {+ String json = "{\"updates\":[{\"@type\":\"rename\",\"newName\":\"sales_v2\"}]}";+ SemanticModelUpdatesRequest request =+ JsonUtils.objectMapper().readValue(json, SemanticModelUpdatesRequest.class);+ request.validate();+ SemanticModelChange.RenameSemanticModel rename =+ assertInstanceOf(+ SemanticModelChange.RenameSemanticModel.class,+ request.getUpdates().get(0).semanticModelChange());+ assertEquals("sales_v2", rename.getNewName());+ assertEquals(+ JsonUtils.objectMapper().readTree(json), JsonUtils.objectMapper().valueToTree(request));+ }+@Testpublic void testUpdatesWrapperRequiresNonEmptyValidatedItems() {IllegalArgumentException missing =@@ -144,7 +149,7 @@ public class TestSemanticModelUpdateRequest {((SemanticModelChange.UpdateComment) emptyComment.semanticModelChange()).getNewComment());String nullDataset =- "{\"updates\":[{\"@type\":\"replaceDefinition\","+ "{\"expectedRevision\":1,\"updates\":[{\"@type\":\"replaceDefinition\","+ "\"definition\":{\"datasets\":[null]}}]}";SemanticModelUpdatesRequest request =JsonUtils.objectMapper().readValue(nullDataset, SemanticModelUpdatesRequest.class);@@ -156,7 +161,7 @@ public class TestSemanticModelUpdateRequest {@Testpublic void testReplaceDefinitionRejectsUnknownNestedFields() {String json =- "{\"updates\":[{\"@type\":\"replaceDefinition\",\"definition\":{"+ "{\"expectedRevision\":1,\"updates\":[{\"@type\":\"replaceDefinition\",\"definition\":{"+ "\"datasets\":[{\"name\":\"orders\","+ "\"source\":{\"namespace\":[\"sales\",\"mart\"],\"name\":\"orders\"}}],"+ "\"unknown\":true}}]}";diff --git a/core/src/main/java/org/apache/gravitino/EntityStore.java b/core/src/main/java/org/apache/gravitino/EntityStore.javaindex 6a2730e5e6..407bc86582 100644--- a/core/src/main/java/org/apache/gravitino/EntityStore.java+++ b/core/src/main/java/org/apache/gravitino/EntityStore.java@@ -26,16 +26,31 @@ import java.util.List;import java.util.Optional;import java.util.function.Consumer;import java.util.function.Function;+import javax.annotation.Nullable;import org.apache.commons.lang3.tuple.Pair;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.SemanticModelEntity;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.utils.Executable;public interface EntityStore extends Closeable {+ /** Loads a retained Semantic Model snapshot or the latest saved revision. */+ default SemanticModelEntity loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {+ throw new UnsupportedOperationException("Loading Semantic Model revisions is not supported");+ }++ /** Lists retained Semantic Model revision metadata newest first. */+ default SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident)+ throws IOException {+ throw new UnsupportedOperationException("Listing Semantic Model revisions is not supported");+ }+/** Lists model identities for governance, irrespective of publication state. */default List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace)throws IOException {@@ -44,6 +59,16 @@ public interface EntityStore extends Closeable {.toList();}+ /** Applies a Semantic Model update with an optional revision precondition. */+ default SemanticModelEntity updateSemanticModel(+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ boolean rename,+ Function<SemanticModelEntity, SemanticModelEntity> updater)+ throws IOException {+ return update(ident, SemanticModelEntity.class, EntityType.SEMANTIC_MODEL, updater);+ }+/*** Reads metric identifiers in a schema without loading complete Semantic Models.*diff --git a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.javaindex de81a6731f..85094210fe 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java@@ -38,6 +38,7 @@ import org.apache.gravitino.exceptions.IllegalSemanticModelException;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.SemanticModelEntity;@@ -46,6 +47,8 @@ import org.apache.gravitino.semantic.SemanticModel.Status;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.PrincipalUtils;@@ -160,6 +163,18 @@ public class ManagedSemanticModelOperations {}}+ /** Loads the requested retained snapshot. */+ public SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) {+ try {+ return store.loadSemanticModelRevision(ident, selector);+ } catch (NoSuchEntityException e) {+ throw new NoSuchSemanticModelException(e, "Semantic Model %s does not exist", ident);+ } catch (IOException e) {+ throw new RuntimeException("Failed to load Semantic Model revision for " + ident, e);+ }+ }+/** Returns whether the identity exists, even when the model has no active revision. */public boolean semanticModelExists(NameIdentifier ident) {try {@@ -169,6 +184,17 @@ public class ManagedSemanticModelOperations {}}+ /** Lists retained revision summaries for the requested model. */+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ try {+ return store.listSemanticModelRevisions(ident);+ } catch (NoSuchEntityException e) {+ throw new NoSuchSemanticModelException(e, "Semantic Model %s does not exist", ident);+ } catch (IOException e) {+ throw new RuntimeException("Failed to list Semantic Model revisions for " + ident, e);+ }+ }+/*** Creates a model with its validated source associations.*@@ -239,18 +265,38 @@ public class ManagedSemanticModelOperations {NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {+ return alterSemanticModel(ident, sourceUpdate, null, changes);+ }++ /** Applies changes to latest, optionally requiring the caller's expected revision. */+ public SemanticModel alterSemanticModel(+ NameIdentifier ident,+ SemanticModelSourceUpdate sourceUpdate,+ @Nullable Integer expectedRevision,+ SemanticModelChange... changes) {boolean validateForWrite = requiresWriteValidation(changes);+ Preconditions.checkArgument(+ expectedRevision == null || expectedRevision > 0, "expectedRevision must be positive");+ Preconditions.checkArgument(+ !validateForWrite || expectedRevision != null,+ "expectedRevision is required when replacing the definition");+ boolean rename = changes[0] instanceof SemanticModelChange.RenameSemanticModel;Preconditions.checkArgument(validateForWrite == sourceUpdate.replacesSources(),"Definition replacement must replace sources; metadata-only changes must preserve sources");try {- return store.update(+ return store.updateSemanticModel(ident,- SemanticModelEntity.class,- Entity.EntityType.SEMANTIC_MODEL,+ expectedRevision,+ rename,oldEntity -> {- SemanticModelEntity candidate = applyChanges(oldEntity, sourceUpdate, changes);+ if (expectedRevision != null && oldEntity.revision() != expectedRevision) {+ throw new OptimisticLockException(+ "Semantic Model %s is at revision %s, expected %s",+ ident, oldEntity.revision(), expectedRevision);+ }+ SemanticModelEntity candidate = applyChanges(oldEntity, sourceUpdate, rename, changes);if (validateForWrite) {NameIdentifier candidateIdent =NameIdentifier.of(candidate.namespace(), candidate.name());@@ -306,8 +352,10 @@ public class ManagedSemanticModelOperations {if (change instanceof SemanticModelChange.ReplaceDefinition) {requiresWriteValidation = true;- } else if (change instanceof SemanticModelChange.RenameSemanticModel- || change instanceof SemanticModelChange.UpdateComment+ } else if (change instanceof SemanticModelChange.RenameSemanticModel) {+ Preconditions.checkArgument(+ changes.length == 1, "Rename must be the only Semantic Model change");+ } else if (change instanceof SemanticModelChange.UpdateComment|| change instanceof SemanticModelChange.SetProperty|| change instanceof SemanticModelChange.RemoveProperty) {// These changes do not modify the definition and must not revisit its sources.@@ -322,6 +370,7 @@ public class ManagedSemanticModelOperations {private static SemanticModelEntity applyChanges(SemanticModelEntity oldEntity,SemanticModelSourceUpdate sourceUpdate,+ boolean rename,SemanticModelChange[] changes) {String newName = oldEntity.name();String newComment = oldEntity.comment();@@ -346,22 +395,32 @@ public class ManagedSemanticModelOperations {AuditInfo oldAudit = oldEntity.auditInfo();Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);String writer = PrincipalUtils.getCurrentUserName();- return SemanticModelEntity.builder()- .withId(oldEntity.id())- .withName(newName)- .withNamespace(oldEntity.namespace())- .withComment(newComment)- .withDefinition(newDefinition)- .withSourceUpdate(sourceUpdate)- .withProperties(newProperties)- .withRevision(Math.incrementExact(oldEntity.revision()), Status.PUBLISHED, writer, now)- .withAuditInfo(- AuditInfo.builder()- .withCreator(oldAudit.creator())- .withCreateTime(oldAudit.createTime())- .withLastModifier(writer)- .withLastModifiedTime(now)- .build())- .build();+ SemanticModelEntity.Builder builder =+ SemanticModelEntity.builder()+ .withId(oldEntity.id())+ .withName(newName)+ .withNamespace(oldEntity.namespace())+ .withComment(newComment)+ .withDefinition(newDefinition)+ .withSourceUpdate(sourceUpdate)+ .withProperties(newProperties)+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(oldAudit.creator())+ .withCreateTime(oldAudit.createTime())+ .withLastModifier(writer)+ .withLastModifiedTime(now)+ .build());+ if (rename) {+ builder.withRevision(+ oldEntity.revision(),+ oldEntity.status(),+ oldEntity.publishedBy(),+ oldEntity.publishedAt());+ } else {+ builder.withRevision(+ Math.incrementExact(oldEntity.revision()), Status.PUBLISHED, writer, now);+ }+ return builder.build();}}diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.javaindex b57964e32a..a35bc76937 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java@@ -39,6 +39,8 @@ import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;/** Dispatches Semantic Model operations through the server pipeline. */@@ -90,6 +92,13 @@ public interface SemanticModelDispatcher {*/SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException;+ /** Loads a selected revision. */+ SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector);++ /** Lists retained revision metadata for a model. */+ SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident);+/*** Returns whether a Semantic Model exists.*@@ -192,7 +201,16 @@ public interface SemanticModelDispatcher {* @throws NoSuchSemanticModelException If the Semantic Model does not exist.* @throws IllegalSemanticModelException If the model cannot be represented as an Ossie document.*/- OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format);+ default OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {+ return exportSemanticModel(ident, SemanticModelRevisionSelector.ACTIVE, format).document();+ }++ /** Exports a selected revision. */+ SemanticModelExport exportSemanticModel(+ NameIdentifier ident, SemanticModelRevisionSelector selector, OssieFormat format);++ /** An exported document and the exact revision used to serialize it. */+ record SemanticModelExport(OssieDocument document, int revision) {}/*** Applies changes atomically to a Semantic Model.@@ -207,10 +225,19 @@ public interface SemanticModelDispatcher {* Model.* @throws IllegalSemanticModelException If a change or the resulting Semantic Model is invalid.*/+ default SemanticModel alterSemanticModel(+ NameIdentifier ident,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes) {+ return alterSemanticModel(ident, null, sourceUpdate, changes);+ }++ /** Applies changes to latest, optionally requiring the caller's expected revision. */SemanticModel alterSemanticModel(- NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)- throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,- IllegalSemanticModelException;+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes);/*** Drops a Semantic Model.diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.javaindex 2d1a62e200..1399d9df74 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java@@ -36,12 +36,13 @@ import org.apache.gravitino.exceptions.IllegalSemanticModelException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;-import org.apache.gravitino.semantic.OssieDocument;import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;/** Normalizes Semantic Model parents while retaining Gravitino-owned model naming rules. */@@ -104,6 +105,17 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcherreturn dispatcher.semanticModelExists(normalizeForLookup(ident));}+ @Override+ public SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) {+ return dispatcher.loadSemanticModelRevision(normalizeForLookup(ident), selector);+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ return dispatcher.listSemanticModelRevisions(normalizeForLookup(ident));+ }+@Overridepublic SemanticModel createSemanticModel(NameIdentifier ident,@@ -129,13 +141,17 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher}@Override- public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {- return dispatcher.exportOssieDocument(normalizeForLookup(ident), format);+ public SemanticModelExport exportSemanticModel(+ NameIdentifier ident, SemanticModelRevisionSelector selector, OssieFormat format) {+ return dispatcher.exportSemanticModel(normalizeForLookup(ident), selector, format);}@Overridepublic SemanticModel alterSemanticModel(- NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {Preconditions.checkArgument(@@ -143,7 +159,7 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcherSemanticModelChange[] normalizedChanges =Arrays.stream(changes).map(this::normalizeChange).toArray(SemanticModelChange[]::new);return dispatcher.alterSemanticModel(- normalizeForLookup(ident), sourceUpdate, normalizedChanges);+ normalizeForLookup(ident), expectedRevision, sourceUpdate, normalizedChanges);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.javaindex fdbb1bb216..d9e6f3d8fb 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java@@ -46,7 +46,6 @@ import org.apache.gravitino.exceptions.NoSuchSemanticModelException;import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;import org.apache.gravitino.meta.SemanticModelDatasetListing;import org.apache.gravitino.secret.SecretManager;-import org.apache.gravitino.semantic.OssieDocument;import org.apache.gravitino.semantic.OssieDocumentConverter;import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;@@ -54,6 +53,8 @@ import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.semantic.SemanticModelPropertiesMetadata;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.MetadataObjectUtil;@@ -172,6 +173,19 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher&& managedOperations.semanticModelExists(ident);}+ @Override+ public SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) {+ checkModelParent(ident);+ return managedOperations.loadSemanticModelRevision(ident, selector);+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ checkModelParent(ident);+ return managedOperations.listSemanticModelRevisions(ident);+ }+@Overridepublic SemanticModel createSemanticModel(NameIdentifier ident,@@ -207,13 +221,24 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher/** {@inheritDoc} */@Override- public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {- return OssieDocumentConverter.exportDocument(loadSemanticModel(ident), format);+ public SemanticModelExport exportSemanticModel(+ NameIdentifier ident, SemanticModelRevisionSelector selector, OssieFormat format) {+ SemanticModel model;+ if (selector == SemanticModelRevisionSelector.ACTIVE) {+ model = loadSemanticModel(ident);+ } else {+ model = loadSemanticModelRevision(ident, selector);+ }+ return new SemanticModelExport(+ OssieDocumentConverter.exportDocument(model, format), model.revision());}@Overridepublic SemanticModel alterSemanticModel(- NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {if (changes == null || changes.length == 0) {@@ -225,7 +250,7 @@ public class SemanticModelOperationDispatcher extends OperationDispatcherif (!schemaDispatcher.schemaExists(schemaIdent)) {throw new NoSuchSemanticModelException("Semantic Model %s does not exist", ident);}- return managedOperations.alterSemanticModel(ident, sourceUpdate, changes);+ return managedOperations.alterSemanticModel(ident, sourceUpdate, expectedRevision, changes);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.javaindex 47c35c23b9..efdd6630ac 100644--- a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java@@ -33,12 +33,13 @@ import org.apache.gravitino.exceptions.IllegalSemanticModelException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchSemanticModelException;import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;-import org.apache.gravitino.semantic.OssieDocument;import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;@@ -96,6 +97,17 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {return dispatcher.semanticModelExists(ident);}+ @Override+ public SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) {+ return dispatcher.loadSemanticModelRevision(ident, selector);+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ return dispatcher.listSemanticModelRevisions(ident);+ }+@Overridepublic SemanticModel createSemanticModel(NameIdentifier ident,@@ -125,16 +137,21 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {}@Override- public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {- return dispatcher.exportOssieDocument(ident, format);+ public SemanticModelExport exportSemanticModel(+ NameIdentifier ident, SemanticModelRevisionSelector selector, OssieFormat format) {+ return dispatcher.exportSemanticModel(ident, selector, format);}@Overridepublic SemanticModel alterSemanticModel(- NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {- SemanticModel model = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);+ SemanticModel model =+ dispatcher.alterSemanticModel(ident, expectedRevision, sourceUpdate, changes);for (SemanticModelChange change : changes) {if (change instanceof SemanticModelChange.RenameSemanticModel) {AuthorizationUtils.notifyEntityNameIdMappingChange(ident, Entity.EntityType.SEMANTIC_MODEL);diff --git a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.javaindex de0330c437..5a240a442e 100644--- a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java@@ -21,6 +21,7 @@ package org.apache.gravitino.listener;import java.util.Map;import java.util.function.Function;+import java.util.function.Supplier;import javax.annotation.Nullable;import org.apache.gravitino.Entity;import org.apache.gravitino.MetadataObject;@@ -69,6 +70,8 @@ import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.utils.PrincipalUtils;@@ -160,17 +163,7 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {- String user = PrincipalUtils.getCurrentUserName();- eventBus.dispatchEvent(new LoadSemanticModelPreEvent(user, ident));- try {- SemanticModel semanticModel = dispatcher.loadSemanticModel(ident);- eventBus.dispatchEvent(- new LoadSemanticModelEvent(user, ident, new SemanticModelInfo(semanticModel)));- return semanticModel;- } catch (Exception e) {- eventBus.dispatchEvent(new LoadSemanticModelFailureEvent(user, ident, e));- throw e;- }+ return loadWithEvents(ident, () -> dispatcher.loadSemanticModel(ident));}@Override@@ -178,6 +171,17 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {return dispatcher.semanticModelExists(ident);}+ @Override+ public SemanticModel loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) {+ return loadWithEvents(ident, () -> dispatcher.loadSemanticModelRevision(ident, selector));+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident) {+ return dispatcher.listSemanticModelRevisions(ident);+ }+@Overridepublic SemanticModel createSemanticModel(NameIdentifier ident,@@ -239,13 +243,14 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {}@Override- public OssieDocument exportOssieDocument(NameIdentifier ident, OssieFormat format) {+ public SemanticModelExport exportSemanticModel(+ NameIdentifier ident, SemanticModelRevisionSelector selector, OssieFormat format) {String user = PrincipalUtils.getCurrentUserName();try {eventBus.dispatchEvent(new ExportSemanticModelPreEvent(user, ident, format));- OssieDocument document = dispatcher.exportOssieDocument(ident, format);- eventBus.dispatchEvent(new ExportSemanticModelEvent(user, ident, format));- return document;+ SemanticModelExport export = dispatcher.exportSemanticModel(ident, selector, format);+ eventBus.dispatchEvent(new ExportSemanticModelEvent(user, ident, format, export.revision()));+ return export;} catch (Exception e) {eventBus.dispatchEvent(new ExportSemanticModelFailureEvent(user, ident, format, e));throw e;@@ -254,13 +259,17 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {@Overridepublic SemanticModel alterSemanticModel(- NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ SemanticModelSourceUpdate sourceUpdate,+ SemanticModelChange... changes)throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,IllegalSemanticModelException {String user = PrincipalUtils.getCurrentUserName();eventBus.dispatchEvent(new AlterSemanticModelPreEvent(user, ident, changes));try {- SemanticModel semanticModel = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);+ SemanticModel semanticModel =+ dispatcher.alterSemanticModel(ident, expectedRevision, sourceUpdate, changes);eventBus.dispatchEvent(new AlterSemanticModelEvent(user, ident, changes, new SemanticModelInfo(semanticModel)));return semanticModel;@@ -283,4 +292,18 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {throw e;}}++ private SemanticModel loadWithEvents(NameIdentifier ident, Supplier<SemanticModel> load) {+ String user = PrincipalUtils.getCurrentUserName();+ eventBus.dispatchEvent(new LoadSemanticModelPreEvent(user, ident));+ try {+ SemanticModel semanticModel = load.get();+ eventBus.dispatchEvent(+ new LoadSemanticModelEvent(user, ident, new SemanticModelInfo(semanticModel)));+ return semanticModel;+ } catch (Exception e) {+ eventBus.dispatchEvent(new LoadSemanticModelFailureEvent(user, ident, e));+ throw e;+ }+ }}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ExportSemanticModelEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ExportSemanticModelEvent.javaindex 5df4d49d4f..8de9c9f763 100644--- a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ExportSemanticModelEvent.java+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ExportSemanticModelEvent.java@@ -19,6 +19,7 @@package org.apache.gravitino.listener.api.event.semantic;+import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.annotation.DeveloperApi;import org.apache.gravitino.listener.api.event.OperationType;@@ -28,6 +29,7 @@ import org.apache.gravitino.semantic.OssieFormat;@DeveloperApipublic final class ExportSemanticModelEvent extends SemanticModelEvent {private final OssieFormat format;+ private final int revision;/*** Constructs a {@code ExportSemanticModelEvent}.@@ -35,10 +37,13 @@ public final class ExportSemanticModelEvent extends SemanticModelEvent {* @param user The username of the individual who initiated the operation.* @param identifier The Semantic Model identifier.* @param format The non-null document format.+ * @param revision The exported revision number.*/- public ExportSemanticModelEvent(String user, NameIdentifier identifier, OssieFormat format) {+ public ExportSemanticModelEvent(+ String user, NameIdentifier identifier, OssieFormat format, int revision) {super(user, identifier);this.format = format;+ this.revision = revision;}/**@@ -50,6 +55,16 @@ public final class ExportSemanticModelEvent extends SemanticModelEvent {return format;}+ /** Returns the exported revision number. */+ public int revision() {+ return revision;+ }++ @Override+ protected Map<String, String> ownCustomInfo() {+ return Map.of("revision", Integer.toString(revision));+ }+@Overridepublic OperationType operationType() {return OperationType.EXPORT_SEMANTIC_MODEL;diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/LoadSemanticModelEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/LoadSemanticModelEvent.javaindex ec8fa44f73..0f63845107 100644--- a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/LoadSemanticModelEvent.java+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/LoadSemanticModelEvent.java@@ -19,6 +19,7 @@package org.apache.gravitino.listener.api.event.semantic;+import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.annotation.DeveloperApi;import org.apache.gravitino.listener.api.event.OperationType;@@ -51,6 +52,11 @@ public final class LoadSemanticModelEvent extends SemanticModelEvent {return loadedSemanticModelInfo;}+ @Override+ protected Map<String, String> ownCustomInfo() {+ return Map.of("revision", Integer.toString(loadedSemanticModelInfo.revision()));+ }+@Overridepublic OperationType operationType() {return OperationType.LOAD_SEMANTIC_MODEL;diff --git a/core/src/main/java/org/apache/gravitino/listener/api/info/SemanticModelInfo.java b/core/src/main/java/org/apache/gravitino/listener/api/info/SemanticModelInfo.javaindex 626b7b901c..4230e43275 100644--- a/core/src/main/java/org/apache/gravitino/listener/api/info/SemanticModelInfo.java+++ b/core/src/main/java/org/apache/gravitino/listener/api/info/SemanticModelInfo.java@@ -38,6 +38,8 @@ public final class SemanticModelInfo {private final SemanticModelDefinition definition;private final Map<String, String> properties;@Nullable private final Audit auditInfo;+ private final int revision;+ @Nullable private final SemanticModel.Status status;/*** Constructs a SemanticModelInfo from a {@link SemanticModel}.@@ -50,7 +52,9 @@ public final class SemanticModelInfo {semanticModel.comment(),semanticModel.definition(),semanticModel.properties(),- semanticModel.auditInfo());+ semanticModel.auditInfo(),+ semanticModel.revision(),+ semanticModel.status());}/**@@ -68,11 +72,24 @@ public final class SemanticModelInfo {SemanticModelDefinition definition,@Nullable Map<String, String> properties,@Nullable Audit auditInfo) {+ this(name, comment, definition, properties, auditInfo, 0, null);+ }++ private SemanticModelInfo(+ String name,+ @Nullable String comment,+ SemanticModelDefinition definition,+ @Nullable Map<String, String> properties,+ @Nullable Audit auditInfo,+ int revision,+ @Nullable SemanticModel.Status status) {this.name = name;this.comment = comment;this.definition = definition;this.properties = properties == null ? ImmutableMap.of() : ImmutableMap.copyOf(properties);this.auditInfo = auditInfo;+ this.revision = revision;+ this.status = status;}/**@@ -121,4 +138,15 @@ public final class SemanticModelInfo {public Audit auditInfo() {return auditInfo;}++ /** Returns the returned revision number, or zero before a save. */+ public int revision() {+ return revision;+ }++ /** Returns the publication status, or null before a save. */+ @Nullable+ public SemanticModel.Status status() {+ return status;+ }}diff --git a/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.javaindex 19d25a3676..9b2bb1afc7 100644--- a/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java+++ b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java@@ -18,6 +18,8 @@*/package org.apache.gravitino.semantic;+import static org.apache.gravitino.semantic.SemanticModelCatalog.LATEST_REVISION;+import com.google.common.base.Preconditions;/** Selects a snapshot relative to the Semantic Model identity. */@@ -41,6 +43,18 @@ public final class SemanticModelRevisionSelector {return new SemanticModelRevisionSelector(number);}+ /** Returns the selector represented by a REST revision path segment. */+ public static SemanticModelRevisionSelector parse(String revision) {+ if (LATEST_REVISION.equals(revision)) {+ return LATEST;+ }+ try {+ return numbered(Integer.parseInt(revision));+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException("Expected a positive revision number or 'latest'", e);+ }+ }+/*** Returns the revision number or the reserved value for a pointer selector.*diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.javaindex a19f8a500c..3d1e0ba744 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java@@ -77,6 +77,8 @@ import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterFactory;import org.apache.gravitino.storage.relational.database.H2Database;import org.apache.gravitino.storage.relational.po.cache.OperateType;@@ -142,11 +144,34 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationCreturn SchemaMetaService.getInstance().listDescendantSchemas(identifier);}+ @Override+ public SemanticModelEntity loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {+ return SemanticModelMetaService.getInstance().getSemanticModelByIdentifier(ident, selector);+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident)+ throws IOException {+ return SemanticModelMetaService.getInstance().listSemanticModelRevisions(ident);+ }+@Overridepublic List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace) throws IOException {return SemanticModelMetaService.getInstance().listSemanticModelIdentifiers(namespace);}+ @Override+ public SemanticModelEntity updateSemanticModel(+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ boolean rename,+ Function<SemanticModelEntity, SemanticModelEntity> updater)+ throws IOException {+ return SemanticModelMetaService.getInstance()+ .updateSemanticModel(ident, expectedRevision, rename, updater);+ }+@Overridepublic List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {return SemanticModelMetricService.getInstance().listMetrics(namespace);diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.javaindex f3156e1d7c..b7f34fc909 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java@@ -24,6 +24,7 @@ import java.util.List;import java.util.Optional;import java.util.function.Consumer;import java.util.function.Function;+import javax.annotation.Nullable;import org.apache.commons.lang3.tuple.Pair;import org.apache.gravitino.Config;import org.apache.gravitino.Entity;@@ -39,6 +40,8 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.SemanticModelEntity;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;/** Interface defining the operations for a Relation Backend. */public interface RelationalBackend@@ -57,6 +60,18 @@ public interface RelationalBackendreturn get(identifier, Entity.EntityType.TABLE).id();}+ /** Loads a retained Semantic Model snapshot or the latest saved revision. */+ default SemanticModelEntity loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {+ throw new UnsupportedOperationException("Loading Semantic Model revisions is not supported");+ }++ /** Lists retained Semantic Model revision metadata newest first. */+ default SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident)+ throws IOException {+ throw new UnsupportedOperationException("Listing Semantic Model revisions is not supported");+ }+/** Lists model identities for governance, irrespective of publication state. */default List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace)throws IOException {@@ -66,6 +81,16 @@ public interface RelationalBackend.toList();}+ /** Applies a Semantic Model update with an optional revision precondition. */+ default SemanticModelEntity updateSemanticModel(+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ boolean rename,+ Function<SemanticModelEntity, SemanticModelEntity> updater)+ throws IOException {+ return update(ident, Entity.EntityType.SEMANTIC_MODEL, updater);+ }+/*** Reads metric identifiers in a schema without loading complete Semantic Models.*diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.javaindex 4183238a4a..c2baea47e7 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java@@ -71,11 +71,14 @@ import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.DomainEntity;import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.meta.SemanticModelEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.metrics.MetricsSystem;import org.apache.gravitino.metrics.source.EntityChangeLogMetricsSource;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.storage.relational.service.EntityIdService;import org.apache.gravitino.storage.relational.utils.ExceptionUtils;import org.apache.gravitino.tag.TagValue;@@ -259,11 +262,37 @@ public class RelationalEntityStorereturn backend.listDescendantSchemas(identifier);}+ @Override+ public SemanticModelEntity loadSemanticModelRevision(+ NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {+ return backend.loadSemanticModelRevision(ident, selector);+ }++ @Override+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier ident)+ throws IOException {+ return backend.listSemanticModelRevisions(ident);+ }+@Overridepublic List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace) throws IOException {return backend.listSemanticModelIdentifiers(namespace);}+ @Override+ public SemanticModelEntity updateSemanticModel(+ NameIdentifier ident,+ @Nullable Integer expectedRevision,+ boolean rename,+ Function<SemanticModelEntity, SemanticModelEntity> updater)+ throws IOException {+ try {+ return backend.updateSemanticModel(ident, expectedRevision, rename, updater);+ } catch (RuntimeException e) {+ throw ExceptionUtils.lockWaitTimeoutAsConflict(e, Entity.EntityType.SEMANTIC_MODEL, ident);+ }+ }+@Overridepublic List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {return backend.listSemanticModelMetrics(namespace);diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.javaindex cdf36678f9..7877d97a08 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java@@ -32,6 +32,7 @@ import org.apache.ibatis.annotations.ResultMap;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.SelectProvider;+import org.apache.ibatis.annotations.Update;import org.apache.ibatis.annotations.UpdateProvider;/** A MyBatis mapper for Semantic Model identity metadata operations. */@@ -194,6 +195,22 @@ public interface SemanticModelMetaMapper {@Param("newSemanticModelMeta") SemanticModelPO newSemanticModelPO,@Param("oldSemanticModelMeta") SemanticModelPO oldSemanticModelPO);+ /** Renames an identity that still has the observed name and optional expected revision. */+ @Update(+ """+ <script>+ UPDATE semantic_model_meta SET semantic_model_name = #{newName}, audit_info = #{auditInfo}+ WHERE semantic_model_id = #{observed.semanticModelId}+ AND semantic_model_name = #{observed.semanticModelName} AND deleted_at = 0+ <if test="expectedRevision != null">AND current_version = #{expectedRevision}</if>+ </script>+ """)+ int renameSemanticModel(+ @Param("observed") SemanticModelPO observed,+ @Param("newName") String newName,+ @Param("auditInfo") String auditInfo,+ @Param("expectedRevision") @Nullable Integer expectedRevision);+/** Soft-deletes a Semantic Model identity by stable ID and observed name. */@UpdateProvider(type = SemanticModelMetaSQLProviderFactory.class,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.javaindex 8626445843..1e9167b95d 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java@@ -23,6 +23,7 @@ import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.SelectProvider;import org.apache.ibatis.annotations.UpdateProvider;@@ -46,6 +47,17 @@ public interface SemanticModelVersionInfoMapper {SemanticModelVersionInfoPO selectSemanticModelVersionInfoBySemanticModelIdAndVersion(@Param("semanticModelId") Long semanticModelId, @Param("version") Integer version);+ /** Lists the metadata of retained revisions without loading their definitions. */+ @Select(+ """+ SELECT version, publication_status AS publicationStatus, published_by AS publishedBy,+ published_at AS publishedAt, audit_info AS auditInfo+ FROM semantic_model_version_info+ WHERE semantic_model_id = #{modelId} AND deleted_at = 0+ ORDER BY version DESC+ """)+ List<SemanticModelVersionInfoPO> listRevisionInfo(@Param("modelId") long modelId);+/** Soft-deletes all snapshots for a Semantic Model ID. */@UpdateProvider(type = SemanticModelVersionInfoSQLProviderFactory.class,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.javaindex 71890395a8..3ee302e922 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java@@ -177,9 +177,7 @@ public class SemanticModelMetaBaseSQLProvider {@Param("oldSemanticModelMeta") SemanticModelPO oldSemanticModelPO) {return "UPDATE "+ TABLE_NAME- + " SET semantic_model_name = #{newSemanticModelMeta.semanticModelName},"- + " audit_info = #{newSemanticModelMeta.auditInfo},"- + " current_version = #{newSemanticModelMeta.currentVersion},"+ + " SET current_version = #{newSemanticModelMeta.currentVersion},"+ " last_version = #{newSemanticModelMeta.lastVersion}"+ ", active_version = #{newSemanticModelMeta.activeVersion}"+ " WHERE semantic_model_id = #{oldSemanticModelMeta.semanticModelId}"diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.javaindex ec955bfce1..c53aefca09 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java@@ -25,6 +25,7 @@ import static org.apache.gravitino.storage.relational.po.SemanticModelPO.buildSeimport static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;+import com.fasterxml.jackson.core.JsonProcessingException;import com.google.common.base.Preconditions;import com.google.common.collect.Lists;import java.io.IOException;@@ -47,10 +48,12 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchSemanticModelRevisionException;import org.apache.gravitino.exceptions.OptimisticLockException;+import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.meta.SemanticModelEntity;import org.apache.gravitino.metrics.Monitored;import org.apache.gravitino.semantic.Metric;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelRevision;import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSource;import org.apache.gravitino.storage.IdGenerator;@@ -190,6 +193,16 @@ public class SemanticModelMetaService {.toList();}+ /** Lists retained revision metadata newest first. */+ public SemanticModelRevision[] listSemanticModelRevisions(NameIdentifier identifier) {+ long modelId = selectModel(identifier, identityOps).getSemanticModelId();+ return SessionUtils.getWithoutCommit(+ SemanticModelVersionInfoMapper.class, mapper -> mapper.listRevisionInfo(modelId))+ .stream()+ .map(SemanticModelVersionInfoPO::revisionInfo)+ .toArray(SemanticModelRevision[]::new);+ }+/*** Inserts or overwrites a Semantic Model, its snapshot, metric identities, and supplied source* associations atomically.@@ -271,7 +284,20 @@ public class SemanticModelMetaService {baseMetricName = "updateSemanticModel")public <E extends Entity & HasIdentifier> SemanticModelEntity updateSemanticModel(NameIdentifier identifier, Function<E, E> updater) throws IOException {+ return updateSemanticModel(identifier, null, false, updater);+ }++ /**+ * Applies a snapshot update or an identity-only rename with an optional revision precondition.+ */+ public <E extends Entity & HasIdentifier> SemanticModelEntity updateSemanticModel(+ NameIdentifier identifier,+ @Nullable Integer expectedRevision,+ boolean rename,+ Function<E, E> updater)+ throws IOException {SemanticModelPO observed = getSemanticModelPOByIdentifier(identifier);+ checkExpectedRevision(identifier, observed, expectedRevision);SemanticModelEntity oldEntity = fromSemanticModelPO(observed, identifier.namespace());SemanticModelEntity newEntity = (SemanticModelEntity) updater.apply((E) oldEntity);Preconditions.checkArgument(@@ -287,26 +313,25 @@ public class SemanticModelMetaService {SemanticModelMetaMapper.class,mapper -> {lockParent(identifier, observed);+ if (rename || !oldEntity.name().equals(newEntity.name())) {+ Preconditions.checkArgument(+ Objects.equals(oldEntity.comment(), newEntity.comment())+ && oldEntity.properties().equals(newEntity.properties())+ && oldEntity.definition().equals(newEntity.definition())+ && !newEntity.sourceUpdate().replacesSources(),+ "Rename must be the only Semantic Model change");+ return rename(mapper, identifier, observed, newEntity, expectedRevision);+ }SemanticModelPO next = updateSemanticModelPO(observed, newEntity);if (mapper.updateSemanticModelMeta(next, observed) != 1) {throw semanticModelWriteFailure(identifier, observed);}- if (!Objects.equals(- observed.getSemanticModelVersionInfoPO().metrics(),- next.getSemanticModelVersionInfoPO().metrics())- && !metricNames(oldEntity.definition())- .equals(metricNames(newEntity.definition()))) {- reconcileMetricIdentities(next, metricNames(newEntity.definition()));- }+ reconcileMetricIdentities(next, metricNames(newEntity.definition()));replaceSources(next, newEntity);SessionUtils.doWithoutCommit(SemanticModelVersionInfoMapper.class,versions ->versions.insertSemanticModelVersionInfo(next.getSemanticModelVersionInfoPO()));- if (!observed.getSemanticModelName().equals(next.getSemanticModelName())) {- EntityChangeLogWriter.append(- identifier, Entity.EntityType.SEMANTIC_MODEL, OperateType.ALTER);- }return fromSemanticModelPO(next, identifier.namespace());});} catch (RuntimeException e) {@@ -606,6 +631,39 @@ public class SemanticModelMetaService {return po;}+ private SemanticModelEntity rename(+ SemanticModelMetaMapper mapper,+ NameIdentifier identifier,+ SemanticModelPO observed,+ SemanticModelEntity renamed,+ @Nullable Integer expectedRevision) {+ String audit;+ try {+ audit = JsonUtils.anyFieldMapper().writeValueAsString(renamed.auditInfo());+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Failed to serialize Semantic Model identity audit", e);+ }+ if (mapper.renameSemanticModel(observed, renamed.name(), audit, expectedRevision) != 1) {+ throw semanticModelWriteFailure(identifier, observed);+ }+ if (!observed.getSemanticModelName().equals(renamed.name())) {+ EntityChangeLogWriter.append(identifier, Entity.EntityType.SEMANTIC_MODEL, OperateType.ALTER);+ }+ SemanticModelPO latest =+ mapper.selectSemanticModelMetaById(observed.getSemanticModelId(), LATEST);+ requireSnapshot(latest, latest.getCurrentVersion(), "latest");+ return fromSemanticModelPO(latest, identifier.namespace());+ }++ private static void checkExpectedRevision(+ NameIdentifier identifier, SemanticModelPO model, @Nullable Integer expectedRevision) {+ if (expectedRevision != null && !expectedRevision.equals(model.getCurrentVersion())) {+ throw new OptimisticLockException(+ "Semantic Model %s is at revision %s, expected %s",+ identifier, model.getCurrentVersion(), expectedRevision);+ }+ }+private static void lockParent(NameIdentifier identifier, SemanticModelPO observed) {SchemaMetaService.getInstance().lockSchemaForEntityWrite(diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.javaindex 5dfd980bb1..c57f6ffd46 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java@@ -28,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.inOrder;@@ -141,6 +142,7 @@ public class TestManagedSemanticModelOperations {operations.alterSemanticModel(IDENT,missing,+ 1,SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.replaceDefinition(definition)));assertSame(original, operations.loadSemanticModel(IDENT));@@ -238,11 +240,15 @@ public class TestManagedSemanticModelOperations {NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "renamed_sales_model");SemanticModelDefinition replacement = definition("invoices");+ operations.alterSemanticModel(+ IDENT,+ SemanticModelSourceUpdate.preserve(),+ SemanticModelChange.rename(renamedIdent.name()));SemanticModel altered =operations.alterSemanticModel(- IDENT,+ renamedIdent,sources(replacement),- SemanticModelChange.rename(renamedIdent.name()),+ 1,SemanticModelChange.updateComment("Updated"),SemanticModelChange.setProperty("tier", "gold"),SemanticModelChange.removeProperty("domain"),@@ -298,7 +304,7 @@ public class TestManagedSemanticModelOperations {SemanticModelDefinition accepted = definition("accepted");operations.alterSemanticModel(- IDENT, sources(accepted), SemanticModelChange.replaceDefinition(accepted));+ IDENT, sources(accepted), 3, SemanticModelChange.replaceDefinition(accepted));assertEquals(2, writeValidationCount.get());SemanticModelDefinition duplicateDatasets =@@ -311,6 +317,7 @@ public class TestManagedSemanticModelOperations {operations.alterSemanticModel(IDENT,sources(duplicateDatasets),+ 4,SemanticModelChange.replaceDefinition(duplicateDatasets)));assertEquals(2, writeValidationCount.get());assertEquals(accepted, operations.loadSemanticModel(IDENT).definition());@@ -323,6 +330,7 @@ public class TestManagedSemanticModelOperations {operations.alterSemanticModel(IDENT,sources(definition("blocked")),+ 4,SemanticModelChange.replaceDefinition(definition("blocked")))));assertEquals(3, writeValidationCount.get());assertEquals(accepted, operations.loadSemanticModel(IDENT).definition());@@ -402,6 +410,7 @@ public class TestManagedSemanticModelOperations {operations.alterSemanticModel(IDENT,sources(second),+ 1,SemanticModelChange.replaceDefinition(first),SemanticModelChange.replaceDefinition(second));assertEquals(second, altered.definition());@@ -419,6 +428,7 @@ public class TestManagedSemanticModelOperations {operations.alterSemanticModel(IDENT,sources(second),+ altered.revision(),SemanticModelChange.replaceDefinition(invalid),SemanticModelChange.replaceDefinition(definition("orders"))));assertEquals(3, writeValidationCount.get());@@ -444,14 +454,18 @@ public class TestManagedSemanticModelOperations {SemanticModelDefinition replacement = definition("invoices");NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "validated_after_replace");+ operations.alterSemanticModel(+ IDENT,+ SemanticModelSourceUpdate.preserve(),+ SemanticModelChange.rename(renamedIdent.name()));SemanticModel altered =operations.alterSemanticModel(- IDENT,+ renamedIdent,sources(replacement),+ 1,SemanticModelChange.replaceDefinition(replacement),SemanticModelChange.setProperty("owner", "analytics"),- SemanticModelChange.updateComment("Updated after replacement"),- SemanticModelChange.rename(renamedIdent.name()));+ SemanticModelChange.updateComment("Updated after replacement"));assertEquals(2, writeValidationCount.get());assertEquals(renamedIdent, validatedIdent.get());@@ -571,8 +585,7 @@ public class TestManagedSemanticModelOperations {doThrow(new NoSuchEntityException("Missing model")).when(store)- .update(- eq(IDENT), eq(SemanticModelEntity.class), eq(Entity.EntityType.SEMANTIC_MODEL), any());+ .updateSemanticModel(eq(IDENT), eq(null), anyBoolean(), any());assertThrows(NoSuchSemanticModelException.class,() ->@@ -582,8 +595,7 @@ public class TestManagedSemanticModelOperations {SemanticModelChange.setProperty("key", "value")));doThrow(new EntityAlreadyExistsException("Rename conflict")).when(store)- .update(- eq(IDENT), eq(SemanticModelEntity.class), eq(Entity.EntityType.SEMANTIC_MODEL), any());+ .updateSemanticModel(eq(IDENT), eq(null), anyBoolean(), any());assertThrows(SemanticModelAlreadyExistsException.class,() ->@@ -594,8 +606,7 @@ public class TestManagedSemanticModelOperations {IOException updateFailure = new IOException("Update failed");doThrow(updateFailure).when(store)- .update(- eq(IDENT), eq(SemanticModelEntity.class), eq(Entity.EntityType.SEMANTIC_MODEL), any());+ .updateSemanticModel(eq(IDENT), eq(null), anyBoolean(), any());assertSame(updateFailure,assertThrows(diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.javaindex a8767f5653..5fd09a5ebb 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java@@ -32,6 +32,7 @@ import java.io.IOException;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;+import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.Set;@@ -46,6 +47,8 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.cache.NoOpsCache;import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;import org.apache.gravitino.meta.SemanticModelEntity;import org.apache.gravitino.meta.TableEntity;@@ -56,6 +59,8 @@ import org.apache.gravitino.semantic.Relationship;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSource;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.storage.RandomIdGenerator;@@ -136,10 +141,6 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {assertNotSame(created, loaded);assertEquals(created, loaded);- assertEquals(1, loaded.revision());- assertEquals(SemanticModel.Status.PUBLISHED, loaded.status());- assertEquals(loaded.auditInfo().creator(), loaded.publishedBy());- assertEquals(loaded.auditInfo().createTime(), loaded.publishedAt());assertEquals(definition, loaded.definition());assertEquals(1, writeValidationCount.get());assertTrue(backend.exists(modelIdent, Entity.EntityType.SEMANTIC_MODEL));@@ -163,18 +164,20 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {NameIdentifier renamedIdent = NameIdentifier.of(modelIdent.namespace(), "renamed_sales_model");SemanticModelDefinition replacement = definition("invoices");+ operations.alterSemanticModel(+ modelIdent,+ SemanticModelSourceUpdate.preserve(),+ SemanticModelChange.rename(renamedIdent.name()));SemanticModel altered =operations.alterSemanticModel(- modelIdent,+ renamedIdent,sources(replacement),- SemanticModelChange.rename(renamedIdent.name()),+ 1,SemanticModelChange.updateComment("Updated"),SemanticModelChange.removeProperty("domain"),SemanticModelChange.setProperty("tier", "gold"),SemanticModelChange.replaceDefinition(replacement));- assertEquals(2, altered.revision());- assertEquals(SemanticModel.Status.PUBLISHED, altered.status());assertEquals(renamedIdent.name(), altered.name());assertEquals("Updated", altered.comment());assertEquals(replacement, altered.definition());@@ -226,6 +229,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {operations.alterSemanticModel(modelIdent,sources(duplicateDatasets),+ 1,SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.setProperty("owner", "changed"),SemanticModelChange.replaceDefinition(duplicateDatasets)));@@ -280,7 +284,10 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {operations.alterSemanticModel(modelIdent,SemanticModelSourceUpdate.preserve(),- SemanticModelChange.rename(renamedIdent.name()),+ SemanticModelChange.rename(renamedIdent.name()));+ operations.alterSemanticModel(+ renamedIdent,+ SemanticModelSourceUpdate.preserve(),SemanticModelChange.updateComment("updated after deletion"),SemanticModelChange.setProperty("owner", "analytics"));assertEquals(original, liveAssociations(created.id()));@@ -296,6 +303,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {operations.alterSemanticModel(renamedIdent,SemanticModelSourceUpdate.preserve(),+ 1,SemanticModelChange.replaceDefinition(definition)));assertThrows(IllegalArgumentException.class,@@ -306,7 +314,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {// Explicit replacement rebinds the source even though the definition is unchanged.operations.alterSemanticModel(- renamedIdent, rebound, SemanticModelChange.replaceDefinition(definition));+ renamedIdent, rebound, 2, SemanticModelChange.replaceDefinition(definition));assertEquals(rebound.sources(),liveAssociations(created.id()).stream().map(Association::source).toList());@@ -350,7 +358,10 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {assertNotEquals(source.id(), recreated.id());operations.alterSemanticModel(- modelIdent, resolvedUpdate, SemanticModelChange.replaceDefinition(replacementDefinition));+ modelIdent,+ resolvedUpdate,+ 1,+ SemanticModelChange.replaceDefinition(replacementDefinition));assertEquals(replacementDefinition, operations.loadSemanticModel(modelIdent).definition());assertEquals(@@ -359,6 +370,85 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {assertEquals(2, writeValidationCount.get());}+ @TestTemplate+ void testRevisionHistoryAndConditionalAlter() {+ SemanticModelDefinition original = definition("orders");+ SemanticModel created =+ operations.createSemanticModel(+ modelIdent, "Original", original, Map.of(), sources(original));+ assertEquals(1, created.revision());+ assertEquals(SemanticModel.Status.PUBLISHED, created.status());+ assertEquals(created.auditInfo().creator(), created.publishedBy());+ assertEquals(created.auditInfo().createTime(), created.publishedAt());++ SemanticModelDefinition replacement = definition("invoices");+ SemanticModelChange change = SemanticModelChange.replaceDefinition(replacement);+ assertThrows(+ IllegalArgumentException.class,+ () -> operations.alterSemanticModel(modelIdent, sources(replacement), change));+ assertThrows(+ IllegalArgumentException.class,+ () -> operations.alterSemanticModel(modelIdent, sources(replacement), 0, change));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ operations.alterSemanticModel(+ modelIdent,+ sources(replacement),+ created.revision(),+ change,+ SemanticModelChange.rename("invalid")));+ assertArrayEquals(new int[] {1}, revisionNumbers(operations, modelIdent));++ SemanticModel saved =+ operations.alterSemanticModel(modelIdent, sources(replacement), created.revision(), change);+ assertEquals(2, saved.revision());+ assertEquals(saved.auditInfo().lastModifiedTime(), saved.publishedAt());+ assertThrows(+ OptimisticLockException.class,+ () ->+ operations.alterSemanticModel(+ modelIdent, sources(replacement), created.revision(), change));+ assertEquals(saved, operations.loadSemanticModel(modelIdent));+ assertEquals(+ saved,+ operations.loadSemanticModelRevision(modelIdent, SemanticModelRevisionSelector.LATEST));+ assertArrayEquals(new int[] {2, 1}, revisionNumbers(operations, modelIdent));++ NameIdentifier renamed = NameIdentifier.of(modelIdent.namespace(), "renamed");+ assertThrows(+ OptimisticLockException.class,+ () ->+ operations.alterSemanticModel(+ modelIdent,+ SemanticModelSourceUpdate.preserve(),+ 1,+ SemanticModelChange.rename(renamed.name())));+ assertEquals(+ 2,+ operations+ .alterSemanticModel(+ modelIdent,+ SemanticModelSourceUpdate.preserve(),+ 2,+ SemanticModelChange.rename(renamed.name()))+ .revision());+ assertThrows(+ NoSuchSemanticModelException.class, () -> operations.loadSemanticModel(modelIdent));+ SemanticModel r1 =+ operations.loadSemanticModelRevision(renamed, SemanticModelRevisionSelector.numbered(1));+ assertEquals(renamed.name(), r1.name());+ assertEquals(original, r1.definition());+ assertArrayEquals(new int[] {2, 1}, revisionNumbers(operations, renamed));+ }++ private static int[] revisionNumbers(+ ManagedSemanticModelOperations managed, NameIdentifier ident) {+ return Arrays.stream(managed.listSemanticModelRevisions(ident))+ .mapToInt(SemanticModelRevision::revision)+ .toArray();+ }+private static Set<String> metricIdentities(long modelId) {return SessionUtils.getWithoutCommit(SemanticModelMetricMapper.class,diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.javaindex b0c09b2e46..c51b9be8db 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java@@ -35,6 +35,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelCatalog;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.junit.jupiter.api.Test;@@ -69,7 +70,11 @@ public class TestSemanticModelDispatcher {void testExportRequiresAnExplicitImplementation() throws NoSuchMethodException {assertFalse(SemanticModelDispatcher.class- .getMethod("exportOssieDocument", NameIdentifier.class, OssieFormat.class)+ .getMethod(+ "exportSemanticModel",+ NameIdentifier.class,+ SemanticModelRevisionSelector.class,+ OssieFormat.class).isDefault());}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.javaindex 9c780c5524..e9a4c37847 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java@@ -52,6 +52,7 @@ import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -176,14 +177,14 @@ public class TestSemanticModelNormalizeDispatcher {SemanticModel model = mock(SemanticModel.class);SemanticModelChange rename = SemanticModelChange.rename("RevenueModel");when(delegate.alterSemanticModel(- NORMALIZED_IDENT, SemanticModelSourceUpdate.preserve(), rename))+ NORMALIZED_IDENT, null, SemanticModelSourceUpdate.preserve(), rename)).thenReturn(model);assertEquals(model,dispatcher.alterSemanticModel(INPUT_IDENT, SemanticModelSourceUpdate.preserve(), rename));verify(delegate)- .alterSemanticModel(NORMALIZED_IDENT, SemanticModelSourceUpdate.preserve(), rename);+ .alterSemanticModel(NORMALIZED_IDENT, null, SemanticModelSourceUpdate.preserve(), rename);NameIdentifier invalidIdent = NameIdentifier.of(INPUT_NAMESPACE, "invalid model");assertThrows(@@ -248,11 +249,15 @@ public class TestSemanticModelNormalizeDispatcher {@Testpublic void testOssieExportNormalizesAndForwardsWithoutLoading() {OssieDocument document = OssieDocument.json("{}");- when(delegate.exportOssieDocument(NORMALIZED_IDENT, OssieFormat.JSON)).thenReturn(document);+ when(delegate.exportSemanticModel(+ eq(NORMALIZED_IDENT), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.JSON)))+ .thenReturn(new SemanticModelDispatcher.SemanticModelExport(document, 1));assertSame(document, dispatcher.exportOssieDocument(INPUT_IDENT, OssieFormat.JSON));- verify(delegate).exportOssieDocument(NORMALIZED_IDENT, OssieFormat.JSON);+ verify(delegate)+ .exportSemanticModel(+ eq(NORMALIZED_IDENT), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.JSON));verifyNoMoreInteractions(delegate);}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.javaindex 6e2c3c57a4..5b32d9643a 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java@@ -191,6 +191,7 @@ public class TestSemanticModelOperationDispatcher {() ->dispatcher.alterSemanticModel(MODEL_IDENT,+ 1,sources(definitionWithReservedExtension()),SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.setProperty("owner", "changed"),@@ -270,17 +271,22 @@ public class TestSemanticModelOperationDispatcher {dispatcher.alterSemanticModel(MODEL_IDENT,SemanticModelSourceUpdate.preserve(),- SemanticModelChange.rename("renamed_sales_model"),- SemanticModelChange.updateComment("Updated"));+ SemanticModelChange.rename("renamed_sales_model"));NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, renamed.name());+ SemanticModel updated =+ dispatcher.alterSemanticModel(+ renamedIdent,+ SemanticModelSourceUpdate.preserve(),+ SemanticModelChange.updateComment("Updated"));assertEquals(Map.of("owner", "analytics", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION),propertyUpdated.properties());- assertEquals("Updated", renamed.comment());+ assertEquals("Updated", updated.comment());SemanticModel replaced =dispatcher.alterSemanticModel(renamedIdent,+ updated.revision(),sources(validDefinition()),SemanticModelChange.replaceDefinition(validDefinition()));assertEquals(2, replaced.definition().datasets().length);@@ -315,8 +321,8 @@ public class TestSemanticModelOperationDispatcher {() ->dispatcher.alterSemanticModel(MODEL_IDENT,+ 1,sources(invalidReplacement),- SemanticModelChange.rename("must_not_persist"),SemanticModelChange.updateComment("Must not persist"),SemanticModelChange.setProperty("owner", "changed"),SemanticModelChange.replaceDefinition(invalidReplacement)));diff --git a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.javaindex 287ae2217a..4cfe1baa98 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java@@ -285,7 +285,9 @@ public class TestSemanticModelHookDispatcher {Namespace namespace = Namespace.of("metalake1", "catalog1", "schema1");Mockito.when(dispatcher.listSemanticModels(namespace)).thenReturn(listed);Mockito.when(dispatcher.loadSemanticModel(IDENT)).thenReturn(loaded);- Mockito.when(dispatcher.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), change))+ Mockito.when(+ dispatcher.alterSemanticModel(+ IDENT, null, SemanticModelSourceUpdate.preserve(), change)).thenReturn(altered);Mockito.when(dispatcher.dropSemanticModel(IDENT)).thenReturn(true);Mockito.when(dispatcher.semanticModelExists(IDENT)).thenReturn(true);@@ -316,7 +318,9 @@ public class TestSemanticModelHookDispatcher {GravitinoEnv env = Mockito.mock(GravitinoEnv.class);Mockito.when(env.gravitinoAuthorizer()).thenReturn(authorizer);SemanticModelChange rename = SemanticModelChange.rename("renamed");- Mockito.when(dispatcher.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), rename))+ Mockito.when(+ dispatcher.alterSemanticModel(+ IDENT, null, SemanticModelSourceUpdate.preserve(), rename)).thenThrow(new IllegalArgumentException("rejected"));try (MockedStatic<GravitinoEnv> mocked = Mockito.mockStatic(GravitinoEnv.class)) {mocked.when(GravitinoEnv::getInstance).thenReturn(env);diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.javaindex 4d0e30d1d4..5f8c0a3d19 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java@@ -556,7 +556,11 @@ public class TestSemanticModelEvent {new NameIdentifier[] {NameIdentifier.of(NAMESPACE, "model1"), NameIdentifier.of(NAMESPACE, "model2")});- when(d.alterSemanticModel(any(NameIdentifier.class), any(), any(SemanticModelChange.class)))+ when(d.alterSemanticModel(+ any(NameIdentifier.class),+ any(),+ any(SemanticModelSourceUpdate.class),+ any(SemanticModelChange.class))).thenReturn(semanticModel);return d;}diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.javaindex 8356a93f05..ee4bb712ee 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java@@ -109,9 +109,10 @@ class TestSemanticModelImportExportEvent {owners = mock(OwnerDispatcher.class);operation = mock(SemanticModelOperationDispatcher.class);doCallRealMethod().when(operation).importSemanticModel(any(), any(), any(), any(), any());- doCallRealMethod().when(operation).exportOssieDocument(any(), any());+ doCallRealMethod().when(operation).exportSemanticModel(any(), any(), any());model = mock(SemanticModel.class);when(model.name()).thenReturn(IDENT.name());+ when(model.revision()).thenReturn(7);when(model.definition()).thenReturn(definition());when(model.properties()).thenReturn(Map.of());when(operation.createSemanticModel(any(), any(), any(), any(), any())).thenReturn(model);@@ -323,6 +324,8 @@ class TestSemanticModelImportExportEvent {assertEquals(format, pre.format());assertEquals(IDENT, event.identifier());assertEquals(format, event.format());+ assertEquals(7, event.revision());+ assertEquals("7", event.customInfo().get("revision"));assertAudit(event, AuditLog.Operation.EXPORT_SEMANTIC_MODEL, OperationStatus.SUCCESS);}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.javaindex 8d99a71e8f..c6574ac9c0 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java@@ -634,9 +634,12 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {SemanticModelEntity renamed =semanticModel(original.id(), namespace, "renamed_sales_model", false, original.properties());- backend.update(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, ignored -> renamed);+ assertEquals(+ renamed,+ backend.update(+ original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, ignored -> renamed));assertFalse(backend.exists(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));- assertSnapshot(renamed, 2);+ assertEquals(renamed, backend.get(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));assertTrue(backend.delete(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, false));assertFalse(backend.exists(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.javaindex 2952e67277..17be666231 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java@@ -156,7 +156,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {}@TestTemplate- public void testUpdateAndRenameCreatePublishedSnapshots() throws IOException {+ public void testUpdateCreatesSnapshotAndRenameOnlyUpdatesIdentity() throws IOException {String oldName = GravitinoITUtils.genRandomName("sales_model_old");String newName = GravitinoITUtils.genRandomName("sales_model_new");SemanticModelEntity original =@@ -177,7 +177,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {semanticModelEntity(original.id(), newName, "orders_v2", "v2 comment", "v2");SemanticModelMetaService service = SemanticModelMetaService.getInstance();assertEquals(- 3, service.updateSemanticModel(original.nameIdentifier(), ignored -> renamed).revision());+ 2, service.updateSemanticModel(original.nameIdentifier(), ignored -> renamed).revision());assertEquals(newName,service@@ -198,18 +198,17 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {.getSemanticModelIdBySchemaIdAndName(schemaId, newName));Map<Integer, VersionState> versions = listSemanticModelVersions(original.id());- assertEquals(3, versions.size());+ assertEquals(2, versions.size());assertEquals("v1 comment", versions.get(1).comment);assertTrue(versions.get(1).datasets.contains("orders_v1"));assertEquals("v2 comment", versions.get(2).comment);assertTrue(versions.get(2).datasets.contains("orders_v2"));assertEquals(0L, versions.get(1).deletedAt);assertEquals(0L, versions.get(2).deletedAt);- assertEquals(0L, versions.get(3).deletedAt);long[] identityVersions = semanticModelIdentityVersions(original.id());- assertEquals(3L, identityVersions[0]);- assertEquals(3L, identityVersions[1]);+ assertEquals(2L, identityVersions[0]);+ assertEquals(2L, identityVersions[1]);assertEntityChange(lastChangeId, oldName, OperateType.ALTER);}@@ -481,7 +480,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {() -> service.deleteObservedSemanticModel(original.nameIdentifier(), observed));assertEquals("original", service.getSemanticModelByIdentifier(renamed.nameIdentifier()).comment());- assertEquals(2, listSemanticModelVersions(original.id()).size());+ assertEquals(1, listSemanticModelVersions(original.id()).size());}@TestTemplatediff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.javaindex ba4be67440..f72355c574 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java@@ -113,10 +113,10 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {}SemanticModelEntity loaded = backend.get(renamed.nameIdentifier(), renamed.type());assertEquals(renamed.fields(), loaded.fields());- assertEquals(3, loaded.revision());+ assertEquals(2, loaded.revision());assertEquals(- 3, service().getSemanticModelPOByIdentifier(renamed.nameIdentifier()).getCurrentVersion());- assertEquals(3, count("semantic_model_version_info", original.id()));+ 2, service().getSemanticModelPOByIdentifier(renamed.nameIdentifier()).getCurrentVersion());+ assertEquals(2, count("semantic_model_version_info", original.id()));assertEquals(initial, liveIds(original.id()));assertEquals(4, count("semantic_model_metric_meta", original.id()));diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.javaindex e799c7cf97..39a521ef75 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java@@ -152,7 +152,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {assertEquals(initial, rows(original.id()));SemanticModelEntity loaded = service().getSemanticModelByIdentifier(renamed.nameIdentifier());assertEquals(renamed.fields(), loaded.fields());- assertEquals(3, loaded.revision());+ assertEquals(2, loaded.revision());SemanticModelSourceUpdate rebound =SemanticModelSourceUpdate.replace(@@ -163,7 +163,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {old -> copy(renamed, renamed.name(), renamed.definition(), rebound));assertEquals(Set.copyOf(rebound.sources()), sourceSet(original.id()));assertEquals(2, rows(original.id()).size());- assertEquals(4, rows(original.id()).get(0).toVersion());+ assertEquals(3, rows(original.id()).get(0).toVersion());assertEquals(0, rows(original.id()).get(0).deletedAt());}diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_semantic_model_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_semantic_model_operation.pyindex c0fe6d05e5..7f54f7c204 100644--- a/mcp-server/mcp_server/client/plain/plain_rest_client_semantic_model_operation.py+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_semantic_model_operation.py@@ -15,7 +15,7 @@# specific language governing permissions and limitations# under the License.-from typing import Optional+from typing import Literal, Optionalfrom httpx import AsyncClient@@ -83,13 +83,33 @@ class PlainRESTClientSemanticModelOperation(SemanticModelOperation):return extract_list_from_response(response, "metrics")async def load_semantic_model(- self, catalog_name: str, schema_name: str, semantic_model_name: str+ self,+ catalog_name: str,+ schema_name: str,+ semantic_model_name: str,+ revision: Optional[int | Literal["latest"]] = None,) -> str:- response = await self.rest_client.get(- self._model_path(catalog_name, schema_name, semantic_model_name)- )+ path = self._model_path(catalog_name, schema_name, semantic_model_name)+ if revision is not None:+ if revision != "latest" and (+ not isinstance(revision, int)+ or isinstance(revision, bool)+ or revision <= 0+ ):+ raise ValueError(+ "Revision must be a positive integer or 'latest'"+ )+ path += f"/revisions/{revision}"+ response = await self.rest_client.get(path)return extract_content_from_response(response, "semanticModel", {})+ async def list_semantic_model_revisions(+ self, catalog_name: str, schema_name: str, semantic_model_name: str+ ) -> str:+ path = self._model_path(catalog_name, schema_name, semantic_model_name)+ response = await self.rest_client.get(f"{path}/revisions")+ return extract_list_from_response(response, "revisions")+# pylint: disable=too-many-positional-argumentsasync def create_semantic_model(self,@@ -116,10 +136,15 @@ class PlainRESTClientSemanticModelOperation(SemanticModelOperation):schema_name: str,semantic_model_name: str,updates: list[dict],+ *,+ expected_revision: Optional[int] = None,) -> str:+ body = {"updates": updates}+ if expected_revision is not None:+ body["expectedRevision"] = expected_revisionresponse = await self.rest_client.put(self._model_path(catalog_name, schema_name, semantic_model_name),- json={"updates": updates},+ json=body,)return extract_content_from_response(response, "semanticModel", {})diff --git a/mcp-server/mcp_server/client/semantic_model_operation.py b/mcp-server/mcp_server/client/semantic_model_operation.pyindex dd958be727..9b3b0e011c 100644--- a/mcp-server/mcp_server/client/semantic_model_operation.py+++ b/mcp-server/mcp_server/client/semantic_model_operation.py@@ -16,7 +16,7 @@# under the License.from abc import ABC, abstractmethod-from typing import Optional+from typing import Literal, Optionalclass SemanticModelOperation(ABC):@@ -54,9 +54,20 @@ class SemanticModelOperation(ABC):@abstractmethodasync def load_semantic_model(+ self,+ catalog_name: str,+ schema_name: str,+ semantic_model_name: str,+ revision: Optional[int | Literal["latest"]] = None,+ ) -> str:+ """Return the selected Semantic Model revision and definition as JSON."""+ pass++ @abstractmethod+ async def list_semantic_model_revisions(self, catalog_name: str, schema_name: str, semantic_model_name: str) -> str:- """Return the Semantic Model's metadata and definition as JSON."""+ """Return retained, visible revision summaries as JSON."""pass# pylint: disable=too-many-positional-arguments@@ -80,6 +91,8 @@ class SemanticModelOperation(ABC):schema_name: str,semantic_model_name: str,updates: list[dict],+ *,+ expected_revision: Optional[int] = None,) -> str:"""Apply native REST update operations atomically and return JSON."""passdiff --git a/mcp-server/mcp_server/tools/semantic_model.py b/mcp-server/mcp_server/tools/semantic_model.pyindex 972a491132..7a8c5e821e 100644--- a/mcp-server/mcp_server/tools/semantic_model.py+++ b/mcp-server/mcp_server/tools/semantic_model.py@@ -19,6 +19,7 @@ from typing import Literal, Optionalfrom fastmcp import Context, FastMCPfrom mcp.types import ToolAnnotations+from pydantic import StrictIntdef load_semantic_model_tools(mcp: FastMCP):@@ -119,6 +120,7 @@ def load_semantic_model_tools(mcp: FastMCP):catalog_name: str,schema_name: str,semantic_model_name: str,+ revision: Optional[int | Literal["latest"]] = None,) -> str:"""Load a Semantic Model's metadata and complete semantic definition.@@ -127,13 +129,36 @@ def load_semantic_model_tools(mcp: FastMCP):catalog_name: Name of the catalog.schema_name: Name of the schema.semantic_model_name: Name of the Semantic Model.+ revision: A positive revision number or "latest". Omit for active.Returns:- A JSON object containing name, comment, definition, properties,- and audit information in Gravitino's native REST format.+ The definition and audit information, including revision, status,+ and publishedBy and publishedAt for a published revision."""client = ctx.request_context.lifespan_context.rest_client()return await client.as_semantic_model_operation().load_semantic_model(+ catalog_name, schema_name, semantic_model_name, revision+ )++ @mcp.tool(+ tags={"semantic_model"},+ annotations=ToolAnnotations(+ readOnlyHint=True, destructiveHint=False, idempotentHint=True+ ),+ )+ async def list_semantic_model_revisions(+ ctx: Context,+ catalog_name: str,+ schema_name: str,+ semantic_model_name: str,+ ) -> str:+ """List retained revisions of a Semantic Model, newest first.++ Each summary reports the revision number, publication status, writer audit,+ and publisher and time when published. Drafts require modify access.+ """+ client = ctx.request_context.lifespan_context.rest_client()+ return await client.as_semantic_model_operation().list_semantic_model_revisions(catalog_name, schema_name, semantic_model_name)@@ -160,8 +185,7 @@ def load_semantic_model_tools(mcp: FastMCP):dots. The REST source lookup route uses catalog.schema.name withoutcomponent escaping; these inputs are rejected before sending a request.- Associations reflect the latest definition write, not model execution- validity or transitive dependencies. An empty result does not establish+ Associations reflect the active revision and cover direct dependencies. An empty result does not establishthat changing or deleting the source is safe.Args:@@ -213,7 +237,7 @@ def load_semantic_model_tools(mcp: FastMCP):properties: Optional Gravitino properties with string values.Returns:- The created Semantic Model as a JSON object.+ The created Semantic Model as JSON, including its revision and status."""client = ctx.request_context.lifespan_context.rest_client()return await client.as_semantic_model_operation().create_semantic_model(@@ -227,6 +251,8 @@ def load_semantic_model_tools(mcp: FastMCP):schema_name: str,semantic_model_name: str,updates: list[dict],+ *,+ expected_revision: Optional[StrictInt] = None,) -> str:"""Apply an ordered, non-empty list of updates atomically.@@ -241,14 +267,21 @@ def load_semantic_model_tools(mcp: FastMCP):or replaceDefinition (definition). Example:[{"@type": "setProperty", "property": "domain","value": "sales"}]. replaceDefinition supplies the entire- definition and revalidates source access.+ definition and revalidates source access. Send rename by itself.+ expected_revision: Required for replaceDefinition. Load "latest" to+ prepare an edit and use its revision. On a conflict, reload,+ reapply your changes to the new latest revision, and retry.Returns:- The altered Semantic Model as a JSON object.+ The altered Semantic Model as JSON, including its revision and status."""client = ctx.request_context.lifespan_context.rest_client()return await client.as_semantic_model_operation().alter_semantic_model(- catalog_name, schema_name, semantic_model_name, updates+ catalog_name,+ schema_name,+ semantic_model_name,+ updates,+ expected_revision=expected_revision,)@mcp.tool(tags={"semantic_model"})diff --git a/mcp-server/tests/integration/test_semantic_model_metric_discovery.py b/mcp-server/tests/integration/test_semantic_model_metric_discovery.pyindex 09e5c4ab37..2951d1398b 100644--- a/mcp-server/tests/integration/test_semantic_model_metric_discovery.py+++ b/mcp-server/tests/integration/test_semantic_model_metric_discovery.py@@ -320,19 +320,28 @@ class TestSemanticModelMetricDiscovery:},"aiContext": "Updated",}+ sales_path = fixture.models_path + "/sales"+ latest = fixture.request("GET", sales_path + "/revisions/latest")[+ "semanticModel"+ ]fixture.request("PUT",- fixture.models_path + "/sales",+ sales_path,{+ "expectedRevision": latest["revision"],"updates": [{"@type": "replaceDefinition","definition": fixture.definition([changed]),- },- {"@type": "rename", "newName": "renamed"},- ]+ }+ ],},)+ fixture.request(+ "PUT",+ sales_path,+ {"updates": [{"@type": "rename", "newName": "renamed"}]},+ )fixture.assert_discovery([fixture.info("renamed", changed)])fixture.request("DELETE", fixture.models_path + "/renamed")fixture.assert_discovery([])diff --git a/mcp-server/tests/unit/tools/mock_operation.py b/mcp-server/tests/unit/tools/mock_operation.pyindex 0021751269..a28a7cf5d7 100644--- a/mcp-server/tests/unit/tools/mock_operation.py+++ b/mcp-server/tests/unit/tools/mock_operation.py@@ -521,10 +521,19 @@ class MockSemanticModelOperation(SemanticModelOperation):return "[]"async def load_semantic_model(- self, catalog_name: str, schema_name: str, semantic_model_name: str+ self,+ catalog_name: str,+ schema_name: str,+ semantic_model_name: str,+ revision=None,) -> str:return '{"name": "mock_semantic_model"}'+ async def list_semantic_model_revisions(+ self, catalog_name: str, schema_name: str, semantic_model_name: str+ ) -> str:+ return "[]"+# pylint: disable=too-many-positional-argumentsasync def create_semantic_model(self,@@ -543,6 +552,8 @@ class MockSemanticModelOperation(SemanticModelOperation):schema_name: str,semantic_model_name: str,updates: list[dict],+ *,+ expected_revision: Optional[int] = None,) -> str:return '{"name": "mock_semantic_model"}'diff --git a/mcp-server/tests/unit/tools/test_semantic_model.py b/mcp-server/tests/unit/tools/test_semantic_model.pyindex d1a8e03679..a2b012c07d 100644--- a/mcp-server/tests/unit/tools/test_semantic_model.py+++ b/mcp-server/tests/unit/tools/test_semantic_model.py@@ -548,24 +548,67 @@ class TestSemanticModelTool(unittest.IsolatedAsyncioTestCase):{**required, **expected},)+ async def test_revision_reads_and_history(self):+ self.model.update(+ revision=2,+ status="PUBLISHED",+ publishedBy="reviewer",+ publishedAt="2026-01-02T00:00:00Z",+ )+ for revision in (2, "latest"):+ result = await self._call(+ "load_semantic_model", {**_MODEL_ARGS, "revision": revision}+ )+ self.assertEqual(result, self.model)+ self._assert_request(+ "GET", f"{_MODELS_PATH}/sales_model/revisions/{revision}"+ )++ revisions = [+ {+ "revision": 2,+ "status": "PUBLISHED",+ "audit": {"creator": "writer"},+ }+ ]+ self.response = {"code": 0, "revisions": revisions}+ result = await self._call("list_semantic_model_revisions", _MODEL_ARGS)+ self.assertEqual(revisions, result)+ self._assert_request("GET", f"{_MODELS_PATH}/sales_model/revisions")+async def test_alter_semantic_model_preserves_order_and_null_comment(self):updates = [- {"@type": "rename", "newName": "sales_model_v2"},{"@type": "updateComment", "newComment": None},{"@type": "setProperty", "property": "domain", "value": "sales"},{"@type": "removeProperty", "property": "legacy"},{"@type": "replaceDefinition", "definition": self.definition},]- self.model["name"] = "sales_model_v2"self.model["comment"] = Noneresult = await self._call(- "alter_semantic_model", {**_MODEL_ARGS, "updates": updates}+ "alter_semantic_model",+ {**_MODEL_ARGS, "updates": updates, "expected_revision": 7},)self.assertEqual(result, self.model)self._assert_request(- "PUT", f"{_MODELS_PATH}/sales_model", {"updates": updates}+ "PUT",+ f"{_MODELS_PATH}/sales_model",+ {"updates": updates, "expectedRevision": 7},)+ async def test_alter_rejects_non_integer_expected_revision(self):+ updates = [{"@type": "updateComment", "newComment": "edit"}]+ for revision in ("1", 1.0, True):+ with self.subTest(revision=revision), self.assertRaises(ToolError):+ await self._call(+ "alter_semantic_model",+ {+ **_MODEL_ARGS,+ "updates": updates,+ "expected_revision": revision,+ },+ )+ self.assertFalse(self.requests)+async def test_drop_semantic_model(self):for dropped in (True, False):with self.subTest(dropped=dropped):@@ -740,6 +783,7 @@ class TestSemanticModelTool(unittest.IsolatedAsyncioTestCase):"list_metric_infos","list_semantic_model_datasets","load_semantic_model",+ "list_semantic_model_revisions","create_semantic_model","alter_semantic_model","drop_semantic_model",diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.javaindex cbc5523b10..c6e9b14ccc 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java@@ -5647,7 +5647,8 @@ public class TestJcasbinAuthorizer {SemanticModel renamed = mock(SemanticModel.class);when(renamed.name()).thenReturn(newIdent.name());SemanticModelChange rename = SemanticModelChange.rename(newIdent.name());- when(dispatcher.alterSemanticModel(oldIdent, SemanticModelSourceUpdate.preserve(), rename))+ when(dispatcher.alterSemanticModel(+ oldIdent, null, SemanticModelSourceUpdate.preserve(), rename)).thenReturn(renamed);when(dispatcher.dropSemanticModel(newIdent)).thenReturn(true);when(gravitinoEnv.gravitinoAuthorizer()).thenReturn(jcasbinAuthorizer);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.javaindex 7f5b35b55f..bd99aa19b3 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java@@ -39,6 +39,8 @@ import org.apache.gravitino.exceptions.MetalakeNotInUseException;import org.apache.gravitino.exceptions.ModelAlreadyExistsException;import org.apache.gravitino.exceptions.ModelVersionAliasesAlreadyExistException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelRevisionException;import org.apache.gravitino.exceptions.NonEmptyCatalogException;import org.apache.gravitino.exceptions.NonEmptyDomainException;import org.apache.gravitino.exceptions.NonEmptyMetalakeException;@@ -1100,6 +1102,11 @@ public class ExceptionHandlers {if (e instanceof IllegalArgumentException) {return Utils.illegalArguments(errorMsg, e);+ } else if (e instanceof NoSuchSemanticModelRevisionException+ || e instanceof NoSuchSemanticModelException) {+ // A hidden draft and a missing snapshot must have the same public error shape.+ return Utils.notFound(e.getClass().getSimpleName(), errorMsg);+} else if (e instanceof NotFoundException) {return Utils.notFound(errorMsg, e);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.javaindex fea55639e0..df64cc98e5 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java@@ -50,13 +50,18 @@ import org.apache.gravitino.dto.requests.SemanticModelUpdatesRequest;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.responses.SemanticModelRevisionListResponse;+import org.apache.gravitino.dto.semantic.SemanticModelRevisionDTO;import org.apache.gravitino.dto.util.DTOConverters;+import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.semantic.OssieDocument;import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;@@ -351,9 +356,16 @@ public class SemanticModelOperations {request.getUpdates().stream().map(SemanticModelUpdateRequest::semanticModelChange).toArray(SemanticModelChange[]::new);+ Integer expectedRevision = request.getExpectedRevision();if (Arrays.stream(changes).anyMatch(change -> change instanceof SemanticModelChange.ReplaceDefinition)) {- dispatcher.loadSemanticModel(ident);+ SemanticModel latest =+ dispatcher.loadSemanticModelRevision(ident, SemanticModelRevisionSelector.LATEST);+ if (latest.revision() != expectedRevision) {+ throw new OptimisticLockException(+ "Semantic Model %s is at revision %s, expected %s",+ ident, latest.revision(), expectedRevision);+ }}SemanticModelSourceUpdate sourceUpdate = SemanticModelSourceUpdate.preserve();for (SemanticModelChange change : changes) {@@ -363,7 +375,8 @@ public class SemanticModelOperations {metalake, ((SemanticModelChange.ReplaceDefinition) change).getDefinition());}}- SemanticModel altered = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);+ SemanticModel altered =+ dispatcher.alterSemanticModel(ident, expectedRevision, sourceUpdate, changes);LOG.info("Semantic Model altered: {}.{}.{}.{}", metalake, catalog, schema, altered.name());return Utils.ok(new SemanticModelResponse(DTOConverters.toDTO(altered)));@@ -466,15 +479,7 @@ public class SemanticModelOperations {NameIdentifier ident =NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);OssieDocument document = dispatcher.exportOssieDocument(ident, outputFormat);- String mediaType =- document.format() == OssieFormat.JSON- ? MediaType.APPLICATION_JSON- : OSSIE_YAML_MEDIA_TYPE;- return Response.ok(document.content(), mediaType)- .header(- "Content-Disposition",- ossieContentDisposition(semanticModel, document.format()))- .build();+ return ossieExportResponse(semanticModel, document);});} catch (Exception e) {return ExceptionHandlers.handleSemanticModelException(@@ -482,6 +487,112 @@ public class SemanticModelOperations {}}+ /** Lists the model's retained revisions visible to the current caller. */+ @GET+ @Path("{semanticModel}/revisions")+ @Produces(VND_GRAVITINO_V1_JSON)+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION,+ accessMetadataType = MetadataObject.Type.SEMANTIC_MODEL)+ public Response listSemanticModelRevisions(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("catalog") @AuthorizationMetadata(type = Entity.EntityType.CATALOG) String catalog,+ @PathParam("schema") @AuthorizationMetadata(type = Entity.EntityType.SCHEMA) String schema,+ @PathParam("semanticModel") @AuthorizationMetadata(type = Entity.EntityType.SEMANTIC_MODEL)+ String semanticModel) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ NameIdentifier ident =+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);+ SemanticModelRevision[] history = dispatcher.listSemanticModelRevisions(ident);+ SemanticModelRevisionDTO[] revisions =+ Arrays.stream(history)+ .map(SemanticModelRevisionDTO::fromRevision)+ .toArray(SemanticModelRevisionDTO[]::new);+ return Utils.ok(new SemanticModelRevisionListResponse(revisions));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleSemanticModelException(+ OperationType.LIST, semanticModel, schema, e);+ }+ }++ /** Loads a numbered or latest revision visible to the current caller. */+ @GET+ @Path("{semanticModel}/revisions/{revision}")+ @Produces(VND_GRAVITINO_V1_JSON)+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION,+ accessMetadataType = MetadataObject.Type.SEMANTIC_MODEL)+ public Response loadSemanticModelRevision(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("catalog") @AuthorizationMetadata(type = Entity.EntityType.CATALOG) String catalog,+ @PathParam("schema") @AuthorizationMetadata(type = Entity.EntityType.SCHEMA) String schema,+ @PathParam("semanticModel") @AuthorizationMetadata(type = Entity.EntityType.SEMANTIC_MODEL)+ String semanticModel,+ @PathParam("revision") String revision) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ NameIdentifier ident =+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);+ SemanticModelRevisionSelector selector = SemanticModelRevisionSelector.parse(revision);+ SemanticModel loaded = dispatcher.loadSemanticModelRevision(ident, selector);+ return Utils.ok(new SemanticModelResponse(DTOConverters.toDTO(loaded)));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleSemanticModelException(+ OperationType.LOAD, semanticModel, schema, e);+ }+ }++ /** Exports a numbered or latest revision visible to the current caller. */+ @GET+ @Path("{semanticModel}/revisions/{revision}/ossie")+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION,+ accessMetadataType = MetadataObject.Type.SEMANTIC_MODEL)+ public Response exportSemanticModelRevision(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("catalog") @AuthorizationMetadata(type = Entity.EntityType.CATALOG) String catalog,+ @PathParam("schema") @AuthorizationMetadata(type = Entity.EntityType.SCHEMA) String schema,+ @PathParam("semanticModel") @AuthorizationMetadata(type = Entity.EntityType.SEMANTIC_MODEL)+ String semanticModel,+ @PathParam("revision") String revision,+ @DefaultValue("yaml") @QueryParam("format") String format) {+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ NameIdentifier ident =+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);+ SemanticModelRevisionSelector selector = SemanticModelRevisionSelector.parse(revision);+ OssieDocument document =+ dispatcher+ .exportSemanticModel(ident, selector, parseOssieFormat(format))+ .document();+ return ossieExportResponse(semanticModel, document);+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleSemanticModelException(+ OperationType.LOAD, semanticModel, schema, e);+ }+ }++ private static Response ossieExportResponse(String semanticModel, OssieDocument document) {+ String mediaType =+ document.format() == OssieFormat.JSON ? MediaType.APPLICATION_JSON : OSSIE_YAML_MEDIA_TYPE;+ return Response.ok(document.content(), mediaType)+ .header("Content-Disposition", ossieContentDisposition(semanticModel, document.format()))+ .build();+ }+private SemanticModel createSemanticModelEntity(String metalake, String catalog, String schema, SemanticModelCreateRequest request) {request.validate();diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.javaindex a3aef2c439..e91b0b36d2 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java@@ -70,6 +70,7 @@ import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.ErrorConstants;import org.apache.gravitino.dto.responses.ErrorResponse;import org.apache.gravitino.dto.responses.SemanticModelResponse;+import org.apache.gravitino.dto.responses.SemanticModelRevisionListResponse;import org.apache.gravitino.dto.semantic.DatasetDTO;import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;import org.apache.gravitino.exceptions.ConnectionFailedException;@@ -113,6 +114,8 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelRevision;+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;import org.apache.gravitino.semantic.SemanticModelSource;import org.apache.gravitino.semantic.SemanticModelSourceUpdate;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;@@ -215,6 +218,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {Table table = registeredTable();when(tables.loadTable(any())).thenReturn(table);when(dispatcher.loadSemanticModel(any())).thenReturn(semanticModel("sales", null));+ when(dispatcher.loadSemanticModelRevision(any(), eq(SemanticModelRevisionSelector.LATEST)))+ .thenReturn(semanticModel("sales", null));doCallRealMethod().when(dispatcher).importOssieDocument(any(), any(), any());}@@ -619,13 +624,13 @@ public class TestSemanticModelOperations extends BaseOperationsTest {SemanticModelUpdatesRequest request =new SemanticModelUpdatesRequest(List.of(- new SemanticModelUpdateRequest.RenameSemanticModelRequest("sales_v2"),new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "finance"),new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("legacy"),new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(- SemanticModelDefinitionDTO.fromDefinition(replacement))));- when(dispatcher.alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class)))+ SemanticModelDefinitionDTO.fromDefinition(replacement))),+ 1);+ when(dispatcher.alterSemanticModel(eq(ident), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("sales_v2", "Updated"));Response response = put(semanticModelPath() + "/sales", request);@@ -637,16 +642,15 @@ public class TestSemanticModelOperations extends BaseOperationsTest {ArgumentCaptor<SemanticModelChange[]> changesCaptor =ArgumentCaptor.forClass(SemanticModelChange[].class);- verify(dispatcher).alterSemanticModel(eq(ident), any(), changesCaptor.capture());+ verify(dispatcher).alterSemanticModel(eq(ident), eq(1), any(), changesCaptor.capture());SemanticModelChange[] changes = changesCaptor.getValue();- Assertions.assertEquals(5, changes.length);- Assertions.assertInstanceOf(SemanticModelChange.RenameSemanticModel.class, changes[0]);- Assertions.assertInstanceOf(SemanticModelChange.UpdateComment.class, changes[1]);- Assertions.assertInstanceOf(SemanticModelChange.SetProperty.class, changes[2]);- Assertions.assertInstanceOf(SemanticModelChange.RemoveProperty.class, changes[3]);- Assertions.assertInstanceOf(SemanticModelChange.ReplaceDefinition.class, changes[4]);+ Assertions.assertEquals(4, changes.length);+ Assertions.assertInstanceOf(SemanticModelChange.UpdateComment.class, changes[0]);+ Assertions.assertInstanceOf(SemanticModelChange.SetProperty.class, changes[1]);+ Assertions.assertInstanceOf(SemanticModelChange.RemoveProperty.class, changes[2]);+ Assertions.assertInstanceOf(SemanticModelChange.ReplaceDefinition.class, changes[3]);Assertions.assertEquals(- replacement, ((SemanticModelChange.ReplaceDefinition) changes[4]).getDefinition());+ replacement, ((SemanticModelChange.ReplaceDefinition) changes[3]).getDefinition());}@Test@@ -658,7 +662,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {List.of(new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(- invalidDefinition)));+ invalidDefinition)),+ 1);assertError(put(semanticModelPath() + "/sales", request),@@ -672,12 +677,11 @@ public class TestSemanticModelOperations extends BaseOperationsTest {@Testvoid testMetadataOnlyAlterPreservesSourcesWithoutResolving() {sourceAuthorizer = mock(GravitinoAuthorizer.class);- when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))+ when(dispatcher.alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("renamed", "Updated"));SemanticModelUpdatesRequest request =new SemanticModelUpdatesRequest(List.of(- new SemanticModelUpdateRequest.RenameSemanticModelRequest("renamed"),new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "sales"),new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("legacy")));@@ -688,6 +692,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {verify(dispatcher).alterSemanticModel(eq(semanticModelIdentifier("sales")),+ eq(null),eq(SemanticModelSourceUpdate.preserve()),any(SemanticModelChange[].class));verifyNoInteractions(tables, views, sourceAuthorizer);@@ -703,7 +708,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {.build();when(dispatcher.createSemanticModel(any(), any(), any(), any(), any())).thenReturn(semanticModel("sales", null));- when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))+ when(dispatcher.alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("sales", null));Assertions.assertEquals(Response.Status.OK.getStatusCode(), writeDefinition(false, original).getStatus());@@ -740,6 +745,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {verify(dispatcher).alterSemanticModel(any(),+ eq(1),eq(SemanticModelSourceUpdate.replace(List.of(new SemanticModelSource("orders", EntityType.TABLE, 202L)))),@@ -749,7 +755,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {@Testvoid testBatchReplacementUsesFinalDefinitionAssociations() {- when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))+ when(dispatcher.alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("sales", null));SemanticModelDefinition finalDefinition =SemanticModelDefinition.builder()@@ -769,7 +775,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(SemanticModelDefinitionDTO.fromDefinition(finalDefinition)),- new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "sales")));+ new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "sales")),+ 1);Assertions.assertEquals(Response.Status.OK.getStatusCode(),@@ -777,12 +784,96 @@ public class TestSemanticModelOperations extends BaseOperationsTest {verify(dispatcher).alterSemanticModel(any(),+ eq(1),eq(SemanticModelSourceUpdate.replace(List.of(new SemanticModelSource("Final.Alias", EntityType.TABLE, 101L)))),any(SemanticModelChange[].class));}+ @Test+ void testRevisionEndpointsReturnSnapshotMetadata() {+ NameIdentifier ident = semanticModelIdentifier("sales");+ SemanticModel published = semanticModel("sales", "First save");+ when(dispatcher.listSemanticModelRevisions(ident))+ .thenReturn(new SemanticModelRevision[] {published});+ when(dispatcher.loadSemanticModelRevision(eq(ident), eq(SemanticModelRevisionSelector.LATEST)))+ .thenReturn(published);+ when(dispatcher.exportSemanticModel(eq(ident), any(), eq(OssieFormat.JSON)))+ .thenReturn(new SemanticModelDispatcher.SemanticModelExport(EXPORTED_JSON, 1));++ String path = semanticModelPath() + "/sales/revisions";+ SemanticModelRevisionListResponse history =+ target(path).request(VND_V1_JSON).get(SemanticModelRevisionListResponse.class);+ Assertions.assertEquals(1, history.revisions().length);+ Assertions.assertEquals("tester", history.revisions()[0].publishedBy());+ Assertions.assertEquals(SemanticModel.Status.PUBLISHED, history.revisions()[0].status());+ SemanticModelResponse latest =+ target(path + "/latest").request(VND_V1_JSON).get(SemanticModelResponse.class);+ Assertions.assertEquals(1, latest.getSemanticModel().revision());+ Assertions.assertEquals(+ EXPORTED_JSON.content(),+ target(path + "/1/ossie").queryParam("format", "json").request().get(String.class));+ assertError(+ target(path + "/0").request(VND_V1_JSON).get(),+ Response.Status.BAD_REQUEST,+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,+ IllegalArgumentException.class.getSimpleName(),+ "Revision must be positive");+ }++ @Test+ void testReplacementRequiresExpectedRevisionAndRejectsStaleValue() {+ SemanticModelUpdateRequest update =+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(+ SemanticModelDefinitionDTO.fromDefinition(semanticModelDefinition()));+ assertError(+ put(semanticModelPath() + "/sales", new SemanticModelUpdatesRequest(List.of(update))),+ Response.Status.BAD_REQUEST,+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,+ IllegalArgumentException.class.getSimpleName(),+ "expectedRevision is required");+ assertError(+ put(semanticModelPath() + "/sales", new SemanticModelUpdatesRequest(List.of(update), 2)),+ Response.Status.CONFLICT,+ ErrorConstants.OPTIMISTIC_LOCK_CONFLICT_CODE,+ OptimisticLockException.class.getSimpleName(),+ "expected 2");+ verifyNoInteractions(tables, views);+ verifyNoModelWrites();+ }++ @ParameterizedTest+ @ValueSource(strings = {"1.9", "\"1\"", "2147483648", "true"})+ void testExpectedRevisionRejectsInvalidJsonNumbers(String revision) {+ String json =+ """+ {"expectedRevision": %s, "updates": [{"@type": "updateComment", "newComment": "edit"}]}+ """+ .formatted(revision);+ try (Response response =+ target(semanticModelPath() + "/sales").request(VND_V1_JSON).put(Entity.json(json))) {+ Assertions.assertEquals(400, response.getStatus());+ }+ verifyNoInteractions(dispatcher);+ }++ @Test+ void testRenameMustBeTheOnlyChange() {+ SemanticModelUpdatesRequest request =+ new SemanticModelUpdatesRequest(+ List.of(+ new SemanticModelUpdateRequest.RenameSemanticModelRequest("renamed"),+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated")));+ assertError(+ put(semanticModelPath() + "/sales", request),+ Response.Status.BAD_REQUEST,+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,+ IllegalArgumentException.class.getSimpleName(),+ "Rename must be the only");+ verifyNoModelWrites();+ }+@Testvoid testAlterSemanticModelRejectsNullBody() {assertError(@@ -803,7 +894,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {doThrow(new NoSuchSemanticModelException("sales does not exist")).when(dispatcher)- .alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class));+ .alterSemanticModel(eq(ident), any(), any(), any(SemanticModelChange[].class));assertError(put(semanticModelPath() + "/sales", request),Response.Status.NOT_FOUND,@@ -813,7 +904,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {doThrow(new OptimisticLockException("sales changed in this transaction")).when(dispatcher)- .alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class));+ .alterSemanticModel(eq(ident), any(), any(), any(SemanticModelChange[].class));assertError(put(semanticModelPath() + "/sales", request),Response.Status.CONFLICT,@@ -984,7 +1075,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {@ParameterizedTest@ValueSource(booleans = {false, true})void testMissingModelBeforeSourceValidation(boolean unavailableSource) {- when(dispatcher.loadSemanticModel(semanticModelIdentifier("sales")))+ when(dispatcher.loadSemanticModelRevision(+ eq(semanticModelIdentifier("sales")), eq(SemanticModelRevisionSelector.LATEST))).thenThrow(new NoSuchSemanticModelException("sales does not exist"));when(tables.loadTable(any())).thenThrow(@@ -1012,7 +1104,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {when(tables.loadTable(any())).thenReturn(table);when(dispatcher.createSemanticModel(any(), any(), any(), any(), any())).thenReturn(semanticModel("sales", null));- when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))+ when(dispatcher.alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("sales", null));Assertions.assertEquals(Response.Status.OK.getStatusCode(),@@ -1078,7 +1170,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {}when(dispatcher.createSemanticModel(any(), any(), any(), any(), any())).thenReturn(semanticModel("sales", null));- when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))+ when(dispatcher.alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class))).thenReturn(semanticModel("sales", null));Response response = writeDefinition(replaceDefinition, definition);if (segment == 0) {@@ -1096,7 +1188,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {// Characterize existing behavior: resolvable names are not rejected solely for whitespace.Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());if (replaceDefinition) {- verify(dispatcher).alterSemanticModel(any(), any(), any(SemanticModelChange[].class));+ verify(dispatcher)+ .alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class));} else {verify(dispatcher).createSemanticModel(any(), any(), eq(definition), any(), any());}@@ -1135,7 +1228,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {private void verifyNoModelWrites() {verify(dispatcher, never()).createSemanticModel(any(), any(), any(), any(), any());verify(dispatcher, never()).importSemanticModel(any(), any(), any(), any(), any());- verify(dispatcher, never()).alterSemanticModel(any(), any(), any(SemanticModelChange[].class));+ verify(dispatcher, never())+ .alterSemanticModel(any(), any(), any(), any(SemanticModelChange[].class));}private Response writeDefinition(boolean replaceDefinition, SemanticModelDefinition definition) {@@ -1145,7 +1239,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {new SemanticModelUpdatesRequest(List.of(new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(- SemanticModelDefinitionDTO.fromDefinition(definition)))))+ SemanticModelDefinitionDTO.fromDefinition(definition))),+ 1)): post(semanticModelPath(), createRequest("sales", null, definition));}@@ -1338,8 +1433,12 @@ public class TestSemanticModelOperations extends BaseOperationsTest {@Testvoid testExportOssieYamlAndJsonDocuments() {NameIdentifier ident = semanticModelIdentifier("sales");- when(dispatcher.exportOssieDocument(ident, OssieFormat.YAML)).thenReturn(EXPORTED_YAML);- when(dispatcher.exportOssieDocument(ident, OssieFormat.JSON)).thenReturn(EXPORTED_JSON);+ when(dispatcher.exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.YAML)))+ .thenReturn(new SemanticModelDispatcher.SemanticModelExport(EXPORTED_YAML, 1));+ when(dispatcher.exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.JSON)))+ .thenReturn(new SemanticModelDispatcher.SemanticModelExport(EXPORTED_JSON, 1));Response yamlResponse = getOssie(semanticModelPath() + "/sales/ossie");@@ -1362,8 +1461,12 @@ public class TestSemanticModelOperations extends BaseOperationsTest {"attachment; filename=\"sales.ossie.json\"",jsonResponse.getHeaderString("Content-Disposition"));Assertions.assertEquals(EXPORTED_JSON.content(), jsonResponse.readEntity(String.class));- verify(dispatcher).exportOssieDocument(ident, OssieFormat.YAML);- verify(dispatcher).exportOssieDocument(ident, OssieFormat.JSON);+ verify(dispatcher)+ .exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.YAML));+ verify(dispatcher)+ .exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.JSON));verifyNoMoreInteractions(dispatcher);}@@ -1459,14 +1562,21 @@ public class TestSemanticModelOperations extends BaseOperationsTest {void testOssieExportPropagatesDispatcherErrors() {doThrow(new NoSuchSemanticModelException("sales does not exist")).when(dispatcher)- .exportOssieDocument(semanticModelIdentifier("sales"), OssieFormat.YAML);+ .exportSemanticModel(+ eq(semanticModelIdentifier("sales")),+ eq(SemanticModelRevisionSelector.ACTIVE),+ eq(OssieFormat.YAML));assertError(getOssie(semanticModelPath() + "/sales/ossie"),Response.Status.NOT_FOUND,ErrorConstants.NOT_FOUND_CODE,NoSuchSemanticModelException.class.getSimpleName(),"sales does not exist");- verify(dispatcher).exportOssieDocument(semanticModelIdentifier("sales"), OssieFormat.YAML);+ verify(dispatcher)+ .exportSemanticModel(+ eq(semanticModelIdentifier("sales")),+ eq(SemanticModelRevisionSelector.ACTIVE),+ eq(OssieFormat.YAML));verifyNoMoreInteractions(dispatcher);}@@ -1531,10 +1641,13 @@ public class TestSemanticModelOperations extends BaseOperationsTest {void testExportEmitsDedicatedEventsWithoutSourceLookup(boolean missing) {NameIdentifier ident = semanticModelIdentifier("sales");if (missing) {- when(dispatcher.exportOssieDocument(ident, OssieFormat.YAML))+ when(dispatcher.exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.YAML))).thenThrow(new NoSuchSemanticModelException("missing model"));} else {- when(dispatcher.exportOssieDocument(ident, OssieFormat.YAML)).thenReturn(EXPORTED_YAML);+ when(dispatcher.exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.YAML)))+ .thenReturn(new SemanticModelDispatcher.SemanticModelExport(EXPORTED_YAML, 1));}try (Response response = getOssie(semanticModelPath() + "/sales/ossie")) {Assertions.assertEquals(missing ? 404 : 200, response.getStatus());@@ -1547,7 +1660,9 @@ public class TestSemanticModelOperations extends BaseOperationsTest {events.getAllValues().get(1).getClass());verifyNoInteractions(tables, views);verifyNoModelWrites();- verify(dispatcher).exportOssieDocument(ident, OssieFormat.YAML);+ verify(dispatcher)+ .exportSemanticModel(+ eq(ident), eq(SemanticModelRevisionSelector.ACTIVE), eq(OssieFormat.YAML));verifyNoMoreInteractions(dispatcher);}@@ -1561,8 +1676,14 @@ public class TestSemanticModelOperations extends BaseOperationsTest {}private SemanticModel semanticModel(String name, String comment) {+ return semanticModel(name, comment, 1, SemanticModel.Status.PUBLISHED);+ }++ private SemanticModel semanticModel(+ String name, String comment, int revision, SemanticModel.Status status) {return SemanticModelEntity.builder().withId(1L)+ .withRevision(revision, status, null, null).withName(name).withNamespace(namespace).withComment(comment)diff --git a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.jsindex c77b25814d..372691faa9 100644--- a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js+++ b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js@@ -98,10 +98,10 @@ export default function CreateSemanticModelDialog({ ...props }) {const initLoad = async () => {setIsLoading(true)try {- const { payload } = await dispatch(- getSemanticModelDetails({ metalake, catalog, schema, semanticModel: editSemanticModel })- )- const loaded = payload?.semanticModel+ const { semanticModel: loaded } = await dispatch(+ getSemanticModelDetails({ metalake, catalog, schema, semanticModel: editSemanticModel, revision: 'latest' })+ ).unwrap()+ if (!loaded?.revision) throw new Error('The latest Semantic Model revision is unavailable.')setCacheData(loaded)form.setFieldValue('name', loaded?.name)form.setFieldValue('comment', loaded?.comment)@@ -112,8 +112,10 @@ export default function CreateSemanticModelDialog({ ...props }) {form.setFieldValue(['properties', index, 'value'], value)index++})- setIsLoading(false)} catch (e) {+ setCacheData(undefined)+ setSaveError(e.message || 'Unable to load the latest Semantic Model revision.')+ } finally {setIsLoading(false)}}@@ -160,6 +162,11 @@ export default function CreateSemanticModelDialog({ ...props }) {let resultif (editSemanticModel) {const updates = genSemanticModelUpdates(cacheData, submitData)+ if (updates.length > 1 && updates.some(update => update['@type'] === 'rename')) {+ setSaveError('Save the rename and other changes separately.')++ return+ }if (updates.length) {result = await dispatch(updateSemanticModel({@@ -167,8 +174,7 @@ export default function CreateSemanticModelDialog({ ...props }) {catalog,schema,semanticModel: editSemanticModel,- expectedDefinition: cacheData.definition,- data: { updates }+ data: { updates, expectedRevision: cacheData.revision }}))}diff --git a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsx b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsxindex d9d187e194..d957d47eac 100644--- a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsx+++ b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsx@@ -33,6 +33,7 @@ vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))const definition = { datasets: [{ name: 'orders', source: { namespace: ['sales', 'mart'], name: 'orders' } }] }const model = {+ revision: 7,name: 'orders',comment: 'original',definition,@@ -62,7 +63,7 @@ beforeEach(() => {value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))})defHttp.get.mockImplementation(({ url }) =>- Promise.resolve(url.endsWith('/orders') ? { semanticModel: model } : { identifiers: [] })+ Promise.resolve(url.endsWith('/orders/revisions/latest') ? { semanticModel: model } : { identifiers: [] }))container = document.createElement('div')document.body.appendChild(container)@@ -161,6 +162,7 @@ describe('semantic model editor', () => {await fill('comment', 'new comment')await submit()expect(defHttp.put.mock.calls[0][0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'updateComment', newComment: 'new comment' }]})})@@ -174,6 +176,7 @@ describe('semantic model editor', () => {)await submit()expect(defHttp.put.mock.calls[0]?.[0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'removeProperty', property: name }]})expect(close).toHaveBeenCalledWith(false)diff --git a/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.js b/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.jsindex bf4baa922b..d5ce735b40 100644--- a/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.js+++ b/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.js@@ -18,10 +18,10 @@*/import { useEffect, useRef, useState } from 'react'-import { Alert, Button, Form, Input, Modal, Select, Space, Tabs, theme } from 'antd'+import { Alert, Button, Form, Input, Modal, Select, Space, Spin, Tabs, theme } from 'antd'import { isEqual } from 'lodash-es'import { useAppDispatch } from '@/lib/hooks/useStore'-import { updateSemanticModel } from '@/lib/store/metalakes'+import { getSemanticModelDetails, updateSemanticModel } from '@/lib/store/metalakes'import { semanticDataTypes, validateSemanticModelDefinition } from '@/lib/utils/semanticModel'import {getSemanticMetadataEntity,@@ -30,25 +30,46 @@ import {} from '@/lib/utils/semanticMetadata'export default function SemanticMetadataEditor(props) {- try {- getSemanticMetadataEntity(props.definition, props.target)- } catch (error) {+ const { metalake, catalog, schema, semanticModel, onClose, target } = props+ const dispatch = useAppDispatch()+ const [snapshot, setSnapshot] = useState(null)+ const [loadError, setLoadError] = useState('')++ useEffect(() => {+ let cancelled = false+ dispatch(getSemanticModelDetails({ metalake, catalog, schema, semanticModel, revision: 'latest' }))+ .unwrap()+ .then(({ semanticModel: latest }) => {+ if (!latest?.revision) throw new Error('The latest Semantic Model revision is unavailable.')+ getSemanticMetadataEntity(latest.definition, target)+ if (!cancelled) setSnapshot(latest)+ })+ .catch(error => {+ if (!cancelled) setLoadError(error.message || 'Unable to load the latest Semantic Model revision.')+ })++ return () => {+ cancelled = true+ }+ }, [dispatch, metalake, catalog, schema, semanticModel, target])++ if (!snapshot) {return (<Modalopen- title='Metadata unavailable'- onCancel={props.onClose}- footer={<Button onClick={props.onClose}>Close</Button>}+ title={loadError ? 'Metadata unavailable' : 'Loading latest revision'}+ onCancel={onClose}+ footer={<Button onClick={onClose}>Close</Button>}>- <Alert type='error' showIcon message={error.message} />+ {loadError ? <Alert type='error' showIcon message={loadError} /> : <Spin />}</Modal>)}- return <SemanticMetadataForm {...props} />+ return <SemanticMetadataForm {...props} snapshot={snapshot} />}-function SemanticMetadataForm({ definition, target, metalake, catalog, schema, semanticModel, onClose, onSaved }) {+function SemanticMetadataForm({ snapshot, target, metalake, catalog, schema, semanticModel, onClose, onSaved }) {const { token } = theme.useToken()const dispatch = useAppDispatch()const [form] = Form.useForm()@@ -80,7 +101,7 @@ function SemanticMetadataForm({ definition, target, metalake, catalog, schema, s}, [errors])// Keep the editing snapshot stable through list/detail refreshes while the dialog is open.- const [original] = useState(definition)+ const [{ definition: original, revision }] = useState(snapshot)const entity = getSemanticMetadataEntity(original, target)const [initial] = useState(() => semanticMetadataFormValues(entity))const structuredContextInitialized = useRef(initial.contextFormat === 'structured')@@ -129,8 +150,7 @@ function SemanticMetadataForm({ definition, target, metalake, catalog, schema, scatalog,schema,semanticModel,- expectedDefinition: original,- data: { updates: [{ '@type': 'replaceDefinition', definition: updated }] }+ data: { expectedRevision: revision, updates: [{ '@type': 'replaceDefinition', definition: updated }] }}))if (result.error || result.payload?.err || !result.payload) {diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.jsindex 18b2f6d883..f241da0cd1 100644--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.js+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.js@@ -820,7 +820,6 @@ export default function SemanticModelDetailsPage() {)}{definition && metadataEdit && (<SemanticMetadataEditor- definition={definition}target={metadataEdit}metalake={metalake}catalog={catalog}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsx b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsxindex 9d4826fba2..bf52e19456 100644--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsx+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsx@@ -146,7 +146,7 @@ const renderDetails = async (definition, details = {}) => {store.dispatch(getSemanticModelDetails.pending('load', args))store.dispatch(getSemanticModelDetails.fulfilled(- { semanticModel: { name: navigation.name, definition, properties: {}, ...details }, init: true },+ { semanticModel: { name: navigation.name, revision: 7, definition, properties: {}, ...details }, init: true },'load',args)@@ -366,12 +366,12 @@ describe('editing from Semantic Model details', () => {async rename => {navigation.name = 'orders'const definition = { datasets: [{ name: 'orders', source: { namespace: ['sales', 'mart'], name: 'orders' } }] }- let model = { name: 'orders', definition, properties: {}, comment: 'original' }+ let model = { name: 'orders', revision: 7, definition, properties: {}, comment: 'original' }const updated = {...model,name: rename ? 'orders_v2' : 'orders',- comment: 'saved comment',+ comment: rename ? 'original' : 'saved comment',audit: { lastModifier: 'editor' }}defHttp.get.mockImplementation(({ url }) =>@@ -385,16 +385,19 @@ describe('editing from Semantic Model details', () => {await renderDetails(definition, model)await click(document.querySelector('[aria-label="Edit Semantic Model"]'))await act(async () => {- Simulate.change(document.querySelector('[data-refer="semantic-model-comment-field"]'), {- target: { value: 'saved comment' }- })if (rename)Simulate.change(document.querySelector('[data-refer="semantic-model-name-field"]'), {target: { value: 'orders_v2' }})+ else+ Simulate.change(document.querySelector('[data-refer="semantic-model-comment-field"]'), {+ target: { value: 'saved comment' }+ })})await click(document.querySelector('[data-refer="handle-submit-semantic-model"]'))- expect(document.querySelector('[data-refer="semantic-model-comment-field"]').value).toBe('saved comment')+ expect(document.querySelector('[data-refer="semantic-model-comment-field"]').value).toBe(+ rename ? 'original' : 'saved comment'+ )expect(navigation.replace).not.toHaveBeenCalled()expect(store.getState().metalakes.activatedDetails.comment).toBe('original')await click(document.querySelector('[data-refer="handle-submit-semantic-model"]'))@@ -462,17 +465,17 @@ describe('focused semantic metadata editing', () => {defHttp.put.mockRejectedValueOnce(new Error('Save rejected'))await click(findText('.ant-modal button', 'Save'))expect(defHttp.put.mock.lastCall[0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'replaceDefinition', definition: expected }]})await act(async () => Simulate.mouseDown(selector.querySelector('.ant-select-clear')))updatedEntity.datatype = nullconst model = { name: navigation.name, definition: expected, properties: {} }defHttp.put.mockResolvedValue({ semanticModel: model })- defHttp.get- .mockResolvedValue({ semanticModel: model, identifiers: [] })- .mockResolvedValueOnce({ semanticModel: { ...model, definition } })+ defHttp.get.mockResolvedValue({ semanticModel: model, identifiers: [] })await click(findText('.ant-modal button', 'Save'))expect(defHttp.put.mock.lastCall[0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'replaceDefinition', definition: expected }]})expect(document.querySelector('.ant-modal')).toBeNull()@@ -515,11 +518,10 @@ describe('focused semantic metadata editing', () => {}const model = { name: navigation.name, definition: expected, properties: {} }defHttp.put.mockResolvedValue({ semanticModel: model })- defHttp.get- .mockResolvedValue({ semanticModel: model, identifiers: [] })- .mockResolvedValueOnce({ semanticModel: { ...model, definition } })+ defHttp.get.mockResolvedValue({ semanticModel: model, identifiers: [] })await click(findText('.ant-modal button', 'Save'))expect(defHttp.put.mock.lastCall[0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'replaceDefinition', definition: expected }]})expect(document.querySelector('.ant-modal')).toBeNull()@@ -533,7 +535,7 @@ describe('focused semantic metadata editing', () => {const extension = [{ vendorName: 'vendor', data: '{"keep":true}' }]definition.customExtensions = extensiondefinition.datasets[0].fields[0].customExtensions = extension- let model = { name: 'orders', definition, properties: {} }+ let model = { name: 'orders', revision: 7, definition, properties: {} }defHttp.get.mockImplementation(({ url }) =>Promise.resolve(url.endsWith('/semantic-models') ? { identifiers: [] } : { semanticModel: model }))@@ -597,6 +599,7 @@ describe('focused semantic metadata editing', () => {}await click(findText('.ant-modal button', 'Save'))expect(defHttp.put.mock.lastCall[0].data).toEqual({+ expectedRevision: 7,updates: [{ '@type': 'replaceDefinition', definition: expected }]})expect(store.getState().metalakes.activatedDetails.definition).toEqual(expected)@@ -908,7 +911,7 @@ it.each([false, true])(Promise.resolve(url.endsWith('/semantic-models')? { identifiers: [] }- : { semanticModel: { name: navigation.name, definition, properties: {} } }+ : { semanticModel: { name: navigation.name, revision: 7, definition, properties: {} } }))await renderDetails(definition)@@ -983,10 +986,20 @@ it.each([[{ datasets: [{ name: 'orders', fields: [] }] }, { kind: 'field', datasetName: 'orders', name: 'amount' }]])('renders a closable error when the editor mounts with unavailable metadata', async (definition, target) => {const close = vi.fn()+ defHttp.get.mockResolvedValueOnce({+ semanticModel: { name: navigation.name, revision: 8, status: 'DRAFT', definition }+ })await act(async () =>root.render(<Provider store={store}>- <SemanticMetadataEditor definition={definition} target={target} onClose={close} />+ <SemanticMetadataEditor+ metalake='demo'+ catalog='sales'+ schema='mart'+ semanticModel={navigation.name}+ target={target}+ onClose={close}+ /></Provider>))@@ -1027,7 +1040,7 @@ it.each(['focused', 'JSON'])(async editor => {navigation.name = 'orders'const definition = definitionWith(() => null)- let serverModel = { name: navigation.name, definition, properties: {} }+ let serverModel = { name: navigation.name, revision: 7, definition, properties: {} }defHttp.get.mockImplementation(() => Promise.resolve({ semanticModel: serverModel }))await renderDetails(definition)let input@@ -1042,9 +1055,10 @@ it.each(['focused', 'JSON'])(Simulate.change(input, { target: { value: JSON.stringify({ ...definition, aiContext: 'My draft' }) } }))}- serverModel = { ...serverModel, definition: { ...definition, aiContext: 'Concurrent edit' } }+ serverModel = { ...serverModel, revision: 8, definition: { ...definition, aiContext: 'Concurrent edit' } }+ defHttp.put.mockRejectedValueOnce({ response: { status: 409 } })await click(findText('.ant-modal button', editor === 'focused' ? 'Save' : 'Submit'))- expect(defHttp.put).not.toHaveBeenCalled()+ expect(defHttp.put.mock.lastCall[0].data.expectedRevision).toBe(7)expect(document.querySelector('.ant-modal .ant-alert').textContent).toContain('changed since')expect(input.value).toContain('My draft')expect(store.getState().metalakes.activatedDetails.definition).toEqual(definition)@@ -1052,7 +1066,7 @@ it.each(['focused', 'JSON'])()it('edits the time dimension through the field form', async () => {- let model = { name: navigation.name, definition: definitionWith(() => null), properties: {} }+ let model = { name: navigation.name, revision: 7, definition: definitionWith(() => null), properties: {} }model.definition.datasets[0].fields[0].dimension = { isTime: true }defHttp.get.mockImplementation(() => Promise.resolve({ semanticModel: model, identifiers: [] }))defHttp.put.mockImplementation(({ data }) => {diff --git a/web-v2/web/src/lib/api/semanticModels/index.js b/web-v2/web/src/lib/api/semanticModels/index.jsindex 64d6dc7b6e..b6fbe8ed57 100644--- a/web-v2/web/src/lib/api/semanticModels/index.js+++ b/web-v2/web/src/lib/api/semanticModels/index.js@@ -41,10 +41,12 @@ export const getSemanticModelsApi = (params, options) => {)}-export const getSemanticModelDetailsApi = ({ metalake, catalog, schema, semanticModel }, options) => {+export const getSemanticModelDetailsApi = ({ metalake, catalog, schema, semanticModel, revision }, options) => {+ const model = Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })+return defHttp.get({- url: `${Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })}`+ url: revision ? `${model}/revisions/${encodeURIComponent(revision)}` : model},options)diff --git a/web-v2/web/src/lib/store/metalakes/index.js b/web-v2/web/src/lib/store/metalakes/index.jsindex 2b5cddf02a..88380839cc 100644--- a/web-v2/web/src/lib/store/metalakes/index.js+++ b/web-v2/web/src/lib/store/metalakes/index.js@@ -2402,9 +2402,9 @@ export const fetchSemanticModels = createAsyncThunk(export const getSemanticModelDetails = createAsyncThunk('appMetalakes/getSemanticModelDetails',- async ({ init, metalake, catalog, schema, semanticModel }) => {+ async ({ init, metalake, catalog, schema, semanticModel, revision }) => {const [err, res] = await to(- getSemanticModelDetailsApi({ metalake, catalog, schema, semanticModel }, { errorMessageMode: 'none' })+ getSemanticModelDetailsApi({ metalake, catalog, schema, semanticModel, revision }, { errorMessageMode: 'none' }))if (err) {@@ -2443,37 +2443,27 @@ export const createSemanticModel = createAsyncThunk(export const updateSemanticModel = createAsyncThunk('appMetalakes/updateSemanticModel',- async ({ metalake, catalog, schema, semanticModel, data, expectedDefinition }, { dispatch, getState }) => {+ async ({ metalake, catalog, schema, semanticModel, data }, { dispatch, getState }) => {const activeEntity = getState().metalakes.activeCatalogEntity- if (data.updates.some(update => update['@type'] === 'replaceDefinition')) {- // Detect intervening edits; atomic protection still requires a server-side version token.- const [err, current] = await to(- getSemanticModelDetailsApi(- { metalake, catalog, schema, semanticModel },- { errorMessageMode: 'none', ignoreCancelToken: true }- )- )- if (err || !current?.semanticModel?.definition || !expectedDefinition) {- return {- err: true,- message: semanticModelErrorMessage(- err,- 'Unable to verify the current definition. Reload the model and try again.'- )- }- }- if (!_.isEqual(current.semanticModel.definition, expectedDefinition)) {- return {- err: true,- message:- 'The definition has changed since this editor was opened. Copy your edits, then refresh the page and reapply them to the latest definition.'- }- }+ const replacingDefinition = data.updates.some(update => update['@type'] === 'replaceDefinition')+ if (replacingDefinition && (!Number.isInteger(data.expectedRevision) || data.expectedRevision <= 0)) {+ return { err: true, message: 'Reload the latest Semantic Model revision before editing its definition.' }}if (getState().metalakes.activeCatalogEntity === activeEntity) await dispatch(setTableLoading(true))const [err, res] = await to(updateSemanticModelApi({ metalake, catalog, schema, semanticModel, data }))if (getState().metalakes.activeCatalogEntity === activeEntity) await dispatch(setTableLoading(false))+ if (+ err?.response?.status === 409 &&+ (replacingDefinition || err.response.data?.type === 'OptimisticLockException')+ ) {+ return {+ err: true,+ message:+ 'The Semantic Model has changed since this editor was opened. Copy your edits, reopen the editor, and reapply them to the latest revision.'+ }+ }+if (err || !res?.semanticModel) {return { err: true, message: semanticModelErrorMessage(err, 'Failed to update the Semantic Model.') }}diff --git a/web-v2/web/src/lib/store/metalakes/semanticModels.test.js b/web-v2/web/src/lib/store/metalakes/semanticModels.test.jsindex 87c8c9f923..1bb4b596d3 100644--- a/web-v2/web/src/lib/store/metalakes/semanticModels.test.js+++ b/web-v2/web/src/lib/store/metalakes/semanticModels.test.js@@ -47,81 +47,39 @@ beforeEach(() => {store = configureStore({ reducer: { metalakes: reducer } })})-describe('definition replacement conflict checks', () => {- const original = { datasets: [], aiContext: 'Original guidance' }- const updated = { ...original, aiContext: 'My draft' }+describe('conditional definition replacement', () => {+ const definition = { datasets: [], aiContext: 'My edits' }const args = {...namespace,semanticModel: 'orders',- expectedDefinition: original,- data: { updates: [{ '@type': 'replaceDefinition', definition: updated }] }+ data: { expectedRevision: 4, updates: [{ '@type': 'replaceDefinition', definition }] }}- it('does not change another page loading state after a delayed verification read', async () => {- store.dispatch(setActiveCatalogEntity({ ...namespace, semanticModel: 'orders' }))- let verify- let finishSave- defHttp.get.mockImplementation(({ url }) =>- url.endsWith('/orders')- ? new Promise(resolve => {- verify = resolve- })- : Promise.resolve({ identifiers: [] })- )- defHttp.put.mockImplementation(- () =>- new Promise(resolve => {- finishSave = resolve- })- )- const save = store.dispatch(updateSemanticModel(args))- store.dispatch(setActiveCatalogEntity({ ...namespace, schema: 'other' }))- verify({ semanticModel: { definition: original } })- await vi.waitFor(() => expect(finishSave).toBeTypeOf('function'))- expect(store.getState().metalakes.tableLoading).toBe(false)- finishSave({ semanticModel: { name: 'orders', definition: updated } })- await save- expect(store.getState().metalakes.tableLoading).toBe(false)- expect(store.getState().metalakes.semanticModels).toEqual([])+ it('sends the revision read by the editor without a verification GET', async () => {+ defHttp.put.mockResolvedValue({ semanticModel: { name: 'orders', revision: 5, definition } })+ defHttp.get.mockResolvedValue({ identifiers: [] })+ const result = await store.dispatch(updateSemanticModel(args))+ expect(result.payload.revision).toBe(5)+ expect(defHttp.put.mock.calls[0][0].data).toEqual(args.data)+ expect(defHttp.put.mock.invocationCallOrder[0]).toBeLessThan(defHttp.get.mock.invocationCallOrder[0])})- it('refuses to overwrite a definition changed since the editor opened', async () => {- defHttp.get.mockResolvedValue({ semanticModel: { definition: { ...original, aiContext: 'Other writer' } } })+ it('reports a conflict and leaves the caller free to reapply its edits', async () => {+ defHttp.put.mockRejectedValue({ response: { status: 409 } })const result = await store.dispatch(updateSemanticModel(args))expect(result.payload.err).toBe(true)expect(result.payload.message).toContain('changed since')- expect(defHttp.put).not.toHaveBeenCalled()expect(store.getState().metalakes.tableLoading).toBe(false)+ expect(defHttp.get).not.toHaveBeenCalled()})- it('compares definitions independently of object key order before saving', async () => {- defHttp.get- .mockResolvedValueOnce({ semanticModel: { definition: { aiContext: 'Original guidance', datasets: [] } } })- .mockResolvedValue({ identifiers: [] })- defHttp.put.mockResolvedValue({ semanticModel: { name: 'orders', definition: updated } })- const result = await store.dispatch(updateSemanticModel(args))- expect(result.payload.definition).toEqual(updated)- expect(defHttp.put.mock.calls[0][0].data).toEqual(args.data)- expect(defHttp.get.mock.invocationCallOrder[0]).toBeLessThan(defHttp.put.mock.invocationCallOrder[0])+ it.each([undefined, 0, -1])('requires a positive revision for replacement: %s', async expectedRevision => {+ const result = await store.dispatch(updateSemanticModel({ ...args, data: { ...args.data, expectedRevision } }))+ expect(result.payload.err).toBe(true)+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(defHttp.get).not.toHaveBeenCalled()})-- it.each(['error', 'missing definition', 'missing snapshot'])(- 'does not save when verification fails: %s',- async reason => {- if (reason === 'error') defHttp.get.mockRejectedValue(new Error('Read denied'))- else- defHttp.get.mockResolvedValue({- semanticModel: reason === 'missing definition' ? {} : { definition: original }- })-- const result = await store.dispatch(- updateSemanticModel({ ...args, expectedDefinition: reason === 'missing snapshot' ? undefined : original })- )- expect(result.payload.err).toBe(true)- expect(defHttp.put).not.toHaveBeenCalled()- }- )})describe('semantic model tree identity', () => {