This is an automated email from the ASF dual-hosted git repository.

github-actions[bot] pushed a commit to branch cherry-pick-9cf8ebb0-to-branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit ddb033d39798d4f875c3e42046c14213f9d4c305
Author: Qi Yu <[email protected]>
AuthorDate: Mon Nov 9 21:50:41 2026 +0800

    [#14752] fix(core): Avoid deadlock when concurrent model renames swap names 
(#14789)
    
    ### What changes were proposed in this pull request?
    
    `ModelMetaService.updateModel` now checks the new name inside the
    transaction, before the `UPDATE`. If another live model holds the name,
    it fails with `EntityAlreadyExistsException`. The check takes no lock
    and uses an existing mapper query. No SQL or interface changes.
    
    ### Why are the changes needed?
    
    On PostgreSQL, the rename `UPDATE` waits on the unique index entry of
    the row that holds the new name. Two renames that swap names wait for
    each other, and one fails with a deadlock and HTTP 500.
    
    Fixes #14752
    
    ### Does this PR introduce _any_ user-facing change?
    
    Renaming a model onto a taken name now returns 409 instead of an
    occasional 500.
    
    Known limits:
    - Only the model rename path changes. Model is the one type with no tree
    lock on this path. Other types were not checked.
    - A name that appears after the check is still caught by the unique key,
    as before.
    
    ### How was this patch tested?
    
    - Added `testRenameOntoNameHeldByOpenWriteFailsWithoutWaiting`. It holds
    the target row in an open transaction, and fails on PostgreSQL without
    the fix.
    - `TestModelMetaService` passes on H2, MySQL and PostgreSQL.
    - Real server on PostgreSQL with two clients swapping names. Before: 2
    of 400 requests returned 500. After: all 800 returned 409, with no
    deadlock in the log.
    # Conflicts:
    #       
core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
---
 .../relational/service/ModelMetaService.java       | 54 +++++++++++++++++
 .../relational/service/TestModelMetaService.java   | 70 ++++++++++++++++++++++
 2 files changed, 124 insertions(+)

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 d492371024..ee616a304d 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
@@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
 import org.apache.gravitino.GravitinoEnv;
 import org.apache.gravitino.HasIdentifier;
 import org.apache.gravitino.MetadataObject;
@@ -379,6 +380,7 @@ public class ModelMetaService {
 
     AtomicInteger updateResult = new AtomicInteger(0);
     try {
+<<<<<<< HEAD
       SessionUtils.doMultipleWithCommit(
           () ->
               updateResult.set(
@@ -399,6 +401,38 @@ public class ModelMetaService {
                           OperateType.ALTER));
             }
           });
+=======
+      SchemaMetaService.getInstance()
+          .doWithSchemaWriteLock(
+              identifier,
+              oldModelPO.getSchemaId(),
+              oldModelPO.getCatalogId(),
+              oldModelPO.getMetalakeId(),
+              () -> {
+                if (isRenamed) {
+                  failIfModelNameTaken(oldModelPO, newEntity);
+                }
+                // The model CAS is the first child write. It succeeds only if 
the concurrency
+                // version
+                // still matches, 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) {
+                  EntityChangeLogWriter.append(
+                      oldModelIdent, Entity.EntityType.MODEL, 
OperateType.ALTER);
+                }
+              });
+>>>>>>> 9cf8ebb0b ([#14752] fix(core): Avoid deadlock when concurrent model 
renames swap names (#14789))
     } catch (RuntimeException re) {
       ExceptionUtils.checkSQLException(
           re, Entity.EntityType.MODEL, newEntity.nameIdentifier().toString());
@@ -412,6 +446,26 @@ public class ModelMetaService {
     }
   }
 
+  /**
+   * Fails a rename whose new name is already taken, before the UPDATE runs. 
On PostgreSQL the
+   * UPDATE waits on the unique index entry of the row that holds the name, so 
two renames that swap
+   * names would wait for each other and deadlock.
+   */
+  private void failIfModelNameTaken(ModelPO oldModelPO, ModelEntity newEntity) 
{
+    Long existingId =
+        SessionUtils.getWithoutCommit(
+            ModelMetaMapper.class,
+            mapper ->
+                mapper.selectModelIdBySchemaIdAndModelName(
+                    oldModelPO.getSchemaId(), newEntity.name()));
+    // The model's own row matches when the rename only changes case on a 
case-insensitive store.
+    if (existingId != null && !Objects.equals(existingId, 
oldModelPO.getModelId())) {
+      throw new EntityAlreadyExistsException(
+          "The %s entity: %s already exists.",
+          Entity.EntityType.MODEL.name(), newEntity.nameIdentifier());
+    }
+  }
+
   @Monitored(
       metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
       baseMetricName = "batchGetModelByIdentifier")
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..135b4e02fa 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
@@ -23,9 +23,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import com.google.common.collect.ImmutableMap;
 import java.io.IOException;
+import java.sql.Statement;
 import java.time.Instant;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.EntityAlreadyExistsException;
@@ -36,9 +42,12 @@ import org.apache.gravitino.meta.BaseMetalake;
 import org.apache.gravitino.meta.ModelEntity;
 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.po.ModelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
 import org.apache.gravitino.storage.relational.utils.POConverters;
 import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.TestTemplate;
 
@@ -281,6 +290,67 @@ public class TestModelMetaService extends TestJDBCBackend {
                 .updateModel(NameIdentifier.of(MODEL_NS, "model3"), 
renameUpdater));
   }
 
+  @TestTemplate
+  void testRenameOntoNameHeldByOpenWriteFailsWithoutWaiting() throws Exception 
{
+    createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+    Map<String, String> properties = ImmutableMap.of("k1", "v1");
+    ModelEntity source =
+        createModelEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            MODEL_NS,
+            "source",
+            "comment",
+            0,
+            properties,
+            AUDIT_INFO);
+    ModelEntity target =
+        createModelEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            MODEL_NS,
+            "target",
+            "comment",
+            0,
+            properties,
+            AUDIT_INFO);
+    ModelMetaService.getInstance().insertModel(source, false);
+    ModelMetaService.getInstance().insertModel(target, false);
+    ModelEntity renamed =
+        ModelEntity.builder()
+            .withId(source.id())
+            .withName(target.name())
+            .withNamespace(source.namespace())
+            .withLatestVersion(source.latestVersion())
+            .withAuditInfo(source.auditInfo())
+            .withComment(source.comment())
+            .withProperties(source.properties())
+            .build();
+    Function<ModelEntity, ModelEntity> renameUpdater = oldModel -> renamed;
+
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    try (SqlSession holder =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(false);
+        Statement statement = holder.getConnection().createStatement()) {
+      // Holding the target row open is what makes the UPDATE wait on its 
unique index entry.
+      statement.executeUpdate(
+          "UPDATE "
+              + ModelMetaMapper.TABLE_NAME
+              + " SET model_comment = 'held' WHERE model_name = 'target' AND 
deleted_at = 0");
+
+      Future<ModelEntity> rename =
+          executor.submit(
+              () ->
+                  ModelMetaService.getInstance()
+                      .updateModel(source.nameIdentifier(), renameUpdater));
+
+      ExecutionException failure =
+          Assertions.assertThrows(ExecutionException.class, () -> 
rename.get(15, TimeUnit.SECONDS));
+      Assertions.assertInstanceOf(EntityAlreadyExistsException.class, 
failure.getCause());
+      holder.rollback();
+    } finally {
+      executor.shutdownNow();
+    }
+  }
+
   @TestTemplate
   void testInsertAndUpdateModelComment() throws IOException {
     createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);

Reply via email to