World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13853] fix(core): Read model versions and aliases from one statement snapshot (#14319)
Qi Yue2ed33cb7deb
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaMapper.javaindex b7aea19dbb..731b5838aa 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaMapper.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaMapper.java@@ -19,7 +19,9 @@package org.apache.gravitino.storage.relational.mapper;import java.util.List;+import javax.annotation.Nullable;import org.apache.gravitino.storage.relational.po.ModelVersionPO;+import org.apache.gravitino.storage.relational.po.ModelVersionSnapshotRowPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Param;@@ -30,6 +32,27 @@ public interface ModelVersionMetaMapper {String TABLE_NAME = "model_version_info";+ /**+ * Reads active version and alias rows together, validating the observed model identity.+ *+ * @param modelId the observed model ID+ * @param schemaId the observed parent schema ID+ * @param modelName the model name+ * @param version the version number, or null when selecting an alias or listing all versions+ * @param alias the alias, or null when selecting a number or listing all versions+ * @return flat rows from one snapshot, a model-ID-only row when no version matches, or an empty+ * list when the model was dropped, renamed, or moved; version and alias must not both be set+ */+ @SelectProvider(+ type = ModelVersionMetaSQLProviderFactory.class,+ method = "selectModelVersionSnapshot")+ List<ModelVersionSnapshotRowPO> selectModelVersionSnapshot(+ @Param("modelId") Long modelId,+ @Param("schemaId") Long schemaId,+ @Param("modelName") String modelName,+ @Nullable @Param("version") Integer version,+ @Nullable @Param("alias") String alias);+@InsertProvider(type = ModelVersionMetaSQLProviderFactory.class,method = "insertModelVersionMetas")diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaSQLProviderFactory.javaindex 5e0ed868dd..2e455a189c 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaSQLProviderFactory.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaSQLProviderFactory.java@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper;import com.google.common.collect.ImmutableMap;import java.util.List;import java.util.Map;+import javax.annotation.Nullable;import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;import org.apache.gravitino.storage.relational.mapper.provider.base.ModelVersionMetaBaseSQLProvider;import org.apache.gravitino.storage.relational.mapper.provider.h2.ModelVersionMetaH2Provider;@@ -51,6 +52,25 @@ public class ModelVersionMetaSQLProviderFactory {return MODEL_VERSION_META_SQL_PROVIDER_MAP.get(jdbcBackendType);}+ /**+ * Returns a single-statement query for version URI rows and alias rows of the observed model.+ *+ * @param modelId the observed model ID+ * @param schemaId the observed schema ID+ * @param modelName the model name+ * @param version the version number, or null for alias selection or listing+ * @param alias the alias, or null for numeric selection or listing+ * @return the snapshot SQL; version and alias must not both be set+ */+ public static String selectModelVersionSnapshot(+ @Param("modelId") Long modelId,+ @Param("schemaId") Long schemaId,+ @Param("modelName") String modelName,+ @Nullable @Param("version") Integer version,+ @Nullable @Param("alias") String alias) {+ return getProvider().selectModelVersionSnapshot(modelId, schemaId, modelName, version, alias);+ }+public static String insertModelVersionMetas(@Param("modelVersionMetas") List<ModelVersionPO> modelVersionPOs) {return getProvider().insertModelVersionMetas(modelVersionPOs);diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionMetaBaseSQLProvider.javaindex 3e54ab71c7..a52a31b91c 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionMetaBaseSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionMetaBaseSQLProvider.java@@ -19,6 +19,7 @@package org.apache.gravitino.storage.relational.mapper.provider.base;import java.util.List;+import javax.annotation.Nullable;import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;@@ -28,6 +29,72 @@ import org.apache.ibatis.annotations.Param;public class ModelVersionMetaBaseSQLProvider {+ /**+ * Returns a single-statement query for version URI rows and alias rows of the observed model.+ *+ * @param modelId the observed model ID+ * @param schemaId the observed schema ID+ * @param modelName the model name+ * @param version the version number, or null for alias selection or listing+ * @param alias the alias, or null for numeric selection or listing+ * @return the snapshot SQL; version and alias must not both be set+ */+ public String selectModelVersionSnapshot(+ @Param("modelId") Long modelId,+ @Param("schemaId") Long schemaId,+ @Param("modelName") String modelName,+ @Nullable @Param("version") Integer version,+ @Nullable @Param("alias") String alias) {+ String selectedVersion = null;+ if (version != null) {+ selectedVersion = "#{version}";+ } else if (alias != null) {+ selectedVersion =+ "(SELECT target.model_version FROM "+ + ModelVersionAliasRelMapper.TABLE_NAME+ + " target WHERE target.model_id = #{modelId}"+ + " AND target.model_version_alias = #{alias} AND target.deleted_at = 0)";+ }+ String versionFilter = selectedVersion == null ? "" : " AND v.version = " + selectedVersion;+ String aliasFilter = selectedVersion == null ? "" : " AND a.model_version = " + selectedVersion;+ // UNION ALL avoids a URI/alias cross product. The service assembles these flat rows;+ // reading both arms in one statement keeps their aliases and URI values consistent.+ return """+ SELECT m.model_id AS modelId,+ snapshot.metalakeId, snapshot.catalogId, snapshot.schemaId, snapshot.modelVersion,+ snapshot.modelVersionComment, snapshot.modelVersionProperties,+ snapshot.modelVersionUriName, snapshot.modelVersionUri,+ snapshot.auditInfo, snapshot.deletedAt,+ snapshot.aliasVersion, snapshot.aliasName, snapshot.aliasDeletedAt+ FROM %s m+ LEFT JOIN (+ SELECT v.model_id AS snapshotModelId,+ v.metalake_id AS metalakeId, v.catalog_id AS catalogId, v.schema_id AS schemaId,+ v.version AS modelVersion, v.model_version_comment AS modelVersionComment,+ v.model_version_properties AS modelVersionProperties,+ v.model_version_uri_name AS modelVersionUriName,+ v.model_version_uri AS modelVersionUri, v.audit_info AS auditInfo,+ v.deleted_at AS deletedAt,+ NULL AS aliasVersion, NULL AS aliasName, NULL AS aliasDeletedAt+ FROM %s v+ WHERE v.model_id = #{modelId} AND v.deleted_at = 0 %s+ UNION ALL+ SELECT a.model_id, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,+ a.model_version, a.model_version_alias, a.deleted_at+ FROM %s a+ WHERE a.model_id = #{modelId} AND a.deleted_at = 0 %s+ ) snapshot ON snapshot.snapshotModelId = m.model_id+ WHERE m.model_id = #{modelId} AND m.schema_id = #{schemaId}+ AND m.model_name = #{modelName} AND m.deleted_at = 0+ """+ .formatted(+ ModelMetaMapper.TABLE_NAME,+ ModelVersionMetaMapper.TABLE_NAME,+ versionFilter,+ ModelVersionAliasRelMapper.TABLE_NAME,+ aliasFilter);+ }+public String insertModelVersionMetas(@Param("modelVersionMetas") List<ModelVersionPO> modelVersionPOs) {// The model-row reservation increments the allocator before this insert. Subtract one to usediff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelVersionSnapshotRowPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelVersionSnapshotRowPO.javanew file mode 100644index 0000000000..bc93a9ae2a--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelVersionSnapshotRowPO.java@@ -0,0 +1,58 @@+/*+ * 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.storage.relational.po;++import javax.annotation.Nullable;+import lombok.Getter;++/**+ * A flat row from a model-version snapshot query. A row contains URI data, alias data, or only the+ * model ID when no version matches. All rows come from the same statement snapshot.+ */+@Getter+public class ModelVersionSnapshotRowPO {++ private Long modelId;++ @Nullable private Long metalakeId;++ @Nullable private Long catalogId;++ @Nullable private Long schemaId;++ @Nullable private Integer modelVersion;++ @Nullable private String modelVersionComment;++ @Nullable private String modelVersionProperties;++ @Nullable private String modelVersionUriName;++ @Nullable private String modelVersionUri;++ @Nullable private String auditInfo;++ @Nullable private Long deletedAt;++ @Nullable private Integer aliasVersion;++ @Nullable private String aliasName;++ @Nullable private Long aliasDeletedAt;+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.javaindex 71edd37485..28e142920d 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java@@ -20,7 +20,6 @@ package org.apache.gravitino.storage.relational.service;import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;-import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import com.google.common.collect.ArrayListMultimap;import com.google.common.collect.ImmutableList;@@ -28,6 +27,7 @@ import com.google.common.collect.ImmutableSet;import com.google.common.collect.Lists;import com.google.common.collect.Multimap;import java.io.IOException;+import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Locale;@@ -35,21 +35,21 @@ import java.util.Map;import java.util.Objects;import java.util.function.Function;import java.util.stream.Collectors;+import javax.annotation.Nullable;import org.apache.commons.lang3.math.NumberUtils;import org.apache.gravitino.Entity;import org.apache.gravitino.HasIdentifier;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.meta.ModelVersionEntity;import org.apache.gravitino.metrics.Monitored;-import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;import org.apache.gravitino.storage.relational.po.ModelPO;import org.apache.gravitino.storage.relational.po.ModelVersionAliasRelPO;import org.apache.gravitino.storage.relational.po.ModelVersionPO;+import org.apache.gravitino.storage.relational.po.ModelVersionSnapshotRowPO;import org.apache.gravitino.storage.relational.utils.ExceptionUtils;import org.apache.gravitino.storage.relational.utils.POConverters;import org.apache.gravitino.storage.relational.utils.SessionUtils;@@ -62,9 +62,6 @@ public class ModelVersionMetaService {private static final Logger LOG = LoggerFactory.getLogger(ModelVersionMetaService.class);- /** How many times a model-version read is re-run when the model changes underneath it. */- @VisibleForTesting static final int MAX_STABLE_READ_ATTEMPTS = 3;-private static final ModelVersionMetaService INSTANCE = new ModelVersionMetaService();public static ModelVersionMetaService getInstance() {@@ -80,8 +77,8 @@ public class ModelVersionMetaService {NamespaceUtil.checkModelVersion(ns);NameIdentifier modelIdent = NameIdentifier.of(ns.levels());- return readWithStableModel(- modelIdent, modelPO -> listModelVersions(modelIdent, modelPO.getModelId()));+ ModelVersionSnapshot snapshot = readSnapshot(modelIdent, null, null);+ return listModelVersions(modelIdent, snapshot);}@Monitored(@@ -91,8 +88,16 @@ public class ModelVersionMetaService {NameIdentifierUtil.checkModelVersion(ident);NameIdentifier modelIdent = NameIdentifier.of(ident.namespace().levels());- return readWithStableModel(- modelIdent, modelPO -> getModelVersion(ident, modelIdent, modelPO.getModelId()));+ boolean isVersionNumber = NumberUtils.isCreatable(ident.name());+ ModelVersionSnapshot snapshot =+ readSnapshot(+ modelIdent,+ isVersionNumber ? Integer.valueOf(ident.name()) : null,+ isVersionNumber ? null : ident.name());+ if (snapshot.modelVersions.isEmpty()) {+ throw noSuchModelVersionException(ident);+ }+ return POConverters.fromModelVersionPO(modelIdent, snapshot.modelVersions, snapshot.aliases);}@Monitored(@@ -376,20 +381,15 @@ public class ModelVersionMetaService {return !oldAliases.equals(newAliases);}- private List<ModelVersionEntity> listModelVersions(NameIdentifier modelIdent, long modelId) {- List<ModelVersionPO> modelVersionPOs =- SessionUtils.getWithoutCommit(- ModelVersionMetaMapper.class, mapper -> mapper.listModelVersionMetasByModelId(modelId));+ private List<ModelVersionEntity> listModelVersions(+ NameIdentifier modelIdent, ModelVersionSnapshot snapshot) {+ List<ModelVersionPO> modelVersionPOs = snapshot.modelVersions;if (modelVersionPOs.isEmpty()) {return Collections.emptyList();}- // Get the aliases for all the model versions.- List<ModelVersionAliasRelPO> aliasRelPOs =- SessionUtils.getWithoutCommit(- ModelVersionAliasRelMapper.class,- mapper -> mapper.selectModelVersionAliasRelsByModelId(modelId));+ List<ModelVersionAliasRelPO> aliasRelPOs = snapshot.aliases;Multimap<Integer, ModelVersionAliasRelPO> aliasRelPOsByModelVersion =ArrayListMultimap.create();aliasRelPOs.forEach(r -> aliasRelPOsByModelVersion.put(r.getModelVersion(), r));@@ -410,95 +410,68 @@ public class ModelVersionMetaService {.values());}- private ModelVersionEntity getModelVersion(- NameIdentifier ident, NameIdentifier modelIdent, long modelId) {- boolean isVersionNumber = NumberUtils.isCreatable(ident.name());-- List<ModelVersionPO> modelVersionPOs =+ private ModelVersionSnapshot readSnapshot(+ NameIdentifier modelIdent, @Nullable Integer version, @Nullable String alias) {+ ModelPO modelPO = ModelMetaService.getInstance().getModelPOByIdentifier(modelIdent);+ // The initial lookup preserves namespace validation and pins the model identity. Version+ // rows, alias resolution, and model existence are then read in one statement snapshot, so+ // linking or altering the model cannot tear the result or force a read to retry.+ List<ModelVersionSnapshotRowPO> rows =SessionUtils.getWithoutCommit(ModelVersionMetaMapper.class,- mapper -> {- if (isVersionNumber) {- return mapper.selectModelVersionMeta(modelId, Integer.valueOf(ident.name()));- } else {- return mapper.selectModelVersionMetaByAlias(modelId, ident.name());- }- });-- if (modelVersionPOs.isEmpty()) {+ mapper ->+ mapper.selectModelVersionSnapshot(+ modelPO.getModelId(),+ modelPO.getSchemaId(),+ modelIdent.name(),+ version,+ alias));+ if (rows.isEmpty()) {throw new NoSuchEntityException(NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,- Entity.EntityType.MODEL_VERSION.name().toLowerCase(Locale.ROOT),- ident.toString());+ Entity.EntityType.MODEL.name().toLowerCase(Locale.ROOT),+ modelIdent.toString());}-- List<ModelVersionAliasRelPO> aliasRelPOs =- SessionUtils.getWithoutCommit(- ModelVersionAliasRelMapper.class,- mapper -> {- if (isVersionNumber) {- return mapper.selectModelVersionAliasRelsByModelIdAndVersion(- modelId, Integer.valueOf(ident.name()));- } else {- return mapper.selectModelVersionAliasRelsByModelIdAndAlias(modelId, ident.name());- }- });-- return POConverters.fromModelVersionPO(modelIdent, modelVersionPOs, aliasRelPOs);+ List<ModelVersionPO> modelVersions = new ArrayList<>();+ List<ModelVersionAliasRelPO> aliases = new ArrayList<>();+ for (ModelVersionSnapshotRowPO row : rows) {+ if (row.getModelVersion() != null) {+ modelVersions.add(+ ModelVersionPO.builder()+ .withModelId(row.getModelId())+ .withMetalakeId(row.getMetalakeId())+ .withCatalogId(row.getCatalogId())+ .withSchemaId(row.getSchemaId())+ .withModelVersion(row.getModelVersion())+ .withModelVersionComment(row.getModelVersionComment())+ .withModelVersionProperties(row.getModelVersionProperties())+ .withModelVersionUriName(row.getModelVersionUriName())+ .withModelVersionUri(row.getModelVersionUri())+ .withAuditInfo(row.getAuditInfo())+ .withDeletedAt(row.getDeletedAt())+ .build());+ } else if (row.getAliasVersion() != null) {+ aliases.add(+ ModelVersionAliasRelPO.builder()+ .withModelId(row.getModelId())+ .withModelVersion(row.getAliasVersion())+ .withModelVersionAlias(row.getAliasName())+ .withDeletedAt(row.getAliasDeletedAt())+ .build());+ }+ // A model-ID-only row represents an existing model with no matching version.+ }+ return new ModelVersionSnapshot(modelVersions, aliases);}- /**- * Runs a read of a model's version and alias rows and returns it only if the model did not change- * while the rows were read.- *- * <p>The version rows and the alias rows are read by separate statements, so a concurrent link,- * alter or delete could otherwise be seen half applied, for example with the old URIs and the new- * aliases. Every such write advances the model row's {@code current_version} in its own- * transaction, so an unchanged version after the read proves the rows belong to one committed- * state. A changed version re-runs the read, up to {@link #MAX_STABLE_READ_ATTEMPTS} times.- *- * <p>{@code current_version} is the model's aggregate concurrency token, so model-level writes- * such as a comment or property change through {@code alterModel} also advance it. Those writes- * cannot tear the version and alias rows, but they still make a concurrent read retry, and a- * model altered on every attempt fails the read with {@link OptimisticLockException}.- *- * @param modelIdent the identifier of the model whose rows are read- * @param read the read to run against the observed model row- * @return the result of a read that saw no concurrent model change- * @throws NoSuchEntityException if the model does not exist, or was dropped during the read- * @throws OptimisticLockException if the model kept changing- */- @VisibleForTesting- <T> T readWithStableModel(NameIdentifier modelIdent, Function<ModelPO, T> read) {- for (int attempt = 1; ; attempt++) {- // Will throw a NoSuchEntityException if the model does not exist.- ModelPO observedModelPO = ModelMetaService.getInstance().getModelPOByIdentifier(modelIdent);- T result = read.apply(observedModelPO);-- ModelPO currentModelPO =- SessionUtils.getWithoutCommit(- ModelMetaMapper.class,- mapper -> mapper.selectModelMetaByModelId(observedModelPO.getModelId()));- if (currentModelPO == null) {- throw new NoSuchEntityException(- NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,- Entity.EntityType.MODEL.name().toLowerCase(Locale.ROOT),- modelIdent.toString());- }- if (Objects.equals(currentModelPO.getCurrentVersion(), observedModelPO.getCurrentVersion())) {- return result;- }- if (attempt >= MAX_STABLE_READ_ATTEMPTS) {- throw ExceptionUtils.concurrentModification(Entity.EntityType.MODEL, modelIdent);- }- // Re-read immediately: a read through the entity cache holds its cache segment lock here,- // so pausing would also stall unrelated entities hashed to the same segment. Spacing the- // attempts needs the retry loop lifted above that lock, or a single-statement read that- // cannot tear; both are left to #13181, so do not add a sleep inside this loop.- LOG.debug(- "Model {} changed during attempt {} of a model-version read, reading it again",- modelIdent,- attempt);+ private static final class ModelVersionSnapshot {+ private final List<ModelVersionPO> modelVersions;+ private final List<ModelVersionAliasRelPO> aliases;++ private ModelVersionSnapshot(+ List<ModelVersionPO> modelVersions, List<ModelVersionAliasRelPO> aliases) {+ this.modelVersions = modelVersions;+ this.aliases = aliases;}}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.javaindex 903c751128..b2e344b4bb 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java@@ -27,6 +27,7 @@ import java.time.Instant;import java.util.Collections;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.UUID;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;@@ -34,6 +35,7 @@ import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;+import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;import java.util.function.Function;import java.util.stream.Collectors;@@ -57,6 +59,7 @@ import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;import org.apache.gravitino.storage.relational.po.ModelPO;import org.apache.gravitino.storage.relational.po.ModelVersionAliasRelPO;+import org.apache.gravitino.storage.relational.po.ModelVersionSnapshotRowPO;import org.apache.gravitino.storage.relational.po.SchemaPO;import org.apache.gravitino.storage.relational.utils.SessionUtils;import org.apache.gravitino.utils.NameIdentifierUtil;@@ -1866,121 +1869,291 @@ public class TestModelVersionMetaService extends TestJDBCBackend {}@TestTemplate- public void testGetModelVersionByNumberRereadsConcurrentUpdate() throws IOException {- assertModelVersionReadRereads(+ void testGetByNumberReturnsSnapshotDuringVersionUpdate() throws IOException {+ assertSnapshotRead(version ->List.of(ModelVersionMetaService.getInstance()- .getModelVersionByIdentifier(version.nameIdentifier())));+ .getModelVersionByIdentifier(version.nameIdentifier())),+ SnapshotWrite.VERSION_UPDATE);}@TestTemplate- public void testGetModelVersionByAliasRereadsConcurrentUpdate() throws IOException {- assertModelVersionReadRereads(+ void testGetByAliasReturnsSnapshotDuringVersionUpdate() throws IOException {+ assertSnapshotRead(version ->List.of(ModelVersionMetaService.getInstance().getModelVersionByIdentifier(- NameIdentifier.of(version.namespace(), "stable_read_alias"))));+ NameIdentifier.of(version.namespace(), "snapshot_alias"))),+ SnapshotWrite.VERSION_UPDATE);}@TestTemplate- public void testListModelVersionsRereadsConcurrentUpdate() throws IOException {- assertModelVersionReadRereads(+ void testListReturnsSnapshotDuringVersionUpdate() throws IOException {+ assertSnapshotRead(version ->- ModelVersionMetaService.getInstance()- .listModelVersionsByNamespace(version.namespace()));+ ModelVersionMetaService.getInstance().listModelVersionsByNamespace(version.namespace()),+ SnapshotWrite.VERSION_UPDATE);}@TestTemplate- public void testReadWithStableModelRereadsAfterConcurrentVersionChange() throws IOException {- ModelVersionEntity version = insertModelWithVersion("stable_read_alias");- AtomicInteger reads = new AtomicInteger();+ void testGetByNumberDoesNotRetryModelAlter() throws IOException {+ assertSnapshotRead(+ version ->+ List.of(+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(version.nameIdentifier())),+ SnapshotWrite.MODEL_ALTER);+ }- String result =- ModelVersionMetaService.getInstance()- .readWithStableModel(- version.modelIdentifier(),- modelPO -> {- if (reads.incrementAndGet() == 1) {- // A writer commits between the version-row and alias-row reads of the first- // attempt, so that attempt may have combined two states.- updateModelVersionUnchecked(- version.nameIdentifier(), current -> copyModelVersion(current, "changed"));- return "torn";- }- return "stable";- });+ @TestTemplate+ void testGetByAliasDoesNotRetryModelAlter() throws IOException {+ assertSnapshotRead(+ version ->+ List.of(+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(+ NameIdentifier.of(version.namespace(), "snapshot_alias"))),+ SnapshotWrite.MODEL_ALTER);+ }- Assertions.assertEquals("stable", result);- Assertions.assertEquals(2, reads.get());+ @TestTemplate+ void testListDoesNotRetryModelAlter() throws IOException {+ assertSnapshotRead(+ version ->+ ModelVersionMetaService.getInstance().listModelVersionsByNamespace(version.namespace()),+ SnapshotWrite.MODEL_ALTER);}@TestTemplate- public void testReadWithStableModelRereadsAfterConcurrentModelAlter() throws IOException {- ModelVersionEntity version = insertModelWithVersion("model_alter_read_alias");- AtomicInteger reads = new AtomicInteger();+ void testGetByNumberDoesNotRetryVersionLink() throws IOException {+ assertSnapshotRead(+ version ->+ List.of(+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(version.nameIdentifier())),+ SnapshotWrite.VERSION_LINK);+ }++ @TestTemplate+ void testGetByAliasDoesNotRetryVersionLink() throws IOException {+ assertSnapshotRead(+ version ->+ List.of(+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(+ NameIdentifier.of(version.namespace(), "snapshot_alias"))),+ SnapshotWrite.VERSION_LINK);+ }++ @TestTemplate+ void testListDoesNotRetryVersionLink() throws IOException {+ assertSnapshotRead(+ version ->+ ModelVersionMetaService.getInstance().listModelVersionsByNamespace(version.namespace()),+ SnapshotWrite.VERSION_LINK);+ }- String result =+ @TestTemplate+ void testSnapshotRejectsModelRenamedAfterLookup() throws IOException {+ ModelVersionEntity version = insertModelWithVersion("snapshot_alias");+ try (MockedStatic<SessionUtils> sessions =+ Mockito.mockStatic(SessionUtils.class, Mockito.CALLS_REAL_METHODS)) {+ sessions+ .when(+ () ->+ SessionUtils.getWithoutCommit(+ Mockito.eq(ModelVersionMetaMapper.class), Mockito.any()))+ .thenAnswer(+ invocation -> {+ Function<ModelEntity, ModelEntity> rename =+ current ->+ createModelEntity(+ current.id(),+ current.namespace(),+ "renamed_model",+ current.comment(),+ current.latestVersion(),+ current.properties(),+ current.auditInfo());+ ModelMetaService.getInstance().updateModel(version.modelIdentifier(), rename);+ return invocation.callRealMethod();+ });+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(version.nameIdentifier()));+ }+ ModelVersionEntity renamed =ModelVersionMetaService.getInstance()- .readWithStableModel(- version.modelIdentifier(),- modelPO -> {- if (reads.incrementAndGet() == 1) {- // A comment-only alter cannot tear the version rows, but it advances the- // model's aggregate token, so the read is re-run.- updateModelUnchecked(version.modelIdentifier(), "altered model comment");- return "before alter";- }- return "after alter";- });+ .getModelVersionByIdentifier(+ NameIdentifier.of(+ METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "renamed_model", "snapshot_alias"));+ Assertions.assertEquals(version.uris(), renamed.uris());+ }- Assertions.assertEquals("after alter", result);- Assertions.assertEquals(2, reads.get());+ @TestTemplate+ void testSnapshotDistinguishesEmptyModelFromMissingVersion() throws IOException {+ ModelVersionEntity version = insertModelWithVersion("snapshot_alias");+ Assertions.assertTrue(+ ModelVersionMetaService.getInstance().deleteModelVersion(version.nameIdentifier()));+ Assertions.assertTrue(+ ModelVersionMetaService.getInstance()+ .listModelVersionsByNamespace(version.namespace())+ .isEmpty());+ NoSuchEntityException missing =+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(version.nameIdentifier()));+ Assertions.assertTrue(missing.getMessage().contains("model_version"));}@TestTemplate- public void testReadWithStableModelGivesUpWhenModelKeepsChanging() throws IOException {- ModelVersionEntity version = insertModelWithVersion("busy_read_alias");- AtomicInteger reads = new AtomicInteger();+ void testSnapshotRejectsModelDroppedAfterLookup() throws IOException {+ ModelVersionEntity version = insertModelWithVersion("snapshot_alias");+ try (MockedStatic<SessionUtils> sessions =+ Mockito.mockStatic(SessionUtils.class, Mockito.CALLS_REAL_METHODS)) {+ sessions+ .when(+ () ->+ SessionUtils.getWithoutCommit(+ Mockito.eq(ModelVersionMetaMapper.class), Mockito.any()))+ .thenAnswer(+ invocation -> {+ Assertions.assertTrue(+ ModelMetaService.getInstance().deleteModel(version.modelIdentifier()));+ return invocation.callRealMethod();+ });+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ ModelVersionMetaService.getInstance()+ .listModelVersionsByNamespace(version.namespace()));+ }+ }- Assertions.assertThrows(- OptimisticLockException.class,- () ->- ModelVersionMetaService.getInstance()- .readWithStableModel(- version.modelIdentifier(),- modelPO -> {- updateModelVersionUnchecked(- version.nameIdentifier(),- current ->- copyModelVersion(current, "change " + reads.incrementAndGet()));- return null;- }));- Assertions.assertEquals(ModelVersionMetaService.MAX_STABLE_READ_ATTEMPTS, reads.get());+ @TestTemplate+ void testSnapshotDoesNotFollowReplacementModel() throws IOException {+ ModelVersionEntity version = insertModelWithVersion("snapshot_alias");+ AtomicBoolean replaced = new AtomicBoolean();+ try (MockedStatic<SessionUtils> sessions =+ Mockito.mockStatic(SessionUtils.class, Mockito.CALLS_REAL_METHODS)) {+ sessions+ .when(+ () ->+ SessionUtils.getWithoutCommit(+ Mockito.eq(ModelVersionMetaMapper.class), Mockito.any()))+ .thenAnswer(+ invocation -> {+ if (replaced.compareAndSet(false, true)) {+ Assertions.assertTrue(+ ModelMetaService.getInstance().deleteModel(version.modelIdentifier()));+ ModelEntity replacement =+ createModelEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ MODEL_NS,+ version.modelIdentifier().name(),+ "replacement",+ 0,+ properties,+ AUDIT_INFO);+ ModelMetaService.getInstance().insertModel(replacement, false);+ }+ return invocation.callRealMethod();+ });+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(version.nameIdentifier()));+ }+ Assertions.assertTrue(replaced.get());+ Assertions.assertTrue(+ ModelVersionMetaService.getInstance()+ .listModelVersionsByNamespace(version.namespace())+ .isEmpty());}@TestTemplate- public void testReadWithStableModelReportsModelDroppedDuringRead() throws IOException {- ModelVersionEntity version = insertModelWithVersion("dropped_read_alias");+ void testSnapshotKeepsAllUrisAndAliasesAcrossVersions() throws IOException {+ ModelVersionEntity first = insertModelWithVersion("first_alias");+ Map<String, String> uris =+ ImmutableMap.of("uri_a", "path_a", "uri_b", "path_b", "uri_c", "path_c");+ updateModelVersionUnchecked(+ first.nameIdentifier(),+ current ->+ createModelVersionEntity(+ current.modelIdentifier(),+ current.version(),+ uris,+ List.of("first_alias", "other_alias", "third_alias"),+ current.comment(),+ current.properties(),+ current.auditInfo()));+ ModelVersionEntity second =+ createModelVersionEntity(+ first.modelIdentifier(),+ 1,+ ImmutableMap.of("uri_c", "path_c"),+ Collections.emptyList(),+ "no aliases",+ properties,+ AUDIT_INFO);+ ModelVersionMetaService.getInstance().insertModelVersion(second);- Assertions.assertThrows(- NoSuchEntityException.class,- () ->- ModelVersionMetaService.getInstance()- .readWithStableModel(- version.modelIdentifier(),- modelPO -> {- Assertions.assertTrue(- ModelMetaService.getInstance().deleteModel(version.modelIdentifier()));- return null;- }));+ ModelPO model = ModelMetaService.getInstance().getModelPOByIdentifier(first.modelIdentifier());+ List<ModelVersionSnapshotRowPO> rows =+ SessionUtils.getWithoutCommit(+ ModelVersionMetaMapper.class,+ mapper ->+ mapper.selectModelVersionSnapshot(+ model.getModelId(),+ model.getSchemaId(),+ first.modelIdentifier().name(),+ null,+ null));+ // Three URIs and three aliases must yield six rows, rather than a nine-row cross product.+ // The second version contributes one URI row and has no aliases.+ Assertions.assertEquals(7, rows.size());+ Assertions.assertEquals(4, rows.stream().filter(row -> row.getModelVersion() != null).count());+ Assertions.assertEquals(3, rows.stream().filter(row -> row.getAliasVersion() != null).count());++ List<ModelVersionEntity> versions =+ ModelVersionMetaService.getInstance().listModelVersionsByNamespace(first.namespace());+ Assertions.assertEquals(2, versions.size());+ Map<Integer, ModelVersionEntity> byNumber =+ versions.stream()+ .collect(Collectors.toMap(ModelVersionEntity::version, Function.identity()));+ Assertions.assertEquals(uris, byNumber.get(0).uris());+ Assertions.assertEquals(+ Set.of("first_alias", "other_alias", "third_alias"), Set.copyOf(byNumber.get(0).aliases()));+ Assertions.assertEquals(3, byNumber.get(0).aliases().size());+ Assertions.assertEquals(second.uris(), byNumber.get(1).uris());+ Assertions.assertTrue(byNumber.get(1).aliases().isEmpty());+ ModelVersionEntity selected =+ ModelVersionMetaService.getInstance()+ .getModelVersionByIdentifier(NameIdentifier.of(first.namespace(), "other_alias"));+ Assertions.assertEquals(uris, selected.uris());+ Assertions.assertEquals(+ Set.of("first_alias", "other_alias", "third_alias"), Set.copyOf(selected.aliases()));}- private void assertModelVersionReadRereads(- Function<ModelVersionEntity, List<ModelVersionEntity>> read) throws IOException {- ModelVersionEntity version = insertModelWithVersion("stable_read_alias");- AtomicInteger versionReads = new AtomicInteger();+ private enum SnapshotWrite {+ VERSION_UPDATE,+ MODEL_ALTER,+ VERSION_LINK+ }++ private void assertSnapshotRead(+ Function<ModelVersionEntity, List<ModelVersionEntity>> read, SnapshotWrite write)+ throws IOException {+ ModelVersionEntity version = insertModelWithVersion("snapshot_alias");+ AtomicInteger reads = new AtomicInteger();+ AtomicBoolean writing = new AtomicBoolean();try (MockedStatic<SessionUtils> sessions =Mockito.mockStatic(SessionUtils.class, Mockito.CALLS_REAL_METHODS)) {sessions@@ -1990,30 +2163,51 @@ public class TestModelVersionMetaService extends TestJDBCBackend {Mockito.eq(ModelVersionMetaMapper.class), Mockito.any())).thenAnswer(invocation -> {- Object rows = invocation.callRealMethod();- if (versionReads.incrementAndGet() == 1) {- // Commit after the first version-row query, before its alias query. Without- // the stable-read check the caller would see the old URI and the new alias.- updateModelVersionUnchecked(- version.nameIdentifier(),- current ->- ModelVersionEntity.builder()- .withModelIdentifier(current.modelIdentifier())- .withVersion(current.version())- .withUris(ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "new_path"))- .withAliases(ImmutableList.of("stable_read_alias", "new_alias"))- .withComment(current.comment())- .withProperties(current.properties())- .withAuditInfo(current.auditInfo())- .build());+ Object snapshot = invocation.callRealMethod();+ if (writing.compareAndSet(false, true)) {+ try {+ reads.incrementAndGet();+ // Commit after every version read. The old split-read path exhausts its+ // retry budget; a statement snapshot remains complete and can be returned.+ if (write == SnapshotWrite.MODEL_ALTER) {+ updateModelUnchecked(version.modelIdentifier(), "changed " + reads.get());+ } else if (write == SnapshotWrite.VERSION_LINK) {+ ModelVersionMetaService.getInstance()+ .insertModelVersion(+ createModelVersionEntity(+ version.modelIdentifier(),+ reads.get(),+ ImmutableMap.of(+ ModelVersion.URI_NAME_UNKNOWN, "linked_path_" + reads.get()),+ Collections.emptyList(),+ "linked",+ properties,+ AUDIT_INFO));+ } else {+ updateModelVersionUnchecked(+ version.nameIdentifier(),+ current ->+ createModelVersionEntity(+ current.modelIdentifier(),+ current.version(),+ ImmutableMap.of(+ ModelVersion.URI_NAME_UNKNOWN, "new_path_" + reads.get()),+ List.of("snapshot_alias", "new_alias"),+ current.comment(),+ current.properties(),+ current.auditInfo()));+ }+ } finally {+ writing.set(false);+ }}- return rows;+ return snapshot;});-List<ModelVersionEntity> result = read.apply(version);Assertions.assertEquals(1, result.size());- Assertions.assertEquals("new_path", result.get(0).uris().get(ModelVersion.URI_NAME_UNKNOWN));- Assertions.assertTrue(result.get(0).aliases().contains("new_alias"));+ Assertions.assertEquals(version.uris(), result.get(0).uris());+ Assertions.assertEquals(version.aliases(), result.get(0).aliases());+ Assertions.assertEquals(1, reads.get());}}