Skip to content

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

[#14752] fix(core): Avoid deadlock when concurrent model renames swap names (#14789)

Qi Yu9cf8ebb0b04d
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 1b209445f1..01fcea2c21 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
@@ -29,6 +29,7 @@ import java.util.Objects;
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;
@@ -337,6 +338,9 @@ public class ModelMetaService {
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
@@ -366,6 +370,26 @@ public class ModelMetaService {
return newEntity;
}
+ /**
+ * 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 f188388b82..0d48014f99 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
@@ -24,9 +24,15 @@ 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.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;
@@ -40,11 +46,14 @@ 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.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.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
import org.mockito.Mockito;
@@ -371,6 +380,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);