Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#12348] improvement(core): add OCC for model writes (#12649)

Qi Yuc5a7ad1119c3
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaMapper.java
index 9fc338ad98..eea9e3fba8 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaMapper.java
@@ -75,11 +75,29 @@ public interface ModelMetaMapper {
@SelectProvider(type = ModelMetaSQLProviderFactory.class, method = "selectModelMetaByModelId")
ModelPO selectModelMetaByModelId(@Param("modelId") Long modelId);
+ /**
+ * Selects and exclusively locks an active model metadata row.
+ *
+ * @param modelId the model ID
+ * @return the active model metadata, or {@code null} when it no longer exists
+ */
+ @SelectProvider(
+ type = ModelMetaSQLProviderFactory.class,
+ method = "selectModelMetaByModelIdForUpdate")
+ ModelPO selectModelMetaByModelIdForUpdate(@Param("modelId") Long modelId);
+
+ /**
+ * Soft-deletes a model only if its stored version is unchanged.
+ *
+ * @param modelId the model ID
+ * @param currentVersion the version observed by the caller
+ * @return the number of changed rows; zero means the model changed or disappeared
+ */
@UpdateProvider(
type = ModelMetaSQLProviderFactory.class,
- method = "softDeleteModelMetaBySchemaIdAndModelName")
- Integer softDeleteModelMetaBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName);
+ method = "softDeleteModelMetaByIdAndVersion")
+ Integer softDeleteModelMetaByIdAndVersion(
+ @Param("modelId") Long modelId, @Param("currentVersion") Long currentVersion);
@UpdateProvider(
type = ModelMetaSQLProviderFactory.class,
@@ -102,8 +120,37 @@ public interface ModelMetaMapper {
Integer deleteModelMetasByLegacyTimeline(
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);
- @UpdateProvider(type = ModelMetaSQLProviderFactory.class, method = "updateModelLatestVersion")
- Integer updateModelLatestVersion(@Param("modelId") Long modelId);
+ /**
+ * Advances the concurrency version shared by a model and its child records, as long as the model
+ * still exists under the name the caller resolved.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the number of changed rows; zero means the model was dropped or renamed away
+ */
+ @UpdateProvider(type = ModelMetaSQLProviderFactory.class, method = "bumpModelVersion")
+ Integer bumpModelVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName);
+
+ /**
+ * Advances the shared concurrency version and the version-number allocator in one write, as long
+ * as the model still exists under the name the caller resolved.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the number of changed rows; zero means the model was dropped or renamed away
+ */
+ @UpdateProvider(
+ type = ModelMetaSQLProviderFactory.class,
+ method = "bumpModelVersionAndLatestVersion")
+ Integer bumpModelVersionAndLatestVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName);
@UpdateProvider(type = ModelMetaSQLProviderFactory.class, method = "updateModelMeta")
Integer updateModelMeta(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaSQLProviderFactory.java
index d16a5c485b..89347a6318 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaSQLProviderFactory.java
@@ -97,9 +97,26 @@ public class ModelMetaSQLProviderFactory {
return getProvider().selectModelMetaByModelId(modelId);
}
- public static String softDeleteModelMetaBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
- return getProvider().softDeleteModelMetaBySchemaIdAndModelName(schemaId, modelName);
+ /**
+ * Returns SQL that selects and exclusively locks an active model metadata row.
+ *
+ * @param modelId the model ID
+ * @return the locking select SQL
+ */
+ public static String selectModelMetaByModelIdForUpdate(@Param("modelId") Long modelId) {
+ return getProvider().selectModelMetaByModelIdForUpdate(modelId);
+ }
+
+ /**
+ * Returns SQL that soft-deletes a model with a version check.
+ *
+ * @param modelId the model ID
+ * @param currentVersion the version observed by the caller
+ * @return the version-checked soft-delete SQL
+ */
+ public static String softDeleteModelMetaByIdAndVersion(
+ @Param("modelId") Long modelId, @Param("currentVersion") Long currentVersion) {
+ return getProvider().softDeleteModelMetaByIdAndVersion(modelId, currentVersion);
}
public static String softDeleteModelMetasByCatalogId(@Param("catalogId") Long catalogId) {
@@ -119,8 +136,35 @@ public class ModelMetaSQLProviderFactory {
return getProvider().deleteModelMetasByLegacyTimeline(legacyTimeline, limit);
}
- public static String updateModelLatestVersion(@Param("modelId") Long modelId) {
- return getProvider().updateModelLatestVersion(modelId);
+ /**
+ * Returns SQL that advances the shared model concurrency version while the model still exists
+ * under the name the caller resolved.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the version bump SQL
+ */
+ public static String bumpModelVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName) {
+ return getProvider().bumpModelVersion(modelId, schemaId, modelName);
+ }
+
+ /**
+ * Returns SQL that advances the shared concurrency version and version-number allocator.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the version registration SQL
+ */
+ public static String bumpModelVersionAndLatestVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName) {
+ return getProvider().bumpModelVersionAndLatestVersion(modelId, schemaId, modelName);
}
public static String updateModelMeta(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasRelMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasRelMapper.java
index 2a330e9273..301724bc3e 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasRelMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasRelMapper.java
@@ -59,11 +59,16 @@ public interface ModelVersionAliasRelMapper {
List<ModelVersionAliasRelPO> selectModelVersionAliasRelsByModelIdAndAlias(
@Param("modelId") Long modelId, @Param("alias") String alias);
+ /**
+ * Soft-deletes every active alias row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the number of changed rows
+ */
@UpdateProvider(
type = ModelVersionAliasSQLProviderFactory.class,
- method = "softDeleteModelVersionAliasRelsBySchemaIdAndModelName")
- Integer softDeleteModelVersionAliasRelsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName);
+ method = "softDeleteModelVersionAliasRelsByModelId")
+ Integer softDeleteModelVersionAliasRelsByModelId(@Param("modelId") Long modelId);
@UpdateProvider(
type = ModelVersionAliasSQLProviderFactory.class,
@@ -71,12 +76,6 @@ public interface ModelVersionAliasRelMapper {
Integer softDeleteModelVersionAliasRelsByModelIdAndVersion(
@Param("modelId") Long modelId, @Param("modelVersion") Integer modelVersion);
- @UpdateProvider(
- type = ModelVersionAliasSQLProviderFactory.class,
- method = "softDeleteModelVersionAliasRelsByModelIdAndAlias")
- Integer softDeleteModelVersionAliasRelsByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias);
-
@UpdateProvider(
type = ModelVersionAliasSQLProviderFactory.class,
method = "softDeleteModelVersionAliasRelsBySchemaIds")
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasSQLProviderFactory.java
index 517728bd84..f9e62de68e 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasSQLProviderFactory.java
@@ -70,9 +70,14 @@ public class ModelVersionAliasSQLProviderFactory {
return getProvider().selectModelVersionAliasRelsByModelIdAndAlias(modelId, alias);
}
- public static String softDeleteModelVersionAliasRelsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
- return getProvider().softDeleteModelVersionAliasRelsBySchemaIdAndModelName(schemaId, modelName);
+ /**
+ * Returns SQL that soft-deletes every active alias row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the soft-delete SQL
+ */
+ public static String softDeleteModelVersionAliasRelsByModelId(@Param("modelId") Long modelId) {
+ return getProvider().softDeleteModelVersionAliasRelsByModelId(modelId);
}
public static String softDeleteModelVersionAliasRelsByModelIdAndVersion(
@@ -80,11 +85,6 @@ public class ModelVersionAliasSQLProviderFactory {
return getProvider().softDeleteModelVersionAliasRelsByModelIdAndVersion(modelId, modelVersion);
}
- public static String softDeleteModelVersionAliasRelsByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return getProvider().softDeleteModelVersionAliasRelsByModelIdAndAlias(modelId, alias);
- }
-
public static String softDeleteModelVersionAliasRelsBySchemaIds(
@Param("schemaIds") List<Long> schemaIds) {
return getProvider().softDeleteModelVersionAliasRelsBySchemaIds(schemaIds);
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.java
index 0cb2f91564..b7aea19dbb 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
@@ -58,11 +58,16 @@ public interface ModelVersionMetaMapper {
List<ModelVersionPO> selectModelVersionMetaByAlias(
@Param("modelId") Long modelId, @Param("alias") String alias);
+ /**
+ * Soft-deletes every active version row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the number of changed rows
+ */
@UpdateProvider(
type = ModelVersionMetaSQLProviderFactory.class,
- method = "softDeleteModelVersionsBySchemaIdAndModelName")
- Integer softDeleteModelVersionsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName);
+ method = "softDeleteModelVersionsByModelId")
+ Integer softDeleteModelVersionsByModelId(@Param("modelId") Long modelId);
@UpdateProvider(
type = ModelVersionMetaSQLProviderFactory.class,
@@ -70,12 +75,6 @@ public interface ModelVersionMetaMapper {
Integer softDeleteModelVersionMetaByModelIdAndVersion(
@Param("modelId") Long modelId, @Param("modelVersion") Integer modelVersion);
- @UpdateProvider(
- type = ModelVersionMetaSQLProviderFactory.class,
- method = "softDeleteModelVersionMetaByModelIdAndAlias")
- Integer softDeleteModelVersionMetaByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias);
-
@UpdateProvider(
type = ModelVersionMetaSQLProviderFactory.class,
method = "softDeleteModelVersionMetasBySchemaIds")
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.java
index 8849270d37..5e0ed868dd 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
@@ -75,9 +75,14 @@ public class ModelVersionMetaSQLProviderFactory {
return getProvider().selectModelVersionMetaByAlias(modelId, alias);
}
- public static String softDeleteModelVersionsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
- return getProvider().softDeleteModelVersionsBySchemaIdAndModelName(schemaId, modelName);
+ /**
+ * Returns SQL that soft-deletes every active version row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the soft-delete SQL
+ */
+ public static String softDeleteModelVersionsByModelId(@Param("modelId") Long modelId) {
+ return getProvider().softDeleteModelVersionsByModelId(modelId);
}
public static String softDeleteModelVersionMetaByModelIdAndVersion(
@@ -85,11 +90,6 @@ public class ModelVersionMetaSQLProviderFactory {
return getProvider().softDeleteModelVersionMetaByModelIdAndVersion(modelId, modelVersion);
}
- public static String softDeleteModelVersionMetaByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return getProvider().softDeleteModelVersionMetaByModelIdAndAlias(modelId, alias);
- }
-
public static String softDeleteModelVersionMetasBySchemaIds(
@Param("schemaIds") List<Long> schemaIds) {
return getProvider().softDeleteModelVersionMetasBySchemaIds(schemaIds);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelMetaBaseSQLProvider.java
index 3f9848ae98..05571f5254 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelMetaBaseSQLProvider.java
@@ -32,10 +32,12 @@ public class ModelMetaBaseSQLProvider {
return "INSERT INTO "
+ ModelMetaMapper.TABLE_NAME
+ " (model_id, model_name, metalake_id, catalog_id, schema_id,"
- + " model_comment, model_properties, model_latest_version, audit_info, deleted_at)"
+ + " model_comment, model_properties, model_latest_version, current_version, last_version,"
+ + " audit_info, deleted_at)"
+ " VALUES (#{modelMeta.modelId}, #{modelMeta.modelName}, #{modelMeta.metalakeId},"
+ " #{modelMeta.catalogId}, #{modelMeta.schemaId}, #{modelMeta.modelComment},"
- + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion}, #{modelMeta.auditInfo},"
+ + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion},"
+ + " #{modelMeta.currentVersion}, #{modelMeta.lastVersion}, #{modelMeta.auditInfo},"
+ " #{modelMeta.deletedAt})";
}
@@ -43,10 +45,12 @@ public class ModelMetaBaseSQLProvider {
return "INSERT INTO "
+ ModelMetaMapper.TABLE_NAME
+ " (model_id, model_name, metalake_id, catalog_id, schema_id,"
- + " model_comment, model_properties, model_latest_version, audit_info, deleted_at)"
+ + " model_comment, model_properties, model_latest_version, current_version, last_version,"
+ + " audit_info, deleted_at)"
+ " VALUES (#{modelMeta.modelId}, #{modelMeta.modelName}, #{modelMeta.metalakeId},"
+ " #{modelMeta.catalogId}, #{modelMeta.schemaId}, #{modelMeta.modelComment},"
- + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion}, #{modelMeta.auditInfo},"
+ + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion},"
+ + " #{modelMeta.currentVersion}, #{modelMeta.lastVersion}, #{modelMeta.auditInfo},"
+ " #{modelMeta.deletedAt})"
+ " ON DUPLICATE KEY UPDATE"
+ " model_name = #{modelMeta.modelName},"
@@ -55,7 +59,16 @@ public class ModelMetaBaseSQLProvider {
+ " schema_id = #{modelMeta.schemaId},"
+ " model_comment = #{modelMeta.modelComment},"
+ " model_properties = #{modelMeta.modelProperties},"
- + " model_latest_version = #{modelMeta.modelLatestVersion},"
+ // Overwrite may receive an entity that was read before one or more versions were
+ // registered. Keep the stored allocator at its highest value so the next registration
+ // cannot reuse an existing version number. Older schemas allowed this column to be null,
+ // so treat that legacy value as the initial allocator value zero.
+ + " model_latest_version ="
+ + " GREATEST(COALESCE(model_latest_version, 0), #{modelMeta.modelLatestVersion}),"
+ // A replacement ModelPO starts at version 1. Advance the version already stored in the
+ // database instead of copying that 1, or an older request could become valid again.
+ + " last_version = current_version + 1,"
+ + " current_version = current_version + 1,"
+ " audit_info = #{modelMeta.auditInfo},"
+ " deleted_at = #{modelMeta.deletedAt}";
}
@@ -63,8 +76,9 @@ public class ModelMetaBaseSQLProvider {
public String listModelPOsBySchemaId(@Param("schemaId") Long schemaId) {
return "SELECT model_id AS modelId, model_name AS modelName, metalake_id AS metalakeId,"
+ " catalog_id AS catalogId, schema_id AS schemaId, model_comment AS modelComment,"
- + " model_properties AS modelProperties, model_latest_version AS"
- + " modelLatestVersion, audit_info AS auditInfo, deleted_at AS deletedAt"
+ + " model_properties AS modelProperties, model_latest_version AS modelLatestVersion,"
+ + " current_version AS currentVersion, last_version AS lastVersion,"
+ + " audit_info AS auditInfo, deleted_at AS deletedAt"
+ " FROM "
+ ModelMetaMapper.TABLE_NAME
+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";
@@ -84,6 +98,8 @@ public class ModelMetaBaseSQLProvider {
mo.model_comment AS modelComment,
mo.model_properties AS modelProperties,
mo.model_latest_version AS modelLatestVersion,
+ mo.current_version AS currentVersion,
+ mo.last_version AS lastVersion,
mo.audit_info AS auditInfo,
mo.deleted_at AS deletedAt
FROM
@@ -114,8 +130,9 @@ public class ModelMetaBaseSQLProvider {
return "<script>"
+ " SELECT model_id AS modelId, model_name AS modelName, metalake_id AS metalakeId,"
+ " catalog_id AS catalogId, schema_id AS schemaId, model_comment AS modelComment,"
- + " model_properties AS modelProperties, model_latest_version AS"
- + " modelLatestVersion, audit_info AS auditInfo, deleted_at AS deletedAt"
+ + " model_properties AS modelProperties, model_latest_version AS modelLatestVersion,"
+ + " current_version AS currentVersion, last_version AS lastVersion,"
+ + " audit_info AS auditInfo, deleted_at AS deletedAt"
+ " FROM "
+ ModelMetaMapper.TABLE_NAME
+ " WHERE deleted_at = 0"
@@ -131,8 +148,9 @@ public class ModelMetaBaseSQLProvider {
@Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
return "SELECT model_id AS modelId, model_name AS modelName, metalake_id AS metalakeId,"
+ " catalog_id AS catalogId, schema_id AS schemaId, model_comment AS modelComment,"
- + " model_properties AS modelProperties, model_latest_version AS"
- + " modelLatestVersion, audit_info AS auditInfo, deleted_at AS deletedAt"
+ + " model_properties AS modelProperties, model_latest_version AS modelLatestVersion,"
+ + " current_version AS currentVersion, last_version AS lastVersion,"
+ + " audit_info AS auditInfo, deleted_at AS deletedAt"
+ " FROM "
+ ModelMetaMapper.TABLE_NAME
+ " WHERE schema_id = #{schemaId} AND model_name = #{modelName} AND deleted_at = 0";
@@ -153,6 +171,8 @@ public class ModelMetaBaseSQLProvider {
mo.model_comment AS modelComment,
mo.model_properties AS modelProperties,
mo.model_latest_version AS modelLatestVersion,
+ mo.current_version AS currentVersion,
+ mo.last_version AS lastVersion,
mo.audit_info AS auditInfo,
mo.deleted_at AS deletedAt
FROM
@@ -191,20 +211,38 @@ public class ModelMetaBaseSQLProvider {
public String selectModelMetaByModelId(@Param("modelId") Long modelId) {
return "SELECT model_id AS modelId, model_name AS modelName, metalake_id AS metalakeId,"
+ " catalog_id AS catalogId, schema_id AS schemaId, model_comment AS modelComment,"
- + " model_properties AS modelProperties, model_latest_version AS"
- + " modelLatestVersion, audit_info AS auditInfo, deleted_at AS deletedAt"
+ + " model_properties AS modelProperties, model_latest_version AS modelLatestVersion,"
+ + " current_version AS currentVersion, last_version AS lastVersion,"
+ + " audit_info AS auditInfo, deleted_at AS deletedAt"
+ " FROM "
+ ModelMetaMapper.TABLE_NAME
+ " WHERE model_id = #{modelId} AND deleted_at = 0";
}
- public String softDeleteModelMetaBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ /**
+ * Returns SQL that selects and exclusively locks an active model row by its stable ID.
+ *
+ * @param modelId the model ID
+ * @return the locking select SQL
+ */
+ public String selectModelMetaByModelIdForUpdate(@Param("modelId") Long modelId) {
+ return selectModelMetaByModelId(modelId) + " FOR UPDATE";
+ }
+
+ /**
+ * Returns SQL that soft-deletes a model only while its stored version is unchanged.
+ *
+ * @param modelId the model ID
+ * @param currentVersion the version observed by the caller
+ * @return the version-checked soft-delete SQL
+ */
+ public String softDeleteModelMetaByIdAndVersion(
+ @Param("modelId") Long modelId, @Param("currentVersion") Long currentVersion) {
return "UPDATE "
+ ModelMetaMapper.TABLE_NAME
+ " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE schema_id = #{schemaId} AND model_name = #{modelName} AND deleted_at = 0";
+ + activeModelVersionWhereClause("modelId", "currentVersion");
}
public String softDeleteModelMetasByCatalogId(@Param("catalogId") Long catalogId) {
@@ -244,11 +282,45 @@ public class ModelMetaBaseSQLProvider {
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";
}
- public String updateModelLatestVersion(@Param("modelId") Long modelId) {
+ /**
+ * Returns SQL that advances the shared model concurrency version while the model still exists
+ * under the name the caller resolved.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the version bump SQL
+ */
+ public String bumpModelVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName) {
+ // Guarded on the identity the caller resolved, not on the version it observed. The row lock
+ // this takes serializes the model's version writes, while a version registered by somebody
+ // else in the meantime is no reason to reject this one.
return "UPDATE "
+ ModelMetaMapper.TABLE_NAME
- + " SET model_latest_version = model_latest_version + 1"
- + " WHERE model_id = #{modelId} AND deleted_at = 0";
+ + " SET last_version = current_version + 1, current_version = current_version + 1"
+ + activeModelIdentityWhereClause();
+ }
+
+ /**
+ * Returns SQL that advances both the shared concurrency version and the version-number allocator.
+ *
+ * @param modelId the model ID
+ * @param schemaId the ID of the schema holding the model
+ * @param modelName the model name the caller resolved
+ * @return the version registration SQL
+ */
+ public String bumpModelVersionAndLatestVersion(
+ @Param("modelId") Long modelId,
+ @Param("schemaId") Long schemaId,
+ @Param("modelName") String modelName) {
+ return "UPDATE "
+ + ModelMetaMapper.TABLE_NAME
+ + " SET model_latest_version = model_latest_version + 1,"
+ + " last_version = current_version + 1, current_version = current_version + 1"
+ + activeModelIdentityWhereClause();
}
public String updateModelMeta(
@@ -262,19 +334,11 @@ public class ModelMetaBaseSQLProvider {
+ " model_comment = #{newModelMeta.modelComment},"
+ " model_properties = #{newModelMeta.modelProperties},"
+ " model_latest_version = #{newModelMeta.modelLatestVersion},"
+ + " current_version = #{newModelMeta.currentVersion},"
+ + " last_version = #{newModelMeta.lastVersion},"
+ " audit_info = #{newModelMeta.auditInfo},"
+ " deleted_at = #{newModelMeta.deletedAt}"
- + " WHERE model_id = #{oldModelMeta.modelId}"
- + " AND model_name = #{oldModelMeta.modelName}"
- + " AND metalake_id = #{oldModelMeta.metalakeId}"
- + " AND catalog_id = #{oldModelMeta.catalogId}"
- + " AND schema_id = #{oldModelMeta.schemaId}"
- + " AND (model_comment = #{oldModelMeta.modelComment}"
- + " OR (model_comment IS NULL and #{oldModelMeta.modelComment} IS NULL))"
- + " AND model_properties = #{oldModelMeta.modelProperties}"
- + " AND model_latest_version = #{oldModelMeta.modelLatestVersion}"
- + " AND audit_info = #{oldModelMeta.auditInfo}"
- + " AND deleted_at = 0";
+ + activeModelVersionWhereClause("oldModelMeta.modelId", "oldModelMeta.currentVersion");
}
public String batchSelectModelByIdentifier(
@@ -286,7 +350,9 @@ public class ModelMetaBaseSQLProvider {
+ "SELECT mm.model_id as modelId, mm.model_name as modelName,"
+ " mm.metalake_id as metalakeId, mm.catalog_id as catalogId, mm.schema_id as schemaId,"
+ " mm.model_comment as modelComment, mm.model_properties as modelProperties,"
- + " mm.model_latest_version as modelLatestVersion, mm.audit_info as auditInfo,"
+ + " mm.model_latest_version as modelLatestVersion,"
+ + " mm.current_version as currentVersion, mm.last_version as lastVersion,"
+ + " mm.audit_info as auditInfo,"
+ " mm.deleted_at as deletedAt"
+ " FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -311,4 +377,24 @@ public class ModelMetaBaseSQLProvider {
+ " AND mm.deleted_at = 0 AND sm.deleted_at = 0 AND cm.deleted_at = 0 AND mlm.deleted_at = 0"
+ "</script>";
}
+
+ private String activeModelIdentityWhereClause() {
+ return " WHERE model_id = #{modelId} AND schema_id = #{schemaId}"
+ + " AND model_name = #{modelName} AND deleted_at = 0";
+ }
+
+ /**
+ * Builds the active-model guard shared by version-checked UPDATE statements.
+ *
+ * @param modelIdParam the MyBatis parameter path for the model ID
+ * @param currentVersionParam the MyBatis parameter path for the observed version
+ * @return the SQL WHERE clause
+ */
+ protected String activeModelVersionWhereClause(String modelIdParam, String currentVersionParam) {
+ return " WHERE model_id = #{"
+ + modelIdParam
+ + "} AND current_version = #{"
+ + currentVersionParam
+ + "} AND deleted_at = 0";
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionAliasRelBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionAliasRelBaseSQLProvider.java
index 7d696d8dd4..2ea0327ce8 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionAliasRelBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionAliasRelBaseSQLProvider.java
@@ -28,6 +28,7 @@ public class ModelVersionAliasRelBaseSQLProvider {
public String insertModelVersionAliasRels(
@Param("modelVersionAliasRel") List<ModelVersionAliasRelPO> modelVersionAliasRelPOs) {
+ // The model-row reservation increments the allocator before version and alias rows are added.
return "<script>"
+ "INSERT INTO "
+ ModelVersionAliasRelMapper.TABLE_NAME
@@ -35,7 +36,7 @@ public class ModelVersionAliasRelBaseSQLProvider {
+ " VALUES "
+ " <foreach collection='modelVersionAliasRel' item='item' separator=','>"
+ " (#{item.modelId},"
- + " (SELECT model_latest_version FROM "
+ + " (SELECT model_latest_version - 1 FROM "
+ ModelMetaMapper.TABLE_NAME
+ " WHERE model_id = #{item.modelId} AND deleted_at = 0),"
+ " #{item.modelVersionAlias},"
@@ -74,17 +75,18 @@ public class ModelVersionAliasRelBaseSQLProvider {
+ " AND deleted_at = 0";
}
- public String softDeleteModelVersionAliasRelsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ /**
+ * Returns SQL that soft-deletes every active alias row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the soft-delete SQL
+ */
+ public String softDeleteModelVersionAliasRelsByModelId(@Param("modelId") Long modelId) {
return "UPDATE "
+ ModelVersionAliasRelMapper.TABLE_NAME
- + " mvar SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE mvar.model_id = ("
- + " SELECT mm.model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " mm WHERE mm.schema_id = #{schemaId} AND mm.model_name = #{modelName}"
- + " AND mm.deleted_at = 0) AND mvar.deleted_at = 0";
+ + " WHERE model_id = #{modelId} AND deleted_at = 0";
}
public String softDeleteModelVersionAliasRelsByModelIdAndVersion(
@@ -96,20 +98,6 @@ public class ModelVersionAliasRelBaseSQLProvider {
+ " WHERE model_id = #{modelId} AND model_version = #{modelVersion} AND deleted_at = 0";
}
- public String softDeleteModelVersionAliasRelsByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return "UPDATE "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " mvar JOIN ("
- + " SELECT model_version FROM "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " WHERE model_id = #{modelId} AND model_version_alias = #{alias} AND deleted_at = 0)"
- + " subquery ON mvar.model_version = subquery.model_version"
- + " SET mvar.deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
- + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE mvar.model_id = #{modelId} AND mvar.deleted_at = 0";
- }
-
public String softDeleteModelVersionAliasRelsBySchemaIds(
@Param("schemaIds") List<Long> schemaIds) {
return "<script>"
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.java
index 09d09812fa..c53daed8ea 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
@@ -29,12 +29,14 @@ public class ModelVersionMetaBaseSQLProvider {
public String insertModelVersionMetas(
@Param("modelVersionMetas") List<ModelVersionPO> modelVersionPOs) {
+ // The model-row reservation increments the allocator before this insert. Subtract one to use
+ // the number reserved by that transaction while keeping concurrent registrations serialized.
return "<script>"
+ "INSERT INTO "
+ ModelVersionMetaMapper.TABLE_NAME
+ " (metalake_id, catalog_id, schema_id, model_id, version, model_version_comment,"
+ " model_version_properties, model_version_uri_name, model_version_uri, audit_info, deleted_at)"
- + " SELECT m.metalake_id, m.catalog_id, m.schema_id, m.model_id, m.model_latest_version, v.model_version_comment,"
+ + " SELECT m.metalake_id, m.catalog_id, m.schema_id, m.model_id, m.model_latest_version - 1, v.model_version_comment,"
+ " v.model_version_properties, v.model_version_uri_name, v.model_version_uri, v.audit_info, v.deleted_at"
+ " FROM ("
+ "<foreach collection='modelVersionMetas' item='version' separator='UNION ALL'>"
@@ -119,17 +121,18 @@ public class ModelVersionMetaBaseSQLProvider {
+ " AND mvi.deleted_at = 0 AND mvar.deleted_at = 0";
}
- public String softDeleteModelVersionsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ /**
+ * Returns SQL that soft-deletes every active version row for a model ID.
+ *
+ * @param modelId the model ID
+ * @return the soft-delete SQL
+ */
+ public String softDeleteModelVersionsByModelId(@Param("modelId") Long modelId) {
return "UPDATE "
+ ModelVersionMetaMapper.TABLE_NAME
- + " mvi SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE mvi.schema_id = #{schemaId} AND mvi.model_id = ("
- + " SELECT mm.model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " mm WHERE mm.schema_id = #{schemaId} AND mm.model_name = #{modelName}"
- + " AND mm.deleted_at = 0) AND mvi.deleted_at = 0";
+ + " WHERE model_id = #{modelId} AND deleted_at = 0";
}
public String softDeleteModelVersionMetaByModelIdAndVersion(
@@ -141,19 +144,6 @@ public class ModelVersionMetaBaseSQLProvider {
+ " WHERE model_id = #{modelId} AND version = #{modelVersion} AND deleted_at = 0";
}
- public String softDeleteModelVersionMetaByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return "UPDATE "
- + ModelVersionMetaMapper.TABLE_NAME
- + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
- + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE model_id = #{modelId} AND version = ("
- + " SELECT model_version FROM "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " WHERE model_id = #{modelId} AND model_version_alias = #{alias} AND deleted_at = 0)"
- + " AND deleted_at = 0";
- }
-
public String softDeleteModelVersionMetasBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
return "<script>"
+ "UPDATE "
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionAliasRelH2SQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionAliasRelH2SQLProvider.java
index a9ddc01c1e..0cbcf5a23b 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionAliasRelH2SQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionAliasRelH2SQLProvider.java
@@ -18,23 +18,6 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.h2;
-import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.provider.base.ModelVersionAliasRelBaseSQLProvider;
-import org.apache.ibatis.annotations.Param;
-public class ModelVersionAliasRelH2SQLProvider extends ModelVersionAliasRelBaseSQLProvider {
-
- @Override
- public String softDeleteModelVersionAliasRelsByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return "UPDATE "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
- + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
- + " WHERE model_id = #{modelId} AND model_version = ("
- + " SELECT model_version FROM "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " WHERE model_id = #{modelId} AND model_version_alias = #{alias} AND deleted_at = 0)"
- + " AND deleted_at = 0";
- }
-}
+public class ModelVersionAliasRelH2SQLProvider extends ModelVersionAliasRelBaseSQLProvider {}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionMetaH2Provider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionMetaH2Provider.java
index e19c3d9f6f..1a7bfbfbc9 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionMetaH2Provider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionMetaH2Provider.java
@@ -30,12 +30,14 @@ public class ModelVersionMetaH2Provider extends ModelVersionMetaBaseSQLProvider
@Override
public String insertModelVersionMetas(
@Param("modelVersionMetas") List<ModelVersionPO> modelVersionPOs) {
+ // The model-row reservation increments the allocator before this insert. Subtract one to use
+ // the number reserved by that transaction while keeping concurrent registrations serialized.
return "<script>"
+ "INSERT INTO "
+ ModelVersionMetaMapper.TABLE_NAME
+ " (metalake_id, catalog_id, schema_id, model_id, version, model_version_comment,"
+ " model_version_properties, model_version_uri_name, model_version_uri, audit_info, deleted_at)"
- + " SELECT m.metalake_id, m.catalog_id, m.schema_id, m.model_id, m.model_latest_version, v.model_version_comment,"
+ + " SELECT m.metalake_id, m.catalog_id, m.schema_id, m.model_id, m.model_latest_version - 1, v.model_version_comment,"
+ " v.model_version_properties, v.model_version_uri_name, v.model_version_uri, v.audit_info, v.deleted_at"
+ " FROM ("
+ "<foreach collection='modelVersionMetas' item='version' separator='UNION ALL'>"
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java
index 62d956d0a1..21a1ed9aea 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java
@@ -31,10 +31,12 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {
return "INSERT INTO "
+ ModelMetaMapper.TABLE_NAME
+ " (model_id, model_name, metalake_id, catalog_id, schema_id,"
- + " model_comment, model_properties, model_latest_version, audit_info, deleted_at)"
+ + " model_comment, model_properties, model_latest_version, current_version, last_version,"
+ + " audit_info, deleted_at)"
+ " VALUES (#{modelMeta.modelId}, #{modelMeta.modelName}, #{modelMeta.metalakeId},"
+ " #{modelMeta.catalogId}, #{modelMeta.schemaId}, #{modelMeta.modelComment},"
- + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion}, #{modelMeta.auditInfo},"
+ + " #{modelMeta.modelProperties}, #{modelMeta.modelLatestVersion},"
+ + " #{modelMeta.currentVersion}, #{modelMeta.lastVersion}, #{modelMeta.auditInfo},"
+ " #{modelMeta.deletedAt})"
+ " ON CONFLICT (model_id) DO UPDATE SET"
+ " model_name = #{modelMeta.modelName},"
@@ -43,18 +45,28 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {
+ " schema_id = #{modelMeta.schemaId},"
+ " model_comment = #{modelMeta.modelComment},"
+ " model_properties = #{modelMeta.modelProperties},"
- + " model_latest_version = #{modelMeta.modelLatestVersion},"
+ // Use the larger allocator value when an overwrite carries an older model snapshot.
+ + " model_latest_version = GREATEST("
+ + ModelMetaMapper.TABLE_NAME
+ + ".model_latest_version, #{modelMeta.modelLatestVersion}),"
+ // Qualify current_version with the table name so PostgreSQL knows this is the stored value,
+ // not the value from the insert that caused the conflict.
+ + " current_version = "
+ + ModelMetaMapper.TABLE_NAME
+ + ".current_version + 1,"
+ + " last_version = "
+ + ModelMetaMapper.TABLE_NAME
+ + ".current_version + 1,"
+ " audit_info = #{modelMeta.auditInfo},"
+ " deleted_at = #{modelMeta.deletedAt}";
}
@Override
- public String softDeleteModelMetaBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ public String softDeleteModelMetaByIdAndVersion(Long modelId, Long currentVersion) {
return "UPDATE "
+ ModelMetaMapper.TABLE_NAME
+ " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
- + " WHERE schema_id = #{schemaId} AND model_name = #{modelName} AND deleted_at = 0";
+ + activeModelVersionWhereClause("modelId", "currentVersion");
}
@Override
@@ -96,32 +108,4 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {
+ ModelMetaMapper.TABLE_NAME
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
}
-
- @Override
- public String updateModelMeta(
- @Param("newModelMeta") ModelPO newModelPO, @Param("oldModelMeta") ModelPO oldModelPO) {
- return "UPDATE "
- + ModelMetaMapper.TABLE_NAME
- + " SET model_name = #{newModelMeta.modelName},"
- + " metalake_id = #{newModelMeta.metalakeId},"
- + " catalog_id = #{newModelMeta.catalogId},"
- + " schema_id = #{newModelMeta.schemaId},"
- + " model_comment = #{newModelMeta.modelComment},"
- + " model_properties = #{newModelMeta.modelProperties},"
- + " model_latest_version = #{newModelMeta.modelLatestVersion},"
- + " audit_info = #{newModelMeta.auditInfo},"
- + " deleted_at = #{newModelMeta.deletedAt}"
- + " WHERE model_id = #{oldModelMeta.modelId}"
- + " AND model_name = #{oldModelMeta.modelName}"
- + " AND metalake_id = #{oldModelMeta.metalakeId}"
- + " AND catalog_id = #{oldModelMeta.catalogId}"
- + " AND schema_id = #{oldModelMeta.schemaId}"
- + " AND (model_comment = #{oldModelMeta.modelComment}"
- + " OR (CAST(model_comment AS VARCHAR) IS NULL"
- + " AND CAST(#{oldModelMeta.modelComment} AS VARCHAR) IS NULL))"
- + " AND model_properties = #{oldModelMeta.modelProperties}"
- + " AND model_latest_version = #{oldModelMeta.modelLatestVersion}"
- + " AND audit_info = #{oldModelMeta.auditInfo}"
- + " AND deleted_at = 0";
- }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java
index 801a0b0056..ab6b9db075 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java
@@ -27,16 +27,11 @@ import org.apache.ibatis.annotations.Param;
public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRelBaseSQLProvider {
@Override
- public String softDeleteModelVersionAliasRelsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ public String softDeleteModelVersionAliasRelsByModelId(Long modelId) {
return "UPDATE "
+ ModelVersionAliasRelMapper.TABLE_NAME
- + " mvar SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
- + " WHERE mvar.model_id = ("
- + " SELECT mm.model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " mm WHERE mm.schema_id = #{schemaId} AND mm.model_name = #{modelName}"
- + " AND mm.deleted_at = 0) AND mvar.deleted_at = 0";
+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
+ + " WHERE model_id = #{modelId} AND deleted_at = 0";
}
@Override
@@ -48,19 +43,6 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRel
+ " WHERE model_id = #{modelId} AND model_version = #{modelVersion} AND deleted_at = 0";
}
- @Override
- public String softDeleteModelVersionAliasRelsByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return "UPDATE "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
- + " WHERE model_id = #{modelId} AND model_version = ("
- + " SELECT model_version FROM "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " WHERE model_id = #{modelId} AND model_version_alias = #{alias} AND deleted_at = 0)"
- + " AND deleted_at = 0";
- }
-
@Override
public String softDeleteModelVersionAliasRelsBySchemaIds(
@Param("schemaIds") List<Long> schemaIds) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java
index 0f689e9d0f..957b9cbaac 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java
@@ -19,8 +19,6 @@
package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
import java.util.List;
-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.mapper.provider.base.ModelVersionMetaBaseSQLProvider;
import org.apache.gravitino.storage.relational.po.ModelVersionPO;
@@ -29,16 +27,11 @@ import org.apache.ibatis.annotations.Param;
public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLProvider {
@Override
- public String softDeleteModelVersionsBySchemaIdAndModelName(
- @Param("schemaId") Long schemaId, @Param("modelName") String modelName) {
+ public String softDeleteModelVersionsByModelId(Long modelId) {
return "UPDATE "
+ ModelVersionMetaMapper.TABLE_NAME
- + " mvi SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
- + " WHERE mvi.schema_id = #{schemaId} AND mvi.model_id = ("
- + " SELECT mm.model_id FROM "
- + ModelMetaMapper.TABLE_NAME
- + " mm WHERE mm.schema_id = #{schemaId} AND mm.model_name = #{modelName}"
- + " AND mm.deleted_at = 0) AND mvi.deleted_at = 0";
+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
+ + " WHERE model_id = #{modelId} AND deleted_at = 0";
}
@Override
@@ -50,19 +43,6 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLP
+ " WHERE model_id = #{modelId} AND version = #{modelVersion} AND deleted_at = 0";
}
- @Override
- public String softDeleteModelVersionMetaByModelIdAndAlias(
- @Param("modelId") Long modelId, @Param("alias") String alias) {
- return "UPDATE "
- + ModelVersionMetaMapper.TABLE_NAME
- + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"
- + " WHERE model_id = #{modelId} AND version = ("
- + " SELECT model_version FROM "
- + ModelVersionAliasRelMapper.TABLE_NAME
- + " WHERE model_id = #{modelId} AND model_version_alias = #{alias} AND deleted_at = 0)"
- + " AND deleted_at = 0";
- }
-
@Override
public String softDeleteModelVersionMetasBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
return "<script>"
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelPO.java
index 008b071d81..06f6dee19c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelPO.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelPO.java
@@ -41,6 +41,10 @@ public class ModelPO {
private Integer modelLatestVersion;
+ private Long currentVersion;
+
+ private Long lastVersion;
+
private String modelProperties;
private String auditInfo;
@@ -96,6 +100,29 @@ public class ModelPO {
return this;
}
+ /**
+ * Sets the version used to detect concurrent changes to the model, its versions, or its
+ * aliases.
+ *
+ * @param currentVersion the current version
+ * @return this builder
+ */
+ public Builder withCurrentVersion(Long currentVersion) {
+ modelPO.currentVersion = currentVersion;
+ return this;
+ }
+
+ /**
+ * Sets the highest concurrency version allocated for this model.
+ *
+ * @param lastVersion the last allocated version
+ * @return this builder
+ */
+ public Builder withLastVersion(Long lastVersion) {
+ modelPO.lastVersion = lastVersion;
+ return this;
+ }
+
public Builder withModelProperties(String modelProperties) {
modelPO.modelProperties = modelProperties;
return this;
@@ -120,6 +147,8 @@ public class ModelPO {
Preconditions.checkArgument(modelPO.schemaId != null, "Schema id is required");
Preconditions.checkArgument(
modelPO.modelLatestVersion != null, "Model latest version is required");
+ Preconditions.checkArgument(modelPO.currentVersion != null, "Current version is required");
+ Preconditions.checkArgument(modelPO.lastVersion != null, "Last version is required");
Preconditions.checkArgument(
StringUtils.isNotBlank(modelPO.auditInfo), "Audit info cannot be empty");
Preconditions.checkArgument(modelPO.deletedAt != null, "Deleted at is required");
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
index 00ef4aecea..e49ad97328 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
@@ -26,7 +26,6 @@ import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -134,9 +133,6 @@ public class ModelMetaService {
LOG.warn("Failed to delete model: {}", ident, e);
return false;
}
- Long schemaId = modelPO.getSchemaId();
- Long modelId = modelPO.getModelId();
-
String metalakeName = ident.namespace().level(0);
String catalogName = ident.namespace().level(1);
String schemaName = ident.namespace().level(2);
@@ -144,60 +140,13 @@ public class ModelMetaService {
EntityChangeLogNameIdentifierCodec.encode(
NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, ident.name()));
- AtomicInteger modelDeletedCount = new AtomicInteger();
- SessionUtils.doMultipleWithCommit(
- // delete model versions first
- () ->
- SessionUtils.doWithoutCommit(
- ModelVersionMetaMapper.class,
- mapper ->
- mapper.softDeleteModelVersionsBySchemaIdAndModelName(schemaId, ident.name())),
-
- // delete model version aliases
- () ->
- SessionUtils.doWithoutCommit(
- ModelVersionAliasRelMapper.class,
- mapper ->
- mapper.softDeleteModelVersionAliasRelsBySchemaIdAndModelName(
- schemaId, ident.name())),
-
- // delete model meta
- () ->
- modelDeletedCount.set(
- SessionUtils.getWithoutCommit(
- ModelMetaMapper.class,
- mapper ->
- mapper.softDeleteModelMetaBySchemaIdAndModelName(schemaId, ident.name()))),
- () ->
- SessionUtils.doWithoutCommit(
- OwnerMetaMapper.class,
- mapper ->
- mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
- modelId, MetadataObject.Type.MODEL.name())),
- () ->
- SessionUtils.doWithoutCommit(
- SecurableObjectMapper.class,
- mapper ->
- mapper.softDeleteObjectRelsByMetadataObject(
- modelId, MetadataObject.Type.MODEL.name())),
- () ->
- SessionUtils.doWithoutCommit(
- TagMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
- modelId, MetadataObject.Type.MODEL.name())),
- () ->
- SessionUtils.doWithoutCommit(
- StatisticMetaMapper.class,
- mapper -> mapper.softDeleteStatisticsByEntityId(modelId)),
- () ->
- SessionUtils.doWithoutCommit(
- PolicyMetadataObjectRelMapper.class,
- mapper ->
- mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- modelId, MetadataObject.Type.MODEL.name())),
- () -> {
- if (modelDeletedCount.get() > 0) {
+ // Delete the model row first, and only when its concurrency version still matches the value
+ // read above. If another writer changed the model, stop before removing any related data.
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () -> deleteModelWithVersion(ident, modelPO),
+ () -> deleteModelDependents(modelPO),
+ () -> {
SessionUtils.doWithoutCommit(
EntityChangeLogMapper.class,
mapper ->
@@ -206,10 +155,16 @@ public class ModelMetaService {
Entity.EntityType.MODEL.name(),
modelFullName,
OperateType.DROP));
- }
- });
+ });
+ } catch (NoSuchEntityException e) {
+ // Another writer dropped the model between the read above and this transaction. A drop that
+ // finds nothing to drop is reported the same way as the read above reports it, so that a
+ // duplicate drop stays a plain "false" instead of surfacing as an error.
+ LOG.warn("Failed to delete model: {}", ident, e);
+ return false;
+ }
- return modelDeletedCount.get() > 0;
+ return true;
}
@Monitored(
@@ -391,18 +346,24 @@ public class ModelMetaService {
metalakeName, catalogName, schemaName, oldModelEntity.name()));
boolean isRenamed = !Objects.equals(oldModelEntity.name(), newEntity.name());
- AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
- () ->
- updateResult.set(
- SessionUtils.getWithoutCommit(
- ModelMetaMapper.class,
- mapper ->
- mapper.updateModelMeta(
- POConverters.updateModelPO(oldModelPO, newEntity), oldModelPO))),
() -> {
- if (isRenamed && updateResult.get() > 0) {
+ // This is the first write in the transaction. It succeeds only if the model still has
+ // the concurrency version read above, so an older request cannot overwrite a newer
+ // model or add an incorrect change-log entry.
+ int updated =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.updateModelMeta(
+ POConverters.updateModelPO(oldModelPO, newEntity), oldModelPO));
+ if (updated == 0) {
+ throw modelWriteFailure(identifier, oldModelPO);
+ }
+ },
+ () -> {
+ if (isRenamed) {
SessionUtils.doWithoutCommit(
EntityChangeLogMapper.class,
mapper ->
@@ -419,11 +380,7 @@ public class ModelMetaService {
throw re;
}
- if (updateResult.get() > 0) {
- return newEntity;
- } else {
- throw new IOException("Failed to update the entity: " + identifier);
- }
+ return newEntity;
}
@Monitored(
@@ -447,4 +404,123 @@ public class ModelMetaService {
return POConverters.fromModelPOs(modelPOs, firstIdent.namespace());
});
}
+
+ /**
+ * Deletes a model row only when its concurrency version has not changed since it was read.
+ *
+ * <p>The caller must run this method in the same transaction that removes the model's related
+ * data. This allows any later cleanup failure to restore the model row as well.
+ */
+ void deleteModelWithVersion(NameIdentifier ident, ModelPO observedModelPO) {
+ int deleted =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.softDeleteModelMetaByIdAndVersion(
+ observedModelPO.getModelId(), observedModelPO.getCurrentVersion()));
+ if (deleted == 0) {
+ throw modelWriteFailure(ident, observedModelPO);
+ }
+ }
+
+ /**
+ * Advances the concurrency version shared by a model, its versions, and its aliases.
+ *
+ * <p>The caller uses this as the first write in a model-version transaction. It takes the model
+ * row, so the model's version writes run one at a time, and a model that was dropped or renamed
+ * away makes this fail before any version or alias row is modified. Version writes append to or
+ * replace rows the caller already resolved, so a version somebody else registered in the meantime
+ * is not a reason to reject this one; a lost update on the same row is still caught where that
+ * row is written.
+ */
+ void bumpModelVersion(NameIdentifier ident, ModelPO observedModelPO) {
+ int updated =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.bumpModelVersion(
+ observedModelPO.getModelId(),
+ observedModelPO.getSchemaId(),
+ observedModelPO.getModelName()));
+ if (updated == 0) {
+ throw modelWriteFailure(ident, observedModelPO);
+ }
+ }
+
+ /**
+ * Advances the shared concurrency version and the model-version allocator in one write.
+ *
+ * <p>This is the model-row reservation for registering a new version. Combining both counters in
+ * one statement avoids taking and updating the same row twice.
+ */
+ void bumpModelVersionAndLatestVersion(NameIdentifier ident, ModelPO observedModelPO) {
+ int updated =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.bumpModelVersionAndLatestVersion(
+ observedModelPO.getModelId(),
+ observedModelPO.getSchemaId(),
+ observedModelPO.getModelName()));
+ if (updated == 0) {
+ throw modelWriteFailure(ident, observedModelPO);
+ }
+ }
+
+ /**
+ * Explains why a version-checked model write changed no rows.
+ *
+ * <p>The locking read waits for a competing transaction to finish. If the same model is still at
+ * the requested name, only its concurrency version changed and the caller should retry. If it was
+ * deleted, renamed, or moved, the requested model no longer exists.
+ */
+ private RuntimeException modelWriteFailure(NameIdentifier ident, ModelPO observedModelPO) {
+ ModelPO currentModelPO =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper -> mapper.selectModelMetaByModelIdForUpdate(observedModelPO.getModelId()));
+ if (currentModelPO == null
+ || !Objects.equals(currentModelPO.getModelName(), observedModelPO.getModelName())
+ || !Objects.equals(currentModelPO.getSchemaId(), observedModelPO.getSchemaId())
+ || !Objects.equals(currentModelPO.getCatalogId(), observedModelPO.getCatalogId())
+ || !Objects.equals(currentModelPO.getMetalakeId(), observedModelPO.getMetalakeId())) {
+ return new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.MODEL.name().toLowerCase(Locale.ROOT),
+ ident.toString());
+ }
+ return ExceptionUtils.concurrentModification(Entity.EntityType.MODEL, ident);
+ }
+
+ private void deleteModelDependents(ModelPO modelPO) {
+ Long modelId = modelPO.getModelId();
+ // The model row has already passed its version check. All cleanup below uses the same
+ // transaction, so a failure restores both the model row and any related rows already removed.
+ SessionUtils.doWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper -> mapper.softDeleteModelVersionAliasRelsByModelId(modelId));
+ SessionUtils.doWithoutCommit(
+ ModelVersionMetaMapper.class, mapper -> mapper.softDeleteModelVersionsByModelId(modelId));
+ SessionUtils.doWithoutCommit(
+ OwnerMetaMapper.class,
+ mapper ->
+ mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
+ modelId, MetadataObject.Type.MODEL.name()));
+ SessionUtils.doWithoutCommit(
+ SecurableObjectMapper.class,
+ mapper ->
+ mapper.softDeleteObjectRelsByMetadataObject(modelId, MetadataObject.Type.MODEL.name()));
+ SessionUtils.doWithoutCommit(
+ TagMetadataObjectRelMapper.class,
+ mapper ->
+ mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
+ modelId, MetadataObject.Type.MODEL.name()));
+ SessionUtils.doWithoutCommit(
+ StatisticMetaMapper.class, mapper -> mapper.softDeleteStatisticsByEntityId(modelId));
+ SessionUtils.doWithoutCommit(
+ PolicyMetadataObjectRelMapper.class,
+ mapper ->
+ mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
+ modelId, MetadataObject.Type.MODEL.name()));
+ }
}
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.java
index b9b90f5d94..4a448b09af 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
@@ -23,6 +23,7 @@ import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATI
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import java.io.IOException;
@@ -31,7 +32,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.math.NumberUtils;
@@ -43,7 +43,6 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.ModelEntity;
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;
@@ -54,9 +53,13 @@ import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ModelVersionMetaService {
+ private static final Logger LOG = LoggerFactory.getLogger(ModelVersionMetaService.class);
+
private static final ModelVersionMetaService INSTANCE = new ModelVersionMetaService();
public static ModelVersionMetaService getInstance() {
@@ -173,10 +176,7 @@ public class ModelVersionMetaService {
try {
SessionUtils.doMultipleWithCommit(
- // Model versions carry the schema ID directly, so they must take the same parent fence
- // as models. Otherwise a schema cascade can pass its model-version cleanup and a
- // concurrent registration can insert a new active version below the deleted schema.
- () -> lockSchemaForModelVersionWrite(modelIdent, modelPO),
+ () -> reserveModelVersionRegistration(modelIdent, modelPO),
() ->
SessionUtils.doWithoutCommit(
ModelVersionMetaMapper.class,
@@ -188,17 +188,6 @@ public class ModelVersionMetaService {
SessionUtils.doWithoutCommit(
ModelVersionAliasRelMapper.class,
mapper -> mapper.insertModelVersionAliasRels(aliasRelPOs));
- },
- () -> {
- // If the model version is inserted successfully, update the model latest version. A
- // zero result means the model disappeared after the read above, so the inserted version
- // and aliases must roll back with this transaction.
- int updated =
- SessionUtils.getWithoutCommit(
- ModelMetaMapper.class, mapper -> mapper.updateModelLatestVersion(modelId));
- if (updated == 0) {
- throw noSuchModelException(modelIdent);
- }
});
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
@@ -214,52 +203,63 @@ public class ModelVersionMetaService {
NameIdentifierUtil.checkModelVersion(ident);
NameIdentifier modelIdent = NameIdentifier.of(ident.namespace().levels());
- // Will throw a NoSuchEntityException if the model does not exist.
- ModelEntity modelEntity;
+ ModelPO modelPO;
try {
- modelEntity = ModelMetaService.getInstance().getModelByIdentifier(modelIdent);
+ modelPO = ModelMetaService.getInstance().getModelPOByIdentifier(modelIdent);
} catch (NoSuchEntityException e) {
return false;
}
boolean isVersionNumber = NumberUtils.isCreatable(ident.name());
+ // Resolve an alias to its numeric model-version value. The transaction below validates this
+ // mapping again after locking the parent model, before it deletes either version or alias rows.
+ List<ModelVersionPO> observedVersionPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionMetaMapper.class,
+ mapper -> {
+ if (isVersionNumber) {
+ return mapper.selectModelVersionMeta(
+ modelPO.getModelId(), Integer.valueOf(ident.name()));
+ }
+ return mapper.selectModelVersionMetaByAlias(modelPO.getModelId(), ident.name());
+ });
+ if (observedVersionPOs.isEmpty()) {
+ return false;
+ }
+ int modelVersion = observedVersionPOs.get(0).getModelVersion();
- AtomicInteger modelVersionDeletedCount = new AtomicInteger();
- SessionUtils.doMultipleWithCommit(
- // Delete model version relations first
- () ->
- modelVersionDeletedCount.set(
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () -> reserveModelVersionWrite(ident, modelPO, modelVersion),
+ () -> {
+ // An alias was resolved to its numeric version above. Delete every URI row belonging to
+ // that version, regardless of whether the caller supplied the number or an alias.
+ int deleted =
SessionUtils.getWithoutCommit(
ModelVersionMetaMapper.class,
- mapper -> {
- if (isVersionNumber) {
- return mapper.softDeleteModelVersionMetaByModelIdAndVersion(
- modelEntity.id(), Integer.valueOf(ident.name()));
- } else {
- return mapper.softDeleteModelVersionMetaByModelIdAndAlias(
- modelEntity.id(), ident.name());
- }
- })),
- () -> {
- // Delete model version alias relations
- if (modelVersionDeletedCount.get() == 0) {
- return;
- }
-
- SessionUtils.doWithoutCommit(
- ModelVersionAliasRelMapper.class,
- mapper -> {
- if (isVersionNumber) {
- mapper.softDeleteModelVersionAliasRelsByModelIdAndVersion(
- modelEntity.id(), Integer.valueOf(ident.name()));
- } else {
- mapper.softDeleteModelVersionAliasRelsByModelIdAndAlias(
- modelEntity.id(), ident.name());
- }
- });
- });
-
- return modelVersionDeletedCount.get() > 0;
+ mapper ->
+ mapper.softDeleteModelVersionMetaByModelIdAndVersion(
+ modelPO.getModelId(), modelVersion));
+ if (deleted == 0) {
+ throw noSuchModelVersionException(ident);
+ }
+ },
+ // Remove all aliases for the same numeric version in the same transaction.
+ () ->
+ SessionUtils.doWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper ->
+ mapper.softDeleteModelVersionAliasRelsByModelIdAndVersion(
+ modelPO.getModelId(), modelVersion)));
+ } catch (NoSuchEntityException e) {
+ // The model, its parent schema or the version itself was dropped between the reads above and
+ // this transaction. Both reads report that case by returning false, so a delete that races
+ // with another delete keeps returning false instead of surfacing as an error.
+ LOG.warn("Failed to delete model version: {}", ident, e);
+ return false;
+ }
+
+ return true;
}
@Monitored(
@@ -324,6 +324,8 @@ public class ModelVersionMetaService {
Entity.EntityType.MODEL_VERSION.name().toLowerCase(Locale.ROOT),
ident.toString());
}
+ ModelVersionPO oldModelVersionPO = oldModelVersionPOs.get(0);
+ int modelVersion = oldModelVersionPO.getModelVersion();
List<ModelVersionAliasRelPO> oldAliasRelPOs =
SessionUtils.getWithoutCommit(
@@ -356,61 +358,61 @@ public class ModelVersionMetaService {
boolean isModelVersionUriUpdated =
isModelVersionUriUpdated(oldModelVersionEntity, newModelVersionEntity);
- final AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
- // URI and alias updates can reinsert active model-version rows, so they need the same
- // schema fence as a new version registration.
- () -> lockSchemaForModelVersionWrite(modelIdent, modelPO),
+ () -> reserveModelVersionUpdate(ident, modelPO, oldModelVersionPOs, oldAliasRelPOs),
() -> {
+ int updated;
if (isModelVersionUriUpdated) {
- // delete old model version POs first
- updateResult.addAndGet(
+ // URI rows share the same model-version number. Replace the complete set so URI
+ // names removed by the update do not remain active.
+ updated =
SessionUtils.getWithoutCommit(
ModelVersionMetaMapper.class,
- mapper -> {
- if (isVersionNumber) {
- return mapper.softDeleteModelVersionMetaByModelIdAndVersion(
- modelId, Integer.valueOf(ident.name()));
- } else {
- return mapper.softDeleteModelVersionMetaByModelIdAndAlias(
- modelId, ident.name());
- }
- }));
-
- // insert model version POs with updated URIs
+ mapper ->
+ mapper.softDeleteModelVersionMetaByModelIdAndVersion(
+ modelId, modelVersion));
+
List<ModelVersionPO> modelVersionPOs =
POConverters.initializeModelVersionPO(newModelVersionEntity, modelId);
SessionUtils.doWithoutCommit(
ModelVersionMetaMapper.class,
mapper -> mapper.insertModelVersionMetasWithVersionNumber(modelVersionPOs));
} else {
- // update model version POs directly
- updateResult.addAndGet(
+ // When the URI set is unchanged, update the common fields in place.
+ updated =
SessionUtils.getWithoutCommit(
ModelVersionMetaMapper.class,
mapper ->
mapper.updateModelVersionMeta(
POConverters.updateModelVersionPO(
- oldModelVersionPOs.get(0), newModelVersionEntity),
- oldModelVersionPOs.get(0))));
+ oldModelVersionPO, newModelVersionEntity),
+ oldModelVersionPO));
+ }
+ if (updated == 0) {
+ // The locked snapshot above established that this version exists and is unchanged,
+ // so a zero-row write is an unexpected concurrent modification. Throwing also rolls
+ // back the aggregate concurrency-version change.
+ throw ExceptionUtils.concurrentModification(Entity.EntityType.MODEL_VERSION, ident);
}
},
() -> {
if (isAliasChanged) {
+ // Replace the full alias set by numeric version. This also works when the request
+ // identified the version through one of its aliases.
SessionUtils.doWithoutCommit(
ModelVersionAliasRelMapper.class,
mapper ->
- oldModelVersionEntity
- .aliases()
- .forEach(
- alias ->
- mapper.softDeleteModelVersionAliasRelsByModelIdAndAlias(
- modelId, alias)));
+ mapper.softDeleteModelVersionAliasRelsByModelIdAndVersion(
+ modelId, oldModelVersionEntity.version()));
- SessionUtils.doWithoutCommit(
- ModelVersionAliasRelMapper.class,
- mapper -> mapper.updateModelVersionAliasRel(newAliasRelPOs));
+ if (!newAliasRelPOs.isEmpty()) {
+ // An empty list means that the update removed every alias; there is nothing to
+ // insert after the old aliases have been deleted.
+ SessionUtils.doWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper -> mapper.updateModelVersionAliasRel(newAliasRelPOs));
+ }
}
});
@@ -420,22 +422,13 @@ public class ModelVersionMetaService {
throw re;
}
- if (updateResult.get() > 0) {
- return newModelVersionEntity;
- } else {
- throw new IOException("Failed to update the entity: " + ident);
- }
+ return newModelVersionEntity;
}
private boolean isModelVersionAliasUpdated(
ModelVersionEntity oldModelVersionEntity, ModelVersionEntity newModelVersionEntity) {
List<String> oldAliases = oldModelVersionEntity.aliases();
List<String> newAliases = newModelVersionEntity.aliases();
-
- if (oldAliases.size() != newAliases.size()) {
- return true;
- }
-
return !oldAliases.equals(newAliases);
}
@@ -456,10 +449,83 @@ public class ModelVersionMetaService {
observedModelPO.getMetalakeId());
}
- private NoSuchEntityException noSuchModelException(NameIdentifier modelIdentifier) {
+ private void reserveModelVersionRegistration(
+ NameIdentifier modelIdentifier, ModelPO observedModelPO) {
+ // The schema fence prevents a registration below a schema being dropped. The model update then
+ // allocates the version number and advances the aggregate OCC token in one row write.
+ lockSchemaForModelVersionWrite(modelIdentifier, observedModelPO);
+ ModelMetaService.getInstance()
+ .bumpModelVersionAndLatestVersion(modelIdentifier, observedModelPO);
+ }
+
+ private void reserveModelVersionWrite(
+ NameIdentifier modelVersionIdentifier, ModelPO observedModelPO, int observedModelVersion) {
+ NameIdentifier modelIdentifier = NameIdentifier.of(modelVersionIdentifier.namespace().levels());
+ // Every model-version mutation follows this order: fence the schema, lock and advance the
+ // parent model row, then validate an alias-based identifier while that row lock is held.
+ lockSchemaForModelVersionWrite(modelIdentifier, observedModelPO);
+ ModelMetaService.getInstance().bumpModelVersion(modelIdentifier, observedModelPO);
+ validateModelVersionIdentifier(
+ modelVersionIdentifier, observedModelPO.getModelId(), observedModelVersion);
+ }
+
+ private void reserveModelVersionUpdate(
+ NameIdentifier modelVersionIdentifier,
+ ModelPO observedModelPO,
+ List<ModelVersionPO> observedVersionPOs,
+ List<ModelVersionAliasRelPO> observedAliasRelPOs) {
+ int observedModelVersion = observedVersionPOs.get(0).getModelVersion();
+ reserveModelVersionWrite(modelVersionIdentifier, observedModelPO, observedModelVersion);
+
+ List<ModelVersionPO> currentVersionPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionMetaMapper.class,
+ mapper ->
+ mapper.selectModelVersionMeta(observedModelPO.getModelId(), observedModelVersion));
+ if (currentVersionPOs.isEmpty()) {
+ throw noSuchModelVersionException(modelVersionIdentifier);
+ }
+ if (!ImmutableSet.copyOf(currentVersionPOs).equals(ImmutableSet.copyOf(observedVersionPOs))) {
+ throw ExceptionUtils.concurrentModification(
+ Entity.EntityType.MODEL_VERSION, modelVersionIdentifier);
+ }
+
+ List<ModelVersionAliasRelPO> currentAliasRelPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper ->
+ mapper.selectModelVersionAliasRelsByModelIdAndVersion(
+ observedModelPO.getModelId(), observedModelVersion));
+ if (!ImmutableSet.copyOf(currentAliasRelPOs).equals(ImmutableSet.copyOf(observedAliasRelPOs))) {
+ throw ExceptionUtils.concurrentModification(
+ Entity.EntityType.MODEL_VERSION, modelVersionIdentifier);
+ }
+ }
+
+ private void validateModelVersionIdentifier(
+ NameIdentifier identifier, long modelId, int observedModelVersion) {
+ if (NumberUtils.isCreatable(identifier.name())) {
+ return;
+ }
+
+ List<ModelVersionAliasRelPO> currentAliasRelPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper ->
+ mapper.selectModelVersionAliasRelsByModelIdAndAlias(modelId, identifier.name()));
+ if (currentAliasRelPOs.isEmpty()) {
+ throw noSuchModelVersionException(identifier);
+ }
+ if (currentAliasRelPOs.stream()
+ .noneMatch(aliasRelPO -> aliasRelPO.getModelVersion() == observedModelVersion)) {
+ throw ExceptionUtils.concurrentModification(Entity.EntityType.MODEL_VERSION, identifier);
+ }
+ }
+
+ private NoSuchEntityException noSuchModelVersionException(NameIdentifier modelVersionIdentifier) {
return new NoSuchEntityException(
NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
- Entity.EntityType.MODEL.name().toLowerCase(Locale.ROOT),
- modelIdentifier.toString());
+ Entity.EntityType.MODEL_VERSION.name().toLowerCase(Locale.ROOT),
+ modelVersionIdentifier.toString());
}
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
index 5557378eda..49a59d32e6 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java
@@ -1644,6 +1644,9 @@ public class POConverters {
.withModelName(modelEntity.name())
.withModelComment(modelEntity.comment())
.withModelLatestVersion(modelEntity.latestVersion())
+ // A new model has no earlier writes, so its concurrency version starts at 1.
+ .withCurrentVersion(INIT_VERSION)
+ .withLastVersion(INIT_VERSION)
.withModelProperties(
JsonUtils.anyFieldMapper().writeValueAsString(modelEntity.properties()))
.withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(modelEntity.auditInfo()))
@@ -1688,14 +1691,17 @@ public class POConverters {
}
/**
- * Updata ModelPO with new ModelEntity object, metalakeID, catalogID, schemaID will be the same as
- * the old one. the id, name, comment, properties, latestVersion and auditInfo will be updated.
+ * Creates a {@link ModelPO} for a model update.
+ *
+ * <p>The parent metalake, catalog, and schema IDs stay unchanged. The model fields come from the
+ * new entity, and the shared concurrency version advances by one.
*
- * @param oldModelPO the old ModelPO object
- * @param newModel the new ModelEntity object
- * @return the updated ModelPO object
+ * @param oldModelPO the model record read before the update
+ * @param newModel the updated model entity
+ * @return the model record to store
*/
public static ModelPO updateModelPO(ModelPO oldModelPO, ModelEntity newModel) {
+ long nextModelVersion = oldModelPO.getCurrentVersion() + 1;
try {
return ModelPO.builder()
.withModelId(newModel.id())
@@ -1705,6 +1711,11 @@ public class POConverters {
.withSchemaId(oldModelPO.getSchemaId())
.withModelComment(newModel.comment())
.withModelLatestVersion(newModel.latestVersion())
+ // Reserve the next shared concurrency version for this model change. The guard on the
+ // write matches current_version, so that column is what the next version is derived from;
+ // last_version only mirrors it.
+ .withCurrentVersion(nextModelVersion)
+ .withLastVersion(nextModelVersion)
.withModelProperties(JsonUtils.anyFieldMapper().writeValueAsString(newModel.properties()))
.withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(newModel.auditInfo()))
.withDeletedAt(DEFAULT_DELETED_AT)
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelMetaBaseSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelMetaBaseSQLProvider.java
new file mode 100644
index 0000000000..af344b2aee
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelMetaBaseSQLProvider.java
@@ -0,0 +1,133 @@
+/*
+ * 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.mapper.provider.base;
+
+import java.util.List;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestModelMetaBaseSQLProvider {
+
+ private static final ModelMetaBaseSQLProvider PROVIDER = new ModelMetaBaseSQLProvider();
+
+ @Test
+ void testInsertPersistsVersionColumns() {
+ String sql = PROVIDER.insertModelMeta(null);
+
+ Assertions.assertTrue(sql.contains("current_version, last_version"));
+ Assertions.assertTrue(sql.contains("#{modelMeta.currentVersion}, #{modelMeta.lastVersion}"));
+ }
+
+ @Test
+ void testOverwriteAdvancesStoredVersion() {
+ String sql = PROVIDER.insertModelMetaOnDuplicateKeyUpdate(null);
+ String insertClause = sql.substring(0, sql.indexOf(" ON DUPLICATE KEY UPDATE"));
+ String updateClause = sql.substring(sql.indexOf(" ON DUPLICATE KEY UPDATE"));
+
+ Assertions.assertTrue(insertClause.contains("current_version, last_version"));
+ Assertions.assertTrue(
+ insertClause.contains("#{modelMeta.currentVersion}, #{modelMeta.lastVersion}"));
+ Assertions.assertTrue(updateClause.contains("last_version = current_version + 1"));
+ Assertions.assertTrue(updateClause.contains("current_version = current_version + 1"));
+ Assertions.assertTrue(
+ updateClause.contains(
+ "model_latest_version ="
+ + " GREATEST(COALESCE(model_latest_version, 0),"
+ + " #{modelMeta.modelLatestVersion})"));
+ Assertions.assertFalse(updateClause.contains("current_version = #{modelMeta.currentVersion}"));
+ Assertions.assertFalse(updateClause.contains("last_version = #{modelMeta.lastVersion}"));
+ }
+
+ @Test
+ void testUpdateUsesOnlyIdVersionAndActiveStateForCas() {
+ String sql = PROVIDER.updateModelMeta(null, null);
+ String whereClause = sql.substring(sql.indexOf(" WHERE"));
+
+ Assertions.assertEquals(
+ " WHERE model_id = #{oldModelMeta.modelId}"
+ + " AND current_version = #{oldModelMeta.currentVersion}"
+ + " AND deleted_at = 0",
+ whereClause);
+ }
+
+ @Test
+ void testDirectDeleteUsesVersionCas() {
+ String sql = PROVIDER.softDeleteModelMetaByIdAndVersion(null, null);
+
+ Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
+ Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
+ }
+
+ @Test
+ void testConflictReadLocksActiveRow() {
+ String sql = PROVIDER.selectModelMetaByModelIdForUpdate(null);
+
+ Assertions.assertTrue(sql.contains("WHERE model_id = #{modelId} AND deleted_at = 0"));
+ Assertions.assertTrue(sql.endsWith("FOR UPDATE"));
+ }
+
+ @Test
+ void testAggregateVersionBumpIsGuardedOnIdentity() {
+ String sql = PROVIDER.bumpModelVersion(null, null, null);
+
+ Assertions.assertTrue(
+ sql.contains("last_version = current_version + 1, current_version = current_version + 1"));
+ // Guarded on the identity the caller resolved: a version another writer registered in the
+ // meantime must not reject this write, while a dropped or renamed model must.
+ Assertions.assertTrue(sql.contains("WHERE model_id = #{modelId}"));
+ Assertions.assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ Assertions.assertTrue(sql.contains("AND model_name = #{modelName}"));
+ Assertions.assertFalse(sql.contains("AND current_version = #{currentVersion}"));
+ Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
+ }
+
+ @Test
+ void testRegistrationAdvancesAllocatorAndAggregateVersionTogether() {
+ String sql = PROVIDER.bumpModelVersionAndLatestVersion(null, null, null);
+
+ Assertions.assertTrue(sql.contains("model_latest_version = model_latest_version + 1"));
+ Assertions.assertTrue(
+ sql.contains("last_version = current_version + 1, current_version = current_version + 1"));
+ Assertions.assertTrue(sql.contains("WHERE model_id = #{modelId}"));
+ Assertions.assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ Assertions.assertTrue(sql.contains("AND model_name = #{modelName}"));
+ Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
+ }
+
+ @Test
+ void testEveryModelReadProjectsVersionColumns() {
+ List<String> readSqls =
+ List.of(
+ PROVIDER.listModelPOsBySchemaId(null),
+ PROVIDER.listModelPOsByFullQualifiedName(null, null, null),
+ PROVIDER.listModelPOsByModelIds(null),
+ PROVIDER.selectModelMetaBySchemaIdAndModelName(null, null),
+ PROVIDER.selectModelByFullQualifiedName(null, null, null, null),
+ PROVIDER.selectModelMetaByModelId(null),
+ PROVIDER.selectModelMetaByModelIdForUpdate(null),
+ PROVIDER.batchSelectModelByIdentifier(null, null, null, null));
+
+ readSqls.forEach(
+ sql -> {
+ Assertions.assertTrue(sql.contains("currentVersion"), () -> "Missing OCC token: " + sql);
+ Assertions.assertTrue(
+ sql.contains("lastVersion"), () -> "Missing last OCC version: " + sql);
+ });
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelVersionRegistrationSQLProviders.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelVersionRegistrationSQLProviders.java
new file mode 100644
index 0000000000..19d215fb6b
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestModelVersionRegistrationSQLProviders.java
@@ -0,0 +1,45 @@
+/*
+ * 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.mapper.provider.base;
+
+import java.util.List;
+import org.apache.gravitino.storage.relational.mapper.provider.h2.ModelVersionMetaH2Provider;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestModelVersionRegistrationSQLProviders {
+
+ @Test
+ void testVersionInsertUsesReservedAllocatorValue() {
+ List<ModelVersionMetaBaseSQLProvider> providers =
+ List.of(new ModelVersionMetaBaseSQLProvider(), new ModelVersionMetaH2Provider());
+
+ providers.forEach(
+ provider ->
+ Assertions.assertTrue(
+ provider.insertModelVersionMetas(null).contains("m.model_latest_version - 1")));
+ }
+
+ @Test
+ void testAliasInsertUsesReservedAllocatorValue() {
+ String sql = new ModelVersionAliasRelBaseSQLProvider().insertModelVersionAliasRels(null);
+
+ Assertions.assertTrue(sql.contains("SELECT model_latest_version - 1"));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestModelMetaPostgreSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestModelMetaPostgreSQLProvider.java
new file mode 100644
index 0000000000..6912d08f28
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestModelMetaPostgreSQLProvider.java
@@ -0,0 +1,62 @@
+/*
+ * 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.mapper.provider.postgresql;
+
+import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestModelMetaPostgreSQLProvider {
+
+ @Test
+ void testOverwriteAdvancesStoredVersion() {
+ String sql = new ModelMetaPostgreSQLProvider().insertModelMetaOnDuplicateKeyUpdate(null);
+ String insertClause = sql.substring(0, sql.indexOf(" ON CONFLICT"));
+ String updateClause = conflictClause();
+
+ Assertions.assertTrue(insertClause.contains("current_version, last_version"));
+ Assertions.assertTrue(
+ insertClause.contains("#{modelMeta.currentVersion}, #{modelMeta.lastVersion}"));
+ Assertions.assertTrue(
+ updateClause.contains(
+ "current_version = " + ModelMetaMapper.TABLE_NAME + ".current_version + 1"));
+ Assertions.assertTrue(
+ updateClause.contains(
+ "last_version = " + ModelMetaMapper.TABLE_NAME + ".current_version + 1"));
+ Assertions.assertTrue(
+ updateClause.contains(
+ "model_latest_version = GREATEST("
+ + ModelMetaMapper.TABLE_NAME
+ + ".model_latest_version, #{modelMeta.modelLatestVersion})"));
+ Assertions.assertFalse(updateClause.matches(".*[^.\\w]current_version\\s*\\+.*"));
+ }
+
+ @Test
+ void testDirectDeleteUsesVersionCas() {
+ String sql = new ModelMetaPostgreSQLProvider().softDeleteModelMetaByIdAndVersion(null, null);
+
+ Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
+ Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
+ }
+
+ private String conflictClause() {
+ String sql = new ModelMetaPostgreSQLProvider().insertModelMetaOnDuplicateKeyUpdate(null);
+ return sql.substring(sql.indexOf(" ON CONFLICT"));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java
index c1b85ccfe2..f188388b82 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java
@@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
@@ -32,15 +33,21 @@ import org.apache.gravitino.EntityAlreadyExistsException;
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.BaseMetalake;
import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.ModelVersionEntity;
+import org.apache.gravitino.model.ModelVersion;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.storage.relational.po.ModelPO;
import org.apache.gravitino.storage.relational.utils.POConverters;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
+import org.mockito.Mockito;
public class TestModelMetaService extends TestJDBCBackend {
@@ -201,6 +208,89 @@ public class TestModelMetaService extends TestJDBCBackend {
.listModelsByNamespace(Namespace.of(METALAKE_NAME, CATALOG_NAME, "inexistent")));
}
+ @TestTemplate
+ public void testDeleteModelRejectsConcurrentVersionRegistration() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+
+ ModelEntity modelEntity =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model_dropped_during_version_register",
+ "model comment",
+ 0,
+ ImmutableMap.of("k1", "v1"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(modelEntity, false);
+
+ ModelPO stalePO =
+ ModelMetaService.getInstance().getModelPOByIdentifier(modelEntity.nameIdentifier());
+ // Registering a version advances the concurrency version the model shares with its versions,
+ // so a drop that read the model before that point loses its compare-and-set.
+ ModelVersionMetaService.getInstance()
+ .insertModelVersion(
+ ModelVersionEntity.builder()
+ .withModelIdentifier(modelEntity.nameIdentifier())
+ .withVersion(0)
+ .withUris(ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path"))
+ .withAliases(Lists.newArrayList("alias1"))
+ .withComment("version comment")
+ .withProperties(ImmutableMap.of("k1", "v1"))
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+
+ ModelMetaService service = Mockito.spy(ModelMetaService.getInstance());
+ Mockito.doReturn(stalePO).when(service).getModelPOByIdentifier(modelEntity.nameIdentifier());
+
+ // A stale drop must not retry with a newer snapshot. Retrying would silently delete the model
+ // version that won the race and defeat the compare-and-set contract exposed to callers.
+ Assertions.assertThrows(
+ OptimisticLockException.class, () -> service.deleteModel(modelEntity.nameIdentifier()));
+ ModelEntity survivingModel =
+ ModelMetaService.getInstance().getModelByIdentifier(modelEntity.nameIdentifier());
+ Assertions.assertEquals(modelEntity.id(), survivingModel.id());
+ Assertions.assertEquals(1, survivingModel.latestVersion());
+ Assertions.assertEquals(
+ "path",
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(
+ NameIdentifierUtil.ofModelVersion(
+ METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, modelEntity.name(), "alias1"))
+ .uris()
+ .get(ModelVersion.URI_NAME_UNKNOWN));
+ }
+
+ @TestTemplate
+ public void testDeleteModelLosingRaceToAnotherDeleteReturnsFalse() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+
+ ModelEntity modelEntity =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model1",
+ "model1 comment",
+ 0,
+ ImmutableMap.of("k1", "v1"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(modelEntity, false);
+
+ ModelPO observedModelPO =
+ ModelMetaService.getInstance().getModelPOByIdentifier(modelEntity.nameIdentifier());
+ // Another node drops the model after this one read it, so the compare-and-set below matches no
+ // row and the model turns out to be gone rather than concurrently modified.
+ Assertions.assertTrue(ModelMetaService.getInstance().deleteModel(modelEntity.nameIdentifier()));
+
+ ModelMetaService service = Mockito.spy(ModelMetaService.getInstance());
+ Mockito.doReturn(observedModelPO)
+ .when(service)
+ .getModelPOByIdentifier(modelEntity.nameIdentifier());
+
+ // A drop that finds nothing left to drop stays a plain false, the same answer the caller gets
+ // when the model was already gone before it was read.
+ Assertions.assertFalse(service.deleteModel(modelEntity.nameIdentifier()));
+ }
+
@TestTemplate
public void testInsertAndDeleteModel() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
@@ -397,4 +487,132 @@ public class TestModelMetaService extends TestJDBCBackend {
ModelMetaService.getInstance()
.updateModel(NameIdentifier.of(MODEL_NS, "model3"), renameUpdater));
}
+
+ @TestTemplate
+ void testAlterRejectsStaleVersionAndKeepsWinner() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model_alter_conflict",
+ "original",
+ 0,
+ ImmutableMap.of("key", "value"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelPO initialPO = ModelMetaService.getInstance().getModelPOById(model.id());
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelMetaService.getInstance()
+ .updateModel(
+ model.nameIdentifier(),
+ entity -> {
+ updateModelUnchecked(
+ model.nameIdentifier(), current -> copyModel(current, "winner"));
+ return copyModel((ModelEntity) entity, "stale update");
+ }));
+
+ ModelEntity current =
+ ModelMetaService.getInstance().getModelByIdentifier(model.nameIdentifier());
+ ModelPO currentPO = ModelMetaService.getInstance().getModelPOById(model.id());
+ Assertions.assertEquals("winner", current.comment());
+ Assertions.assertEquals(initialPO.getCurrentVersion() + 1, currentPO.getCurrentVersion());
+ Assertions.assertEquals(currentPO.getCurrentVersion(), currentPO.getLastVersion());
+ }
+
+ @TestTemplate
+ void testOverwriteAdvancesVersionAndRejectsStaleDelete() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model_overwrite_conflict",
+ "original",
+ 0,
+ ImmutableMap.of("key", "value"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity modelVersion =
+ ModelVersionEntity.builder()
+ .withModelIdentifier(model.nameIdentifier())
+ .withVersion(0)
+ .withUris(ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"))
+ .withAliases(List.of("surviving_alias"))
+ .withComment("version comment")
+ .withProperties(ImmutableMap.of("version_key", "version_value"))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ ModelVersionMetaService.getInstance().insertModelVersion(modelVersion);
+ ModelPO stalePO = ModelMetaService.getInstance().getModelPOById(model.id());
+
+ // Simulate an overwrite request that carries the model snapshot from before version 0 was
+ // registered. It must update model metadata without moving the version allocator backwards.
+ ModelMetaService.getInstance().insertModel(copyModel(model, "winner"), true);
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ ModelMetaService.getInstance()
+ .deleteModelWithVersion(model.nameIdentifier(), stalePO)));
+ ModelEntity current =
+ ModelMetaService.getInstance().getModelByIdentifier(model.nameIdentifier());
+ ModelPO currentPO = ModelMetaService.getInstance().getModelPOById(model.id());
+ Assertions.assertEquals("winner", current.comment());
+ Assertions.assertEquals(stalePO.getCurrentVersion() + 1, currentPO.getCurrentVersion());
+ Assertions.assertEquals(currentPO.getCurrentVersion(), currentPO.getLastVersion());
+ Assertions.assertEquals(1, current.latestVersion());
+ Assertions.assertEquals(
+ modelVersion,
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(modelVersion.nameIdentifier()));
+ Assertions.assertEquals(
+ modelVersion,
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(
+ NameIdentifier.of(modelVersion.nameIdentifier().namespace(), "surviving_alias")));
+
+ ModelVersionEntity nextModelVersion =
+ ModelVersionEntity.builder()
+ .withModelIdentifier(model.nameIdentifier())
+ .withVersion(1)
+ .withUris(ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "next_model_path"))
+ .withAliases(List.of("next_alias"))
+ .withComment("next version comment")
+ .withProperties(ImmutableMap.of("next_key", "next_value"))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ ModelVersionMetaService.getInstance().insertModelVersion(nextModelVersion);
+ Assertions.assertEquals(
+ nextModelVersion,
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(
+ NameIdentifier.of(nextModelVersion.nameIdentifier().namespace(), "1")));
+ }
+
+ private ModelEntity copyModel(ModelEntity model, String comment) {
+ return ModelEntity.builder()
+ .withId(model.id())
+ .withName(model.name())
+ .withNamespace(model.namespace())
+ .withComment(comment)
+ .withLatestVersion(model.latestVersion())
+ .withProperties(model.properties())
+ .withAuditInfo(model.auditInfo())
+ .build();
+ }
+
+ private void updateModelUnchecked(
+ NameIdentifier identifier, Function<ModelEntity, ModelEntity> updater) {
+ try {
+ ModelMetaService.getInstance().updateModel(identifier, updater);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
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.java
index 888c577b4e..1aa158666f 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
@@ -42,6 +42,7 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.IllegalNamespaceException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
+import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.ModelVersionEntity;
@@ -49,14 +50,20 @@ import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.model.ModelVersion;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
+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.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.SchemaPO;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
public class TestModelVersionMetaService extends TestJDBCBackend {
@@ -171,6 +178,230 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
.isEmpty());
}
+ @TestTemplate
+ public void testRegisterModelVersionAcceptsAConcurrentRegistration() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model_registered_from_two_nodes",
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+
+ ModelPO observedModelPO =
+ ModelMetaService.getInstance().getModelPOByIdentifier(model.nameIdentifier());
+ // Another node registers a version after this one read the model. That advances the version the
+ // model shares with its versions, but it does not conflict with the registration below: the two
+ // append different rows.
+ ModelVersionMetaService.getInstance()
+ .insertModelVersion(
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path_from_the_other_node"),
+ ImmutableList.of("alias_from_the_other_node"),
+ "version comment",
+ properties,
+ AUDIT_INFO));
+
+ ModelMetaService modelMetaService = Mockito.spy(ModelMetaService.getInstance());
+ Mockito.doReturn(observedModelPO)
+ .when(modelMetaService)
+ .getModelPOByIdentifier(model.nameIdentifier());
+
+ try (MockedStatic<ModelMetaService> mocked = Mockito.mockStatic(ModelMetaService.class)) {
+ mocked.when(ModelMetaService::getInstance).thenReturn(modelMetaService);
+
+ Assertions.assertDoesNotThrow(
+ () ->
+ ModelVersionMetaService.getInstance()
+ .insertModelVersion(
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 1,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path_from_this_node"),
+ ImmutableList.of("alias_from_this_node"),
+ "version comment",
+ properties,
+ AUDIT_INFO)));
+ }
+
+ Assertions.assertEquals(
+ 2,
+ ModelVersionMetaService.getInstance()
+ .listModelVersionsByNamespace(NamespaceUtil.toModelVersionNs(model.nameIdentifier()))
+ .size());
+ }
+
+ @TestTemplate
+ public void testDeleteModelVersionLosingRaceToModelDropReturnsFalse() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ "model_dropped_during_version_delete",
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity modelVersion =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path"),
+ aliases,
+ "version comment",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(modelVersion);
+
+ ModelPO observedModelPO =
+ ModelMetaService.getInstance().getModelPOByIdentifier(model.nameIdentifier());
+ // Another node drops the model row after this one read it, while the version rows this delete
+ // is about are still visible. The version bump below is what discovers the model is gone.
+ SessionUtils.doWithCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.softDeleteModelMetaByIdAndVersion(
+ observedModelPO.getModelId(), observedModelPO.getCurrentVersion()));
+
+ ModelMetaService modelMetaService = Mockito.spy(ModelMetaService.getInstance());
+ Mockito.doReturn(observedModelPO)
+ .when(modelMetaService)
+ .getModelPOByIdentifier(model.nameIdentifier());
+
+ try (MockedStatic<ModelMetaService> mocked = Mockito.mockStatic(ModelMetaService.class)) {
+ mocked.when(ModelMetaService::getInstance).thenReturn(modelMetaService);
+
+ // A version delete whose model disappeared underneath it reports the same false as a delete
+ // that found no model in the first place.
+ Assertions.assertFalse(
+ ModelVersionMetaService.getInstance().deleteModelVersion(modelVersion.nameIdentifier()));
+ }
+ }
+
+ @TestTemplate
+ public void testDeleteModelVersionRejectsConcurrentAliasReassignment() throws Exception {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity firstVersion =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "first_path"),
+ ImmutableList.of("moving_alias"),
+ "first",
+ properties,
+ AUDIT_INFO);
+ ModelVersionEntity secondVersion =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 1,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "second_path"),
+ ImmutableList.of("second_alias"),
+ "second",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(firstVersion);
+ ModelVersionMetaService.getInstance().insertModelVersion(secondVersion);
+ ModelPO modelPO = ModelMetaService.getInstance().getModelPOById(model.id());
+ NameIdentifier aliasIdentifier = getModelVersionIdent(model.nameIdentifier(), "moving_alias");
+
+ Throwable deleteFailure =
+ runAfterConcurrentModelWrite(
+ modelPO,
+ () ->
+ SessionUtils.doWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper -> {
+ mapper.softDeleteModelVersionAliasRelsByModelIdAndVersion(
+ model.id(), firstVersion.version());
+ mapper.updateModelVersionAliasRel(
+ ImmutableList.of(
+ ModelVersionAliasRelPO.builder()
+ .withModelId(model.id())
+ .withModelVersion(secondVersion.version())
+ .withModelVersionAlias("moving_alias")
+ .withDeletedAt(0L)
+ .build()));
+ }),
+ () -> ModelVersionMetaService.getInstance().deleteModelVersion(aliasIdentifier));
+ Assertions.assertInstanceOf(OptimisticLockException.class, deleteFailure);
+
+ Assertions.assertEquals(
+ firstVersion.version(),
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(firstVersion.nameIdentifier())
+ .version());
+ Assertions.assertEquals(
+ secondVersion.version(),
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(aliasIdentifier)
+ .version());
+ }
+
+ @TestTemplate
+ public void testDeleteModelVersionLosingRaceToVersionDeleteReturnsFalse() throws Exception {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path"),
+ ImmutableList.of("deleted_alias"),
+ "version comment",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+ ModelPO modelPO = ModelMetaService.getInstance().getModelPOById(model.id());
+
+ Throwable deleteFailure =
+ runAfterConcurrentModelWrite(
+ modelPO,
+ () -> {
+ SessionUtils.doWithoutCommit(
+ ModelVersionMetaMapper.class,
+ mapper ->
+ mapper.softDeleteModelVersionMetaByModelIdAndVersion(
+ model.id(), version.version()));
+ SessionUtils.doWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper ->
+ mapper.softDeleteModelVersionAliasRelsByModelIdAndVersion(
+ model.id(), version.version()));
+ },
+ () ->
+ Assertions.assertFalse(
+ ModelVersionMetaService.getInstance()
+ .deleteModelVersion(version.nameIdentifier())));
+ Assertions.assertNull(deleteFailure);
+ }
+
@TestTemplate
public void testUpdateModelVersionFailsWhenSchemaIsDeletedConcurrently() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
@@ -228,6 +459,112 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
.isEmpty());
}
+ @TestTemplate
+ public void testUpdateModelVersionRejectsConcurrentAliasReassignment() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity firstVersion =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "first_path"),
+ ImmutableList.of("moving_alias"),
+ "first",
+ properties,
+ AUDIT_INFO);
+ ModelVersionEntity secondVersion =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 1,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "second_path"),
+ ImmutableList.of("second_alias"),
+ "second",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(firstVersion);
+ ModelVersionMetaService.getInstance().insertModelVersion(secondVersion);
+
+ NameIdentifier aliasIdentifier = getModelVersionIdent(model.nameIdentifier(), "moving_alias");
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ aliasIdentifier,
+ current -> {
+ updateModelVersionUnchecked(
+ firstVersion.nameIdentifier(),
+ winner ->
+ copyModelVersion(winner, winner.comment(), Collections.emptyList()));
+ updateModelVersionUnchecked(
+ secondVersion.nameIdentifier(),
+ winner ->
+ copyModelVersion(
+ winner,
+ winner.comment(),
+ ImmutableList.of("second_alias", "moving_alias")));
+ return copyModelVersion((ModelVersionEntity) current, "stale update");
+ }));
+
+ Assertions.assertEquals(
+ "first",
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(firstVersion.nameIdentifier())
+ .comment());
+ Assertions.assertEquals(
+ secondVersion.version(),
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(aliasIdentifier)
+ .version());
+ }
+
+ @TestTemplate
+ public void testUpdateModelVersionLosingRaceToVersionDeleteReportsMissing() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "path"),
+ ImmutableList.of("deleted_alias"),
+ "version comment",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ version.nameIdentifier(),
+ current -> {
+ Assertions.assertTrue(
+ ModelVersionMetaService.getInstance()
+ .deleteModelVersion(version.nameIdentifier()));
+ return copyModelVersion((ModelVersionEntity) current, "stale update");
+ }));
+ }
+
@TestTemplate
public void testInsertAndSelectModelVersion() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
@@ -1140,6 +1477,240 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
Assertions.assertEquals(updatedVersionAliases, altered.aliases());
}
+ @TestTemplate
+ void testModelVersionWritesAdvanceAggregateVersion() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ assertModelCurrentVersion(model.id(), 1L);
+
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
+ ImmutableList.of("aggregate_alias"),
+ "original",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+ assertModelCurrentVersion(model.id(), 2L);
+
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ version.nameIdentifier(),
+ current -> copyModelVersion((ModelVersionEntity) current, "updated"));
+ assertModelCurrentVersion(model.id(), 3L);
+
+ Assertions.assertTrue(
+ ModelVersionMetaService.getInstance().deleteModelVersion(version.nameIdentifier()));
+ assertModelCurrentVersion(model.id(), 4L);
+ }
+
+ @TestTemplate
+ void testModelVersionAlterRejectsStaleAggregateVersion() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
+ ImmutableList.of("stale_alias"),
+ "original",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ version.nameIdentifier(),
+ current -> {
+ updateModelVersionUnchecked(
+ version.nameIdentifier(), winner -> copyModelVersion(winner, "winner"));
+ return copyModelVersion((ModelVersionEntity) current, "stale update");
+ }));
+
+ ModelVersionEntity current =
+ ModelVersionMetaService.getInstance().getModelVersionByIdentifier(version.nameIdentifier());
+ Assertions.assertEquals("winner", current.comment());
+ assertModelCurrentVersion(model.id(), 3L);
+ }
+
+ @TestTemplate
+ void testModelVersionAlterRejectsConcurrentAliasUpdate() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
+ ImmutableList.of("original_alias"),
+ "original",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ version.nameIdentifier(),
+ current -> {
+ updateModelVersionUnchecked(
+ version.nameIdentifier(),
+ winner ->
+ copyModelVersion(
+ winner, winner.comment(), ImmutableList.of("winner_alias")));
+ return copyModelVersion(
+ (ModelVersionEntity) current,
+ "stale update",
+ ImmutableList.of("loser_alias"));
+ }));
+
+ ModelVersionEntity current =
+ ModelVersionMetaService.getInstance().getModelVersionByIdentifier(version.nameIdentifier());
+ Assertions.assertEquals("original", current.comment());
+ Assertions.assertEquals(ImmutableList.of("winner_alias"), current.aliases());
+ assertModelCurrentVersion(model.id(), 3L);
+ }
+
+ @TestTemplate
+ void testModelVersionAlterRejectsConcurrentUriUpdate() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity version =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "original_path"),
+ ImmutableList.of("version_alias"),
+ "original",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ version.nameIdentifier(),
+ current -> {
+ updateModelVersionUnchecked(
+ version.nameIdentifier(),
+ winner ->
+ copyModelVersion(
+ winner,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "winner_path")));
+ return copyModelVersion(
+ (ModelVersionEntity) current,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "loser_path"));
+ }));
+
+ ModelVersionEntity current =
+ ModelVersionMetaService.getInstance().getModelVersionByIdentifier(version.nameIdentifier());
+ Assertions.assertEquals(
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "winner_path"), current.uris());
+ assertModelCurrentVersion(model.id(), 3L);
+ }
+
+ @TestTemplate
+ void testAliasConflictRollsBackAggregateVersionAndVersionUpdate() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ MODEL_NS,
+ randomModelName(),
+ "model comment",
+ 0,
+ properties,
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ ModelVersionEntity first =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 0,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "first_path"),
+ ImmutableList.of("taken_alias"),
+ "first",
+ properties,
+ AUDIT_INFO);
+ ModelVersionEntity second =
+ createModelVersionEntity(
+ model.nameIdentifier(),
+ 1,
+ ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "second_path"),
+ ImmutableList.of("second_alias"),
+ "second",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(first);
+ ModelVersionMetaService.getInstance().insertModelVersion(second);
+ ModelPO beforeFailure = ModelMetaService.getInstance().getModelPOById(model.id());
+
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .updateModelVersion(
+ second.nameIdentifier(),
+ current ->
+ copyModelVersion(
+ (ModelVersionEntity) current,
+ "must roll back",
+ ImmutableList.of("taken_alias"))));
+
+ ModelPO afterFailure = ModelMetaService.getInstance().getModelPOById(model.id());
+ ModelVersionEntity unchanged =
+ ModelVersionMetaService.getInstance().getModelVersionByIdentifier(second.nameIdentifier());
+ Assertions.assertEquals(beforeFailure.getCurrentVersion(), afterFailure.getCurrentVersion());
+ Assertions.assertEquals(beforeFailure.getLastVersion(), afterFailure.getLastVersion());
+ Assertions.assertEquals("second", unchanged.comment());
+ Assertions.assertEquals(ImmutableList.of("second_alias"), unchanged.aliases());
+ }
+
@TestTemplate
void testDeleteModelVersionsByLegacyTimeline() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
@@ -1261,4 +1832,123 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
.withAuditInfo(auditInfo)
.build();
}
+
+ private ModelVersionEntity copyModelVersion(ModelVersionEntity version, String comment) {
+ return copyModelVersion(version, comment, version.aliases());
+ }
+
+ private ModelVersionEntity copyModelVersion(
+ ModelVersionEntity version, String comment, List<String> updatedAliases) {
+ return createModelVersionEntity(
+ version.modelIdentifier(),
+ version.version(),
+ version.uris(),
+ updatedAliases,
+ comment,
+ version.properties(),
+ version.auditInfo());
+ }
+
+ private ModelVersionEntity copyModelVersion(
+ ModelVersionEntity version, Map<String, String> updatedUris) {
+ return createModelVersionEntity(
+ version.modelIdentifier(),
+ version.version(),
+ updatedUris,
+ version.aliases(),
+ version.comment(),
+ version.properties(),
+ version.auditInfo());
+ }
+
+ private void updateModelVersionUnchecked(
+ NameIdentifier identifier, Function<ModelVersionEntity, ModelVersionEntity> updater) {
+ try {
+ ModelVersionMetaService.getInstance().updateModelVersion(identifier, updater);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Throwable runAfterConcurrentModelWrite(
+ ModelPO modelPO, Runnable winnerMutation, Runnable loserMutation) throws Exception {
+ CountDownLatch modelLocked = new CountDownLatch(1);
+ CountDownLatch loserReachedModelWrite = new CountDownLatch(1);
+ CountDownLatch allowWinnerMutation = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ ModelMetaService modelMetaService = Mockito.spy(ModelMetaService.getInstance());
+ Mockito.doAnswer(
+ invocation -> {
+ loserReachedModelWrite.countDown();
+ return invocation.callRealMethod();
+ })
+ .when(modelMetaService)
+ .bumpModelVersion(Mockito.any(), Mockito.any());
+ Future<Throwable> winner =
+ executor.submit(
+ () ->
+ runAndCapture(
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () -> {
+ int updated =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.bumpModelVersion(
+ modelPO.getModelId(),
+ modelPO.getSchemaId(),
+ modelPO.getModelName()));
+ Assertions.assertEquals(1, updated);
+ modelLocked.countDown();
+ await(allowWinnerMutation);
+ winnerMutation.run();
+ })));
+
+ try {
+ Assertions.assertTrue(modelLocked.await(30, TimeUnit.SECONDS));
+ Future<Throwable> loser =
+ executor.submit(
+ () -> {
+ try (MockedStatic<ModelMetaService> mocked =
+ Mockito.mockStatic(ModelMetaService.class)) {
+ mocked.when(ModelMetaService::getInstance).thenReturn(modelMetaService);
+ return runAndCapture(loserMutation);
+ }
+ });
+ Assertions.assertTrue(loserReachedModelWrite.await(30, TimeUnit.SECONDS));
+ Assertions.assertThrows(TimeoutException.class, () -> loser.get(500, TimeUnit.MILLISECONDS));
+
+ allowWinnerMutation.countDown();
+ Assertions.assertNull(winner.get(30, TimeUnit.SECONDS));
+ return loser.get(30, TimeUnit.SECONDS);
+ } finally {
+ allowWinnerMutation.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ private Throwable runAndCapture(Runnable operation) {
+ try {
+ operation.run();
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ }
+
+ private void await(CountDownLatch latch) {
+ try {
+ Assertions.assertTrue(latch.await(30, TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void assertModelCurrentVersion(long modelId, long expectedVersion) {
+ ModelPO modelPO = ModelMetaService.getInstance().getModelPOById(modelId);
+ Assertions.assertEquals(expectedVersion, modelPO.getCurrentVersion());
+ Assertions.assertEquals(modelPO.getCurrentVersion(), modelPO.getLastVersion());
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java
index 2935e0b4e7..e7b0beae5f 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java
@@ -957,6 +957,8 @@ public class TestPOConverters {
JsonUtils.anyFieldMapper().readValue(modelPO.getAuditInfo(), AuditInfo.class);
assertEquals(auditInfo, resultAuditInfo);
assertEquals(1, modelPO.getModelLatestVersion());
+ assertEquals(1, modelPO.getCurrentVersion());
+ assertEquals(1, modelPO.getLastVersion());
assertEquals(0, modelPO.getDeletedAt());
// Test with null fields
@@ -1000,6 +1002,8 @@ public class TestPOConverters {
.withModelProperties(JsonUtils.anyFieldMapper().writeValueAsString(properties))
.withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(auditInfo))
.withModelLatestVersion(1)
+ .withCurrentVersion(1L)
+ .withLastVersion(1L)
.withDeletedAt(0L)
.build();
@@ -1029,6 +1033,8 @@ public class TestPOConverters {
.withModelProperties(JsonUtils.anyFieldMapper().writeValueAsString(null))
.withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(auditInfo))
.withModelLatestVersion(1)
+ .withCurrentVersion(1L)
+ .withLastVersion(1L)
.withDeletedAt(0L)
.build();
@@ -1058,6 +1064,8 @@ public class TestPOConverters {
.withModelProperties(JsonUtils.anyFieldMapper().writeValueAsString(emptyProperties))
.withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(auditInfo))
.withModelLatestVersion(1)
+ .withCurrentVersion(1L)
+ .withLastVersion(1L)
.withDeletedAt(0L)
.build();
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index 37e9732884..2ac5e66998 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -350,6 +350,8 @@ CREATE TABLE IF NOT EXISTS `model_meta` (
`model_comment` CLOB DEFAULT NULL COMMENT 'model comment',
`model_properties` CLOB DEFAULT NULL COMMENT 'model properties',
`model_latest_version` INT UNSIGNED DEFAULT 0 COMMENT 'model latest version',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model last allocated version',
`audit_info` CLOB NOT NULL COMMENT 'model audit info',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'model deleted at',
PRIMARY KEY (`model_id`),
diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
index 19d7f054dc..8175e0c630 100644
--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
@@ -28,6 +28,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS `uk_mid_geid_del` ON `group_meta` (`metalake_i
ALTER TABLE `table_column_version_info`
ALTER COLUMN `column_comment` VARCHAR(4096) DEFAULT '';
+ALTER TABLE `model_meta` ADD COLUMN `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model current version' AFTER `model_latest_version`;
+ALTER TABLE `model_meta` ADD COLUMN `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model last allocated version' AFTER `current_version`;
+
ALTER TABLE `tag_meta` ADD COLUMN `allowed_values` CLOB DEFAULT NULL COMMENT 'tag allowed values as a JSON string array, NULL allows any value, [] allows no value' AFTER `properties`;
ALTER TABLE `tag_relation_meta` DROP INDEX `uk_ti_mi_del`;
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index d6bdfb8f5e..b8042ef534 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -341,6 +341,8 @@ CREATE TABLE IF NOT EXISTS `model_meta` (
`model_comment` TEXT DEFAULT NULL COMMENT 'model comment',
`model_properties` MEDIUMTEXT DEFAULT NULL COMMENT 'model properties',
`model_latest_version` INT UNSIGNED DEFAULT 0 COMMENT 'model latest version',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model last allocated version',
`audit_info` MEDIUMTEXT NOT NULL COMMENT 'model audit info',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'model deleted at',
PRIMARY KEY (`model_id`),
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index d59ef44bcc..67fba282a2 100644
--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
@@ -70,6 +70,10 @@ ALTER TABLE `group_role_rel` RENAME INDEX `idx_rid` TO `group_role_rel_idx_rid`;
ALTER TABLE `tag_relation_meta` RENAME INDEX `idx_mid` TO `tag_relation_meta_idx_mid`;
ALTER TABLE `model_meta` RENAME INDEX `idx_mid` TO `model_meta_idx_mid`;
ALTER TABLE `model_meta` RENAME INDEX `idx_cid` TO `model_meta_idx_cid`;
+
+ALTER TABLE `model_meta`
+ ADD COLUMN `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model current version' AFTER `model_latest_version`,
+ ADD COLUMN `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model last allocated version' AFTER `current_version`;
ALTER TABLE `model_version_info` RENAME INDEX `idx_mid` TO `model_version_info_idx_mid`;
ALTER TABLE `model_version_info` RENAME INDEX `idx_cid` TO `model_version_info_idx_cid`;
ALTER TABLE `model_version_info` RENAME INDEX `idx_sid` TO `model_version_info_idx_sid`;
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index c0b0c0f6e8..2461b957af 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -598,11 +598,15 @@ CREATE TABLE IF NOT EXISTS model_meta (
model_comment VARCHAR(65535) DEFAULT NULL,
model_properties TEXT DEFAULT NULL,
model_latest_version INT NOT NULL DEFAULT 0,
+ current_version INT NOT NULL DEFAULT 1,
+ last_version INT NOT NULL DEFAULT 1,
audit_info TEXT NOT NULL,
deleted_at BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (model_id),
UNIQUE (schema_id, model_name, deleted_at)
);
+COMMENT ON COLUMN model_meta.current_version IS 'model current version';
+COMMENT ON COLUMN model_meta.last_version IS 'model last allocated version';
CREATE INDEX IF NOT EXISTS model_meta_idx_metalake_id ON model_meta (metalake_id);
CREATE INDEX IF NOT EXISTS model_meta_idx_catalog_id ON model_meta (catalog_id);
diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
index ea6edd173b..7a0a12d2b5 100644
--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
@@ -32,6 +32,11 @@ CREATE UNIQUE INDEX IF NOT EXISTS uk_mid_geid_del ON group_meta (metalake_id, ex
ALTER TABLE table_column_version_info
ALTER COLUMN column_comment TYPE VARCHAR(4096);
+ALTER TABLE model_meta ADD COLUMN IF NOT EXISTS current_version INT NOT NULL DEFAULT 1;
+ALTER TABLE model_meta ADD COLUMN IF NOT EXISTS last_version INT NOT NULL DEFAULT 1;
+COMMENT ON COLUMN model_meta.current_version IS 'model current version';
+COMMENT ON COLUMN model_meta.last_version IS 'model last allocated version';
+
ALTER TABLE tag_meta ADD COLUMN IF NOT EXISTS allowed_values TEXT DEFAULT NULL;
COMMENT ON COLUMN tag_meta.allowed_values IS 'tag allowed values as a JSON string array, NULL allows any value, [] allows no value';