This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new 9cf8ebb0b0 [#14752] fix(core): Avoid deadlock when concurrent model
renames swap names (#14789)
9cf8ebb0b0 is described below
commit 9cf8ebb0b04de9c83f2dbf68435c69f4b2bb9c53
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.
---
.../relational/service/ModelMetaService.java | 24 ++++++++
.../relational/service/TestModelMetaService.java | 70 ++++++++++++++++++++++
2 files changed, 94 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 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);