Skip to content

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

[#13731] improvement(core): Remove TreeLock from partition, tag, policy, owner, model and table statistic operations (#13737)

Qi Yub837e07a933f
diff --git a/api/src/main/java/org/apache/gravitino/model/ModelCatalog.java b/api/src/main/java/org/apache/gravitino/model/ModelCatalog.java
index 7e6bf02f03..b890ddd04b 100644
--- a/api/src/main/java/org/apache/gravitino/model/ModelCatalog.java
+++ b/api/src/main/java/org/apache/gravitino/model/ModelCatalog.java
@@ -31,10 +31,23 @@ import org.apache.gravitino.exceptions.NoSuchModelException;
import org.apache.gravitino.exceptions.NoSuchModelVersionException;
import org.apache.gravitino.exceptions.NoSuchModelVersionURINameException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.OptimisticLockException;
/**
* The ModelCatalog interface defines the public API for managing model objects in a schema. If the
* catalog implementation supports model objects, it should implement this interface.
+ *
+ * <p>Gravitino does not serialize calls to this interface: methods may be invoked concurrently,
+ * including for the same model, from one server or from several. An implementation must keep
+ * version numbers and aliases unique under concurrent calls itself, for example by enforcing them
+ * in its storage.
+ *
+ * <p>Conflicting operations may fail with {@link OptimisticLockException}. This includes reads when
+ * concurrent changes prevent obtaining consistent model-version metadata. Callers may retry reads
+ * with a bounded number of attempts; before retrying writes, reload the metadata and reconsider the
+ * intended change. For example, {@link #deleteModel} and {@link #alterModel} fail this way when a
+ * version of the model was linked, altered or deleted after the model was read, so that a drop
+ * never removes a version it did not observe.
*/
@Evolving
public interface ModelCatalog {
diff --git a/api/src/main/java/org/apache/gravitino/rel/SupportsPartitions.java b/api/src/main/java/org/apache/gravitino/rel/SupportsPartitions.java
index d4f5a21e6a..3348e4548b 100644
--- a/api/src/main/java/org/apache/gravitino/rel/SupportsPartitions.java
+++ b/api/src/main/java/org/apache/gravitino/rel/SupportsPartitions.java
@@ -26,7 +26,15 @@ import org.apache.gravitino.rel.partitions.ListPartition;
import org.apache.gravitino.rel.partitions.Partition;
import org.apache.gravitino.rel.partitions.RangePartition;
-/** Interface for tables that support partitions. */
+/**
+ * Interface for tables that support partitions.
+ *
+ * <p>Gravitino does not serialize calls to this interface: methods may be invoked concurrently,
+ * including for the same table, from one server or from several. Implementations must preserve
+ * partition consistency under concurrent calls, including partition-name uniqueness and safe add,
+ * drop and purge operations. Concurrent table changes must also be handled by the implementation or
+ * its underlying storage.
+ */
@Evolving
public interface SupportsPartitions {
diff --git a/api/src/main/java/org/apache/gravitino/tag/SupportsTags.java b/api/src/main/java/org/apache/gravitino/tag/SupportsTags.java
index 5d75cd139d..67805d1782 100644
--- a/api/src/main/java/org/apache/gravitino/tag/SupportsTags.java
+++ b/api/src/main/java/org/apache/gravitino/tag/SupportsTags.java
@@ -55,9 +55,9 @@ public interface SupportsTags {
/**
* Associate tags with no value to the specific object. The tagsToAdd will be added to the object,
- * and the tagsToRemove will be removed from the object. Missing tags are ignored. If the same tag
- * is in both tagsToAdd and tagsToRemove, it will be ignored. Repeated existing assignments are
- * idempotent.
+ * and the tagsToRemove will be removed from the object. Missing tags are ignored, including tags
+ * dropped or renamed while the call runs. If the same tag is in both tagsToAdd and tagsToRemove,
+ * it will be ignored. Repeated existing assignments are idempotent.
*
* @param tagsToAdd The array of tag names to be added to the object.
* @param tagsToRemove The array of tag names to be removed from the object.
diff --git a/catalogs/catalog-model/build.gradle.kts b/catalogs/catalog-model/build.gradle.kts
index 056cdaf9de..94a62230ff 100644
--- a/catalogs/catalog-model/build.gradle.kts
+++ b/catalogs/catalog-model/build.gradle.kts
@@ -40,6 +40,7 @@ dependencies {
testImplementation(project(":clients:client-java"))
testImplementation(project(":common"))
testImplementation(project(":core"))
+ testImplementation(project(":core", "testArtifacts"))
testImplementation(project(":integration-test-common", "testArtifacts"))
testImplementation(project(":server"))
testImplementation(project(":server-common"))
diff --git a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
index 0793521deb..cc1798ac37 100644
--- a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
+++ b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
@@ -48,9 +48,11 @@ import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -86,6 +88,7 @@ import org.apache.gravitino.model.ModelVersionChange;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.RaceTestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -119,7 +122,9 @@ public class TestModelCatalogOperations {
// they will be set automatically by the configuration file if you set ENTITY_RELATIONAL_STORE
// as EMBEDDED_ENTITY_RELATIONAL_STORE.
when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))
- .thenReturn(String.format("jdbc:h2:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", STORE_PATH));
+ .thenReturn(
+ String.format(
+ "jdbc:h2:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL;LOCK_TIMEOUT=30000", STORE_PATH));
when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("gravitino");
when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("gravitino");
when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");
@@ -2073,6 +2078,75 @@ public class TestModelCatalogOperations {
return "schema_" + UUID.randomUUID().toString().replace("-", "");
}
+ @Test
+ public void testConcurrentLinkModelVersionAllocatesDistinctVersions() throws Exception {
+ String schemaName = randomSchemaName();
+ createSchema(schemaName);
+ NameIdentifier modelIdent =
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, schemaName, "model_race");
+ ops.registerModel(modelIdent, null, StringIdentifier.newPropertiesWithId(newStringId(), null));
+
+ AtomicInteger aliasSeq = new AtomicInteger();
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ 8,
+ () -> {
+ ops.linkModelVersion(
+ modelIdent,
+ ImmutableMap.of("n1", "u1"),
+ new String[] {"alias_" + aliasSeq.getAndIncrement()},
+ null,
+ StringIdentifier.newPropertiesWithId(newStringId(), null));
+ return null;
+ });
+
+ outcomes.forEach(Assertions::assertNull);
+ int[] versions = ops.listModelVersions(modelIdent);
+ Arrays.sort(versions);
+ Assertions.assertArrayEquals(new int[] {0, 1, 2, 3, 4, 5, 6, 7}, versions);
+ Assertions.assertEquals(8, ops.getModel(modelIdent).latestVersion());
+ for (ModelVersion version : ops.listModelVersionInfos(modelIdent)) {
+ Assertions.assertEquals(1, version.aliases().length);
+ Assertions.assertEquals(
+ version.version(), ops.getModelVersion(modelIdent, version.aliases()[0]).version());
+ }
+ }
+
+ @Test
+ public void testConcurrentLinkModelVersionWithSameAliasHasOneWinner() throws Exception {
+ String schemaName = randomSchemaName();
+ createSchema(schemaName);
+ NameIdentifier modelIdent =
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, schemaName, "model_alias_race");
+ ops.registerModel(modelIdent, null, StringIdentifier.newPropertiesWithId(newStringId(), null));
+
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ 8,
+ () -> {
+ ops.linkModelVersion(
+ modelIdent,
+ ImmutableMap.of("n1", "u1"),
+ new String[] {"prod"},
+ null,
+ StringIdentifier.newPropertiesWithId(newStringId(), null));
+ return "linked";
+ });
+
+ Assertions.assertEquals(1, outcomes.stream().filter("linked"::equals).count());
+ outcomes.stream()
+ .filter(o -> !"linked".equals(o))
+ .forEach(
+ o -> Assertions.assertInstanceOf(ModelVersionAliasesAlreadyExistException.class, o));
+ int[] versions = ops.listModelVersions(modelIdent);
+ Assertions.assertEquals(1, versions.length);
+ Assertions.assertEquals(versions[0], ops.getModelVersion(modelIdent, "prod").version());
+ }
+
+ private StringIdentifier newStringId() {
+ return StringIdentifier.fromId(idGenerator.nextId());
+ }
+
private void createSchema(String schemaName) {
NameIdentifier schemaIdent =
NameIdentifierUtil.ofSchema(METALAKE_NAME, CATALOG_NAME, schemaName);
diff --git a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
index fc27c94718..9e56ecbe1c 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
@@ -35,8 +35,6 @@ import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NotFoundException;
-import org.apache.gravitino.lock.LockType;
-import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.meta.GroupEntity;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.utils.MetadataObjectUtil;
@@ -46,8 +44,9 @@ import org.slf4j.LoggerFactory;
/**
* OwnerManager is used for manage the owner of metadata object. The user and group don't have an
- * owner. Because the post hook will call the methods. We shouldn't add the lock of the metadata
- * object. Otherwise, it will cause deadlock.
+ * owner. It takes no tree lock: the entity store keeps one live owner per object and fences the
+ * object and the owner principal inside the owner write, which also lets the post hooks of create
+ * operations call it without lock ordering concerns.
*/
public class OwnerManager implements OwnerDispatcher {
private static final Logger LOG = LoggerFactory.getLogger(OwnerManager.class);
@@ -75,41 +74,29 @@ public class OwnerManager implements OwnerDispatcher {
OwnerImpl newOwner = new OwnerImpl();
if (ownerType == Owner.Type.USER) {
NameIdentifier ownerIdent = AuthorizationUtils.ofUser(metalake, ownerName);
- TreeLockUtils.doWithTreeLock(
- ownerIdent,
- LockType.READ,
- () -> {
- store
- .relationOperations()
- .insertRelation(
- SupportsRelationOperations.Type.OWNER_REL,
- objectIdent,
- MetadataObjectUtil.toEntityType(metadataObject),
- ownerIdent,
- Entity.EntityType.USER,
- true);
- return null;
- });
+ store
+ .relationOperations()
+ .insertRelation(
+ SupportsRelationOperations.Type.OWNER_REL,
+ objectIdent,
+ MetadataObjectUtil.toEntityType(metadataObject),
+ ownerIdent,
+ Entity.EntityType.USER,
+ true);
newOwner.name = ownerName;
newOwner.type = Owner.Type.USER;
} else if (ownerType == Owner.Type.GROUP) {
NameIdentifier ownerIdent = AuthorizationUtils.ofGroup(metalake, ownerName);
- TreeLockUtils.doWithTreeLock(
- ownerIdent,
- LockType.READ,
- () -> {
- store
- .relationOperations()
- .insertRelation(
- SupportsRelationOperations.Type.OWNER_REL,
- objectIdent,
- MetadataObjectUtil.toEntityType(metadataObject),
- ownerIdent,
- Entity.EntityType.GROUP,
- true);
- return null;
- });
+ store
+ .relationOperations()
+ .insertRelation(
+ SupportsRelationOperations.Type.OWNER_REL,
+ objectIdent,
+ MetadataObjectUtil.toEntityType(metadataObject),
+ ownerIdent,
+ Entity.EntityType.GROUP,
+ true);
newOwner.name = ownerName;
newOwner.type = Owner.Type.GROUP;
@@ -183,21 +170,15 @@ public class OwnerManager implements OwnerDispatcher {
}
try {
- TreeLockUtils.doWithTreeLock(
- ownerIdent,
- LockType.READ,
- () -> {
- store
- .relationOperations()
- .batchInsertRelations(
- SupportsRelationOperations.Type.OWNER_REL,
- owned,
- objectType,
- ownerIdent,
- ownerEntityType,
- true);
- return null;
- });
+ store
+ .relationOperations()
+ .batchInsertRelations(
+ SupportsRelationOperations.Type.OWNER_REL,
+ owned,
+ objectType,
+ ownerIdent,
+ ownerEntityType,
+ true);
// Owner relations are already persisted; a failure for one plugin notification must not
// abort the remaining notifications and leave the batch half-notified.
@@ -299,16 +280,12 @@ public class OwnerManager implements OwnerDispatcher {
OwnerImpl owner = new OwnerImpl();
try {
List<? extends Entity> entities =
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- store
- .relationOperations()
- .listEntitiesByRelation(
- SupportsRelationOperations.Type.OWNER_REL,
- ident,
- MetadataObjectUtil.toEntityType(metadataObject)));
+ store
+ .relationOperations()
+ .listEntitiesByRelation(
+ SupportsRelationOperations.Type.OWNER_REL,
+ ident,
+ MetadataObjectUtil.toEntityType(metadataObject));
if (entities.isEmpty()) {
return Optional.empty();
diff --git a/core/src/main/java/org/apache/gravitino/catalog/ModelOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ModelOperationDispatcher.java
index 6579f7adda..5bb3d49861 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/ModelOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/ModelOperationDispatcher.java
@@ -37,8 +37,6 @@ import org.apache.gravitino.exceptions.NoSuchModelException;
import org.apache.gravitino.exceptions.NoSuchModelVersionException;
import org.apache.gravitino.exceptions.NoSuchModelVersionURINameException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
-import org.apache.gravitino.lock.LockType;
-import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.model.Model;
import org.apache.gravitino.model.ModelCatalog;
import org.apache.gravitino.model.ModelChange;
@@ -60,28 +58,20 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
@Override
public NameIdentifier[] listModels(Namespace namespace) throws NoSuchSchemaException {
- return TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(namespace.levels()),
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
- c -> c.doWithModelOps(m -> m.listModels(namespace)),
- NoSuchSchemaException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(NameIdentifier.of(namespace.levels())),
+ c -> c.doWithModelOps(m -> m.listModels(namespace)),
+ NoSuchSchemaException.class);
}
@Override
public Model getModel(NameIdentifier ident) throws NoSuchModelException {
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
Model model =
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- catalogIdent,
- c -> c.doWithModelOps(m -> m.getModel(ident)),
- NoSuchModelException.class));
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithModelOps(m -> m.getModel(ident)),
+ NoSuchModelException.class);
return EntityCombinedModel.of(model)
.withHiddenProperties(
@@ -97,18 +87,12 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
checkAndUpdateProperties(
catalogIdent, properties, HasPropertyMetadata::modelPropertiesMetadata);
- // Lock the model node, not the schema, so models in the same schema can be registered
- // concurrently. See TableOperationDispatcher#createTable for the reasoning and trade-off.
Model registeredModel =
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- catalogIdent,
- c -> c.doWithModelOps(m -> m.registerModel(ident, comment, updatedProperties)),
- NoSuchSchemaException.class,
- ModelAlreadyExistsException.class));
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithModelOps(m -> m.registerModel(ident, comment, updatedProperties)),
+ NoSuchSchemaException.class,
+ ModelAlreadyExistsException.class);
return EntityCombinedModel.of(registeredModel)
.withHiddenProperties(
@@ -120,26 +104,18 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
@Override
public boolean deleteModel(NameIdentifier ident) {
- return TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(ident.namespace().levels()),
- LockType.WRITE,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.deleteModel(ident)),
- RuntimeException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.deleteModel(ident)),
+ RuntimeException.class);
}
@Override
public int[] listModelVersions(NameIdentifier ident) throws NoSuchModelException {
- return TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.listModelVersions(ident)),
- NoSuchModelException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.listModelVersions(ident)),
+ NoSuchModelException.class);
}
@Override
@@ -147,14 +123,10 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
return internalListModelVersion(
ident,
() ->
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.listModelVersionInfos(ident)),
- NoSuchModelException.class)));
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.listModelVersionInfos(ident)),
+ NoSuchModelException.class));
}
@Override
@@ -163,14 +135,10 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
return internalGetModelVersion(
ident,
() ->
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.getModelVersion(ident, version)),
- NoSuchModelVersionException.class)));
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.getModelVersion(ident, version)),
+ NoSuchModelVersionException.class));
}
@Override
@@ -179,14 +147,10 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
return internalGetModelVersion(
ident,
() ->
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.getModelVersion(ident, alias)),
- NoSuchModelVersionException.class)));
+ doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.getModelVersion(ident, alias)),
+ NoSuchModelVersionException.class));
}
@Override
@@ -202,72 +166,52 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
checkAndUpdateProperties(
catalogIdent, properties, HasPropertyMetadata::modelVersionPropertiesMetadata);
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithModelOps(
- m -> {
- m.linkModelVersion(ident, uris, aliases, comment, updatedProperties);
- return null;
- }),
- NoSuchModelException.class,
- ModelVersionAliasesAlreadyExistException.class));
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithModelOps(
+ m -> {
+ m.linkModelVersion(ident, uris, aliases, comment, updatedProperties);
+ return null;
+ }),
+ NoSuchModelException.class,
+ ModelVersionAliasesAlreadyExistException.class);
}
@Override
public String getModelVersionUri(NameIdentifier ident, int version, String uriName)
throws NoSuchModelVersionException, NoSuchModelVersionURINameException {
- return TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.getModelVersionUri(ident, version, uriName)),
- NoSuchModelVersionException.class,
- NoSuchModelVersionURINameException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.getModelVersionUri(ident, version, uriName)),
+ NoSuchModelVersionException.class,
+ NoSuchModelVersionURINameException.class);
}
@Override
public String getModelVersionUri(NameIdentifier ident, String alias, String uriName)
throws NoSuchModelVersionException, NoSuchModelVersionURINameException {
- return TreeLockUtils.doWithTreeLock(
- ident,
- LockType.READ,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.getModelVersionUri(ident, alias, uriName)),
- NoSuchModelVersionException.class,
- NoSuchModelVersionURINameException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.getModelVersionUri(ident, alias, uriName)),
+ NoSuchModelVersionException.class,
+ NoSuchModelVersionURINameException.class);
}
@Override
public boolean deleteModelVersion(NameIdentifier ident, int version) {
- return TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.deleteModelVersion(ident, version)),
- RuntimeException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.deleteModelVersion(ident, version)),
+ RuntimeException.class);
}
@Override
public boolean deleteModelVersion(NameIdentifier ident, String alias) {
- return TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- getCatalogIdentifier(ident),
- c -> c.doWithModelOps(m -> m.deleteModelVersion(ident, alias)),
- RuntimeException.class));
+ return doWithCatalog(
+ getCatalogIdentifier(ident),
+ c -> c.doWithModelOps(m -> m.deleteModelVersion(ident, alias)),
+ RuntimeException.class);
}
/** {@inheritDoc} */
@@ -278,15 +222,11 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
Model alteredModel =
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- catalogIdent,
- c -> c.doWithModelOps(f -> f.alterModel(ident, changes)),
- NoSuchModelException.class,
- IllegalArgumentException.class));
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithModelOps(f -> f.alterModel(ident, changes)),
+ NoSuchModelException.class,
+ IllegalArgumentException.class);
return EntityCombinedModel.of(alteredModel)
.withHiddenProperties(
@@ -319,15 +259,11 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
NameIdentifier catalogIdent = getCatalogIdentifier(ident);
ModelVersion alteredModelVersion =
- TreeLockUtils.doWithTreeLock(
- ident,
- LockType.WRITE,
- () ->
- doWithCatalog(
- catalogIdent,
- c -> c.doWithModelOps(fn),
- NoSuchModelVersionException.class,
- IllegalArgumentException.class));
+ doWithCatalog(
+ catalogIdent,
+ c -> c.doWithModelOps(fn),
+ NoSuchModelVersionException.class,
+ IllegalArgumentException.class);
return EntityCombinedModelVersion.of(alteredModelVersion)
.withHiddenProperties(
@@ -370,20 +306,15 @@ public class ModelOperationDispatcher extends OperationDispatcher implements Mod
NameIdentifier catalogIdent,
Map<String, String> properties,
Function<HasPropertyMetadata, PropertiesMetadata> propertiesMetadataProvider) {
- TreeLockUtils.doWithTreeLock(
+ doWithCatalog(
catalogIdent,
- LockType.READ,
- () ->
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithPropertiesMeta(
- p -> {
- validatePropertyForCreate(
- propertiesMetadataProvider.apply(p), properties);
- return null;
- }),
- IllegalArgumentException.class));
+ c ->
+ c.doWithPropertiesMeta(
+ p -> {
+ validatePropertyForCreate(propertiesMetadataProvider.apply(p), properties);
+ return null;
+ }),
+ IllegalArgumentException.class);
long uid = idGenerator.nextId();
StringIdentifier stringId = StringIdentifier.fromId(uid);
diff --git a/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java
index 8887dbb78a..9d5757884c 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/PartitionOperationDispatcher.java
@@ -23,8 +23,6 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.NoSuchPartitionException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;
-import org.apache.gravitino.lock.LockType;
-import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.rel.SupportsPartitions;
import org.apache.gravitino.rel.partitions.Partition;
import org.apache.gravitino.secret.SecretManager;
@@ -51,64 +49,39 @@ public class PartitionOperationDispatcher extends OperationDispatcher
@Override
public String[] listPartitionNames(NameIdentifier tableIdent) {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.READ,
- () ->
- doWithTable(
- tableIdent, SupportsPartitions::listPartitionNames, NoSuchTableException.class));
+ return doWithTable(
+ tableIdent, SupportsPartitions::listPartitionNames, NoSuchTableException.class);
}
@Override
public Partition[] listPartitions(NameIdentifier tableIdent) {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.READ,
- () ->
- doWithTable(
- tableIdent, SupportsPartitions::listPartitions, NoSuchTableException.class));
+ return doWithTable(tableIdent, SupportsPartitions::listPartitions, NoSuchTableException.class);
}
@Override
public Partition getPartition(NameIdentifier tableIdent, String partitionName)
throws NoSuchPartitionException {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.READ,
- () ->
- doWithTable(
- tableIdent, p -> p.getPartition(partitionName), NoSuchPartitionException.class));
+ return doWithTable(
+ tableIdent, p -> p.getPartition(partitionName), NoSuchPartitionException.class);
}
@Override
public Partition addPartition(NameIdentifier tableIdent, Partition partition)
throws PartitionAlreadyExistsException {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.WRITE,
- () ->
- doWithTable(
- tableIdent, p -> p.addPartition(partition), PartitionAlreadyExistsException.class));
+ return doWithTable(
+ tableIdent, p -> p.addPartition(partition), PartitionAlreadyExistsException.class);
}
@Override
public boolean dropPartition(NameIdentifier tableIdent, String partitionName) {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.WRITE,
- () ->
- doWithTable(
- tableIdent, p -> p.dropPartition(partitionName), NoSuchPartitionException.class));
+ return doWithTable(
+ tableIdent, p -> p.dropPartition(partitionName), NoSuchPartitionException.class);
}
@Override
public boolean purgePartition(NameIdentifier tableIdent, String partitionName)
throws UnsupportedOperationException {
- return TreeLockUtils.doWithTreeLock(
- tableIdent,
- LockType.WRITE,
- () ->
- doWithTable(
- tableIdent, p -> p.purgePartition(partitionName), NoSuchPartitionException.class));
+ return doWithTable(
+ tableIdent, p -> p.purgePartition(partitionName), NoSuchPartitionException.class);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
index 04da88ef7f..b742ef98e7 100644
--- a/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
+++ b/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java
@@ -37,8 +37,6 @@ import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
-import org.apache.gravitino.lock.LockType;
-import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.storage.IdGenerator;
@@ -79,42 +77,31 @@ public class PolicyManager implements PolicyDispatcher {
public PolicyEntity[] listPolicyInfos(String metalake) {
NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);
checkMetalake(metalakeIdent, entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(NamespaceUtil.ofPolicy(metalake).levels()),
- LockType.READ,
- () -> {
- try {
- return entityStore
- .list(
- NamespaceUtil.ofPolicy(metalake), PolicyEntity.class, Entity.EntityType.POLICY)
- .toArray(new PolicyEntity[0]);
- } catch (IOException ioe) {
- LOG.error("Failed to list policies under metalake {}", metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore
+ .list(NamespaceUtil.ofPolicy(metalake), PolicyEntity.class, Entity.EntityType.POLICY)
+ .toArray(new PolicyEntity[0]);
+ } catch (IOException ioe) {
+ LOG.error("Failed to list policies under metalake {}", metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
@Override
public PolicyEntity getPolicy(String metalake, String policyName) throws NoSuchPolicyException {
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- LockType.READ,
- () -> {
- try {
- return entityStore.get(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- Entity.EntityType.POLICY,
- PolicyEntity.class);
- } catch (NoSuchEntityException e) {
- throw new NoSuchPolicyException(
- "Policy with name %s under metalake %s does not exist", policyName, metalake);
- } catch (IOException ioe) {
- LOG.error("Failed to get policy {} under metalake {}", policyName, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore.get(
+ NameIdentifierUtil.ofPolicy(metalake, policyName),
+ Entity.EntityType.POLICY,
+ PolicyEntity.class);
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchPolicyException(
+ "Policy with name %s under metalake %s does not exist", policyName, metalake);
+ } catch (IOException ioe) {
+ LOG.error("Failed to get policy {} under metalake {}", policyName, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
@Override
@@ -128,66 +115,56 @@ public class PolicyManager implements PolicyDispatcher {
throws PolicyAlreadyExistsException {
NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);
checkMetalake(metalakeIdent, entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- LockType.WRITE,
- () -> {
- PolicyEntity policyEntity =
- PolicyEntity.builder()
- .withId(idGenerator.nextId())
- .withName(policyName)
- .withNamespace(NamespaceUtil.ofPolicy(metalake))
- .withComment(comment)
- .withPolicyType(type)
- .withEnabled(enabled)
- .withContent(content)
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .withCreateTime(Instant.now())
- .build())
- .build();
+ PolicyEntity policyEntity =
+ PolicyEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(policyName)
+ .withNamespace(NamespaceUtil.ofPolicy(metalake))
+ .withComment(comment)
+ .withPolicyType(type)
+ .withEnabled(enabled)
+ .withContent(content)
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
- try {
- entityStore.put(policyEntity, false /* overwritten */);
- return policyEntity;
- } catch (EntityAlreadyExistsException e) {
- throw new PolicyAlreadyExistsException(
- "Policy with name %s under metalake %s already exists", policyName, metalake);
- } catch (IOException ioe) {
- LOG.error("Failed to create policy {} under metalake {}", policyName, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ entityStore.put(policyEntity, false /* overwritten */);
+ return policyEntity;
+ } catch (EntityAlreadyExistsException e) {
+ throw new PolicyAlreadyExistsException(
+ "Policy with name %s under metalake %s already exists", policyName, metalake);
+ } catch (IOException ioe) {
+ LOG.error("Failed to create policy {} under metalake {}", policyName, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
@Override
public PolicyEntity alterPolicy(String metalake, String policyName, PolicyChange... changes) {
NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);
checkMetalake(metalakeIdent, entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- LockType.WRITE,
- () -> {
- try {
- return entityStore.update(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- PolicyEntity.class,
- Entity.EntityType.POLICY,
- policyEntity -> updatePolicyEntity(policyEntity, changes));
- } catch (NoSuchEntityException e) {
- throw new NoSuchPolicyException(
- "Policy with name %s under metalake %s does not exist", policyName, metalake);
- } catch (EntityAlreadyExistsException e) {
- throw new RuntimeException(
- String.format(
- "Trying to alter policy %s under metalake %s, but the new name already exists",
- policyName, metalake));
- } catch (IOException ioe) {
- LOG.error("Failed to alter policy {} under metalake {}", policyName, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore.update(
+ NameIdentifierUtil.ofPolicy(metalake, policyName),
+ PolicyEntity.class,
+ Entity.EntityType.POLICY,
+ policyEntity -> updatePolicyEntity(policyEntity, changes));
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchPolicyException(
+ "Policy with name %s under metalake %s does not exist", policyName, metalake);
+ } catch (EntityAlreadyExistsException e) {
+ throw new RuntimeException(
+ String.format(
+ "Trying to alter policy %s under metalake %s, but the new name already exists",
+ policyName, metalake));
+ } catch (IOException ioe) {
+ LOG.error("Failed to alter policy {} under metalake {}", policyName, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
@Override
@@ -204,46 +181,36 @@ public class PolicyManager implements PolicyDispatcher {
public boolean deletePolicy(String metalake, String policyName) {
NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);
checkMetalake(metalakeIdent, entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- LockType.WRITE,
- () -> {
- try {
- return entityStore.delete(
- NameIdentifierUtil.ofPolicy(metalake, policyName), Entity.EntityType.POLICY);
- } catch (IOException ioe) {
- LOG.error("Failed to delete policy {} under metalake {}", policyName, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore.delete(
+ NameIdentifierUtil.ofPolicy(metalake, policyName), Entity.EntityType.POLICY);
+ } catch (IOException ioe) {
+ LOG.error("Failed to delete policy {} under metalake {}", policyName, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
@Override
public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- policyIdentifier,
- LockType.READ,
- () -> {
- getPolicyWithoutLock(metalake, policyName);
- try {
- return entityStore
- .relationOperations()
- .batchListEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_TAG_REL,
- Collections.singletonList(policyIdentifier),
- Entity.EntityType.POLICY)
- .toArray(new RelationalEntity<?>[0]);
- } catch (IOException e) {
- LOG.error(
- "Failed to list tag associations for policy {} under metalake {}",
- policyName,
- metalake,
- e);
- throw new RuntimeException(e);
- }
- });
+ loadPolicyEntity(metalake, policyName);
+ try {
+ return entityStore
+ .relationOperations()
+ .batchListEntitiesByRelation(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ Collections.singletonList(policyIdentifier),
+ Entity.EntityType.POLICY)
+ .toArray(new RelationalEntity<?>[0]);
+ } catch (IOException e) {
+ LOG.error(
+ "Failed to list tag associations for policy {} under metalake {}",
+ policyName,
+ metalake,
+ e);
+ throw new RuntimeException(e);
+ }
}
@Override
@@ -256,7 +223,7 @@ public class PolicyManager implements PolicyDispatcher {
return objectPolicyResolver.resolve(metalake, metadataObject);
}
- private PolicyEntity getPolicyWithoutLock(String metalake, String policyName) {
+ private PolicyEntity loadPolicyEntity(String metalake, String policyName) {
try {
return entityStore.get(
NameIdentifierUtil.ofPolicy(metalake, policyName),
@@ -274,34 +241,29 @@ public class PolicyManager implements PolicyDispatcher {
String metalake, String policyName, boolean expectedEnabledState) {
NameIdentifier metalakeIdent = NameIdentifierUtil.ofMetalake(metalake);
checkMetalake(metalakeIdent, entityStore);
- TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- LockType.WRITE,
- () -> {
- if (policyEnabled(metalake, policyName) == expectedEnabledState) {
- return null;
- }
+ if (policyEnabled(metalake, policyName) == expectedEnabledState) {
+ return;
+ }
- try {
- entityStore.update(
- NameIdentifierUtil.ofPolicy(metalake, policyName),
- PolicyEntity.class,
- Entity.EntityType.POLICY,
- policyEntity -> {
- PolicyEntity.Builder builder = newPolicyBuilder(policyEntity);
- builder.withEnabled(expectedEnabledState);
- return builder.build();
- });
- return null;
- } catch (IOException ioe) {
- LOG.error(
- "Failed to change policy {} enabled state under metalake {}",
- policyName,
- metalake,
- ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ entityStore.update(
+ NameIdentifierUtil.ofPolicy(metalake, policyName),
+ PolicyEntity.class,
+ Entity.EntityType.POLICY,
+ policyEntity -> {
+ PolicyEntity.Builder builder = newPolicyBuilder(policyEntity);
+ builder.withEnabled(expectedEnabledState);
+ return builder.build();
+ });
+ } catch (NoSuchEntityException e) {
+ // The policy was dropped between the state check above and this update.
+ throw new NoSuchPolicyException(
+ e, "Policy with name %s under metalake %s does not exist", policyName, metalake);
+ } catch (IOException ioe) {
+ LOG.error(
+ "Failed to change policy {} enabled state under metalake {}", policyName, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
private PolicyEntity.Builder newPolicyBuilder(PolicyEntity policyEntity) {
diff --git a/core/src/main/java/org/apache/gravitino/stats/StatisticManager.java b/core/src/main/java/org/apache/gravitino/stats/StatisticManager.java
index a01f740ae9..fe71da0276 100644
--- a/core/src/main/java/org/apache/gravitino/stats/StatisticManager.java
+++ b/core/src/main/java/org/apache/gravitino/stats/StatisticManager.java
@@ -141,20 +141,16 @@ public class StatisticManager implements Closeable, StatisticDispatcher {
try {
NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
Entity.EntityType type = StatisticEntity.getStatisticType(metadataObject.type());
- return TreeLockUtils.doWithTreeLock(
- identifier,
- LockType.READ,
- () ->
- store
- .list(Namespace.fromString(identifier.toString()), StatisticEntity.class, type)
- .stream()
- .map(
- entity -> {
- String name = entity.name();
- StatisticValue<?> value = entity.value();
- return new CustomStatistic(name, value, entity.auditInfo());
- })
- .collect(Collectors.toList()));
+ return store
+ .list(Namespace.fromString(identifier.toString()), StatisticEntity.class, type)
+ .stream()
+ .map(
+ entity -> {
+ String name = entity.name();
+ StatisticValue<?> value = entity.value();
+ return new CustomStatistic(name, value, entity.auditInfo());
+ })
+ .collect(Collectors.toList());
} catch (NoSuchEntityException nse) {
LOG.warn(
"Failed to list statistics for metadata object {} in the metalake {}: {}",
@@ -200,14 +196,7 @@ public class StatisticManager implements Closeable, StatisticDispatcher {
.build();
statisticEntities.add(statistic);
}
- TreeLockUtils.doWithTreeLock(
- identifier,
- LockType.WRITE,
- (Executable<Void, IOException>)
- () -> {
- store.batchPut(statisticEntities, true);
- return null;
- });
+ store.batchPut(statisticEntities, true);
} catch (NoSuchEntityException nse) {
LOG.warn(
@@ -236,9 +225,7 @@ public class StatisticManager implements Closeable, StatisticDispatcher {
Pair.of(NameIdentifierUtil.ofStatistic(identifier, statistic), type);
idents.add(pair);
}
- int deleteCount =
- TreeLockUtils.doWithTreeLock(
- identifier, LockType.WRITE, () -> store.batchDelete(idents, true));
+ int deleteCount = store.batchDelete(idents, true);
// If deleteCount is 0, it means that the statistics were not found.
return deleteCount != 0;
} catch (NoSuchEntityException nse) {
@@ -296,6 +283,10 @@ public class StatisticManager implements Closeable, StatisticDispatcher {
List<MetadataObjectStatisticsUpdate> statisticsToUpdate = Lists.newArrayList();
statisticsToUpdate.add(
MetadataObjectStatisticsUpdate.of(metadataObject, partitionStatistics));
+ // Unlike table-level statistics, partition statistics keep the tree lock. A partition
+ // statistic storage is pluggable and need not update atomically: the Lance storage deletes
+ // and then appends in two commits, so two concurrent updates of one table could leave
+ // duplicates.
TreeLockUtils.doWithTreeLock(
identifier,
LockType.WRITE,
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 fcc58faf3b..19db5554f1 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.storage.relational.service;
import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
@@ -40,9 +41,10 @@ import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
-import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.meta.ModelVersionEntity;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
import org.apache.gravitino.storage.relational.po.ModelPO;
@@ -60,6 +62,9 @@ public class ModelVersionMetaService {
private static final Logger LOG = LoggerFactory.getLogger(ModelVersionMetaService.class);
+ /** How many times a model-version read is re-run when the model changes underneath it. */
+ @VisibleForTesting static final int MAX_STABLE_READ_ATTEMPTS = 3;
+
private static final ModelVersionMetaService INSTANCE = new ModelVersionMetaService();
public static ModelVersionMetaService getInstance() {
@@ -75,41 +80,8 @@ public class ModelVersionMetaService {
NamespaceUtil.checkModelVersion(ns);
NameIdentifier modelIdent = NameIdentifier.of(ns.levels());
- // Will throw a NoSuchEntityException if the model does not exist.
- ModelEntity modelEntity = ModelMetaService.getInstance().getModelByIdentifier(modelIdent);
-
- List<ModelVersionPO> modelVersionPOs =
- SessionUtils.getWithoutCommit(
- ModelVersionMetaMapper.class,
- mapper -> mapper.listModelVersionMetasByModelId(modelEntity.id()));
-
- if (modelVersionPOs.isEmpty()) {
- return Collections.emptyList();
- }
-
- // Get the aliases for all the model versions.
- List<ModelVersionAliasRelPO> aliasRelPOs =
- SessionUtils.getWithoutCommit(
- ModelVersionAliasRelMapper.class,
- mapper -> mapper.selectModelVersionAliasRelsByModelId(modelEntity.id()));
- Multimap<Integer, ModelVersionAliasRelPO> aliasRelPOsByModelVersion =
- ArrayListMultimap.create();
- aliasRelPOs.forEach(r -> aliasRelPOsByModelVersion.put(r.getModelVersion(), r));
-
- return ImmutableList.copyOf(
- modelVersionPOs.stream()
- .collect(
- Collectors.groupingBy(
- ModelVersionPO::getModelVersion,
- Collectors.collectingAndThen(
- Collectors.<ModelVersionPO>toList(),
- m -> {
- List<ModelVersionAliasRelPO> versionAliasRelPOs =
- Lists.newArrayList(
- aliasRelPOsByModelVersion.get(m.get(0).getModelVersion()));
- return POConverters.fromModelVersionPO(modelIdent, m, versionAliasRelPOs);
- })))
- .values());
+ return readWithStableModel(
+ modelIdent, modelPO -> listModelVersions(modelIdent, modelPO.getModelId()));
}
@Monitored(
@@ -119,44 +91,8 @@ 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 = ModelMetaService.getInstance().getModelByIdentifier(modelIdent);
-
- boolean isVersionNumber = NumberUtils.isCreatable(ident.name());
-
- List<ModelVersionPO> modelVersionPOs =
- SessionUtils.getWithoutCommit(
- ModelVersionMetaMapper.class,
- mapper -> {
- if (isVersionNumber) {
- return mapper.selectModelVersionMeta(
- modelEntity.id(), Integer.valueOf(ident.name()));
- } else {
- return mapper.selectModelVersionMetaByAlias(modelEntity.id(), ident.name());
- }
- });
-
- if (modelVersionPOs.isEmpty()) {
- throw new NoSuchEntityException(
- NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
- Entity.EntityType.MODEL_VERSION.name().toLowerCase(Locale.ROOT),
- ident.toString());
- }
-
- List<ModelVersionAliasRelPO> aliasRelPOs =
- SessionUtils.getWithoutCommit(
- ModelVersionAliasRelMapper.class,
- mapper -> {
- if (isVersionNumber) {
- return mapper.selectModelVersionAliasRelsByModelIdAndVersion(
- modelEntity.id(), Integer.valueOf(ident.name()));
- } else {
- return mapper.selectModelVersionAliasRelsByModelIdAndAlias(
- modelEntity.id(), ident.name());
- }
- });
-
- return POConverters.fromModelVersionPO(modelIdent, modelVersionPOs, aliasRelPOs);
+ return readWithStableModel(
+ modelIdent, modelPO -> getModelVersion(ident, modelIdent, modelPO.getModelId()));
}
@Monitored(
@@ -438,6 +374,132 @@ public class ModelVersionMetaService {
return !oldAliases.equals(newAliases);
}
+ private List<ModelVersionEntity> listModelVersions(NameIdentifier modelIdent, long modelId) {
+ List<ModelVersionPO> modelVersionPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionMetaMapper.class, mapper -> mapper.listModelVersionMetasByModelId(modelId));
+
+ if (modelVersionPOs.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ // Get the aliases for all the model versions.
+ List<ModelVersionAliasRelPO> aliasRelPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper -> mapper.selectModelVersionAliasRelsByModelId(modelId));
+ Multimap<Integer, ModelVersionAliasRelPO> aliasRelPOsByModelVersion =
+ ArrayListMultimap.create();
+ aliasRelPOs.forEach(r -> aliasRelPOsByModelVersion.put(r.getModelVersion(), r));
+
+ return ImmutableList.copyOf(
+ modelVersionPOs.stream()
+ .collect(
+ Collectors.groupingBy(
+ ModelVersionPO::getModelVersion,
+ Collectors.collectingAndThen(
+ Collectors.<ModelVersionPO>toList(),
+ m -> {
+ List<ModelVersionAliasRelPO> versionAliasRelPOs =
+ Lists.newArrayList(
+ aliasRelPOsByModelVersion.get(m.get(0).getModelVersion()));
+ return POConverters.fromModelVersionPO(modelIdent, m, versionAliasRelPOs);
+ })))
+ .values());
+ }
+
+ private ModelVersionEntity getModelVersion(
+ NameIdentifier ident, NameIdentifier modelIdent, long modelId) {
+ boolean isVersionNumber = NumberUtils.isCreatable(ident.name());
+
+ List<ModelVersionPO> modelVersionPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionMetaMapper.class,
+ mapper -> {
+ if (isVersionNumber) {
+ return mapper.selectModelVersionMeta(modelId, Integer.valueOf(ident.name()));
+ } else {
+ return mapper.selectModelVersionMetaByAlias(modelId, ident.name());
+ }
+ });
+
+ if (modelVersionPOs.isEmpty()) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.MODEL_VERSION.name().toLowerCase(Locale.ROOT),
+ ident.toString());
+ }
+
+ List<ModelVersionAliasRelPO> aliasRelPOs =
+ SessionUtils.getWithoutCommit(
+ ModelVersionAliasRelMapper.class,
+ mapper -> {
+ if (isVersionNumber) {
+ return mapper.selectModelVersionAliasRelsByModelIdAndVersion(
+ modelId, Integer.valueOf(ident.name()));
+ } else {
+ return mapper.selectModelVersionAliasRelsByModelIdAndAlias(modelId, ident.name());
+ }
+ });
+
+ return POConverters.fromModelVersionPO(modelIdent, modelVersionPOs, aliasRelPOs);
+ }
+
+ /**
+ * Runs a read of a model's version and alias rows and returns it only if the model did not change
+ * while the rows were read.
+ *
+ * <p>The version rows and the alias rows are read by separate statements, so a concurrent link,
+ * alter or delete could otherwise be seen half applied, for example with the old URIs and the new
+ * aliases. Every such write advances the model row's {@code current_version} in its own
+ * transaction, so an unchanged version after the read proves the rows belong to one committed
+ * state. A changed version re-runs the read, up to {@link #MAX_STABLE_READ_ATTEMPTS} times.
+ *
+ * <p>{@code current_version} is the model's aggregate concurrency token, so model-level writes
+ * such as a comment or property change through {@code alterModel} also advance it. Those writes
+ * cannot tear the version and alias rows, but they still make a concurrent read retry, and a
+ * model altered on every attempt fails the read with {@link OptimisticLockException}.
+ *
+ * @param modelIdent the identifier of the model whose rows are read
+ * @param read the read to run against the observed model row
+ * @return the result of a read that saw no concurrent model change
+ * @throws NoSuchEntityException if the model does not exist, or was dropped during the read
+ * @throws OptimisticLockException if the model kept changing
+ */
+ @VisibleForTesting
+ <T> T readWithStableModel(NameIdentifier modelIdent, Function<ModelPO, T> read) {
+ for (int attempt = 1; ; attempt++) {
+ // Will throw a NoSuchEntityException if the model does not exist.
+ ModelPO observedModelPO = ModelMetaService.getInstance().getModelPOByIdentifier(modelIdent);
+ T result = read.apply(observedModelPO);
+
+ ModelPO currentModelPO =
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper -> mapper.selectModelMetaByModelId(observedModelPO.getModelId()));
+ if (currentModelPO == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.MODEL.name().toLowerCase(Locale.ROOT),
+ modelIdent.toString());
+ }
+ if (Objects.equals(currentModelPO.getCurrentVersion(), observedModelPO.getCurrentVersion())) {
+ return result;
+ }
+ if (attempt >= MAX_STABLE_READ_ATTEMPTS) {
+ throw ExceptionUtils.concurrentModification(Entity.EntityType.MODEL, modelIdent);
+ }
+ // Re-read immediately: a read through the entity cache holds its cache segment lock here,
+ // so pausing would also stall unrelated entities hashed to the same segment. Spacing the
+ // attempts needs the retry loop lifted above that lock, or a single-statement read that
+ // cannot tear; both are left to #13181, so do not add a sleep inside this loop.
+ LOG.debug(
+ "Model {} changed during attempt {} of a model-version read, reading it again",
+ modelIdent,
+ attempt);
+ }
+ }
+
private boolean isModelVersionUriUpdated(
ModelVersionEntity oldModelVersionEntity, ModelVersionEntity newModelVersionEntity) {
Map<String, String> oldUris = oldModelVersionEntity.uris();
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
index 41d665307d..100c8d7e1f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
@@ -836,13 +836,37 @@ public class TagMetaService {
}
/**
- * Locks every tag taking part in an assignment change and returns the rows as they are now, so
- * the assignment cannot be written against a tag that is being renamed or dropped.
+ * Locks every tag taking part in an assignment change and returns the rows that still carry the
+ * name the caller resolved, so the assignment cannot be written against a tag that is being
+ * renamed or dropped.
*
- * <p>See {@link #lockTags} for how the rows are locked and what counts as a missing tag.
+ * <p>The rows are locked by one statement in tag ID order, like {@link #lockTags}. Unlike that
+ * method, a tag that was dropped or renamed after it was resolved is left out instead of failing
+ * the change: an assignment ignores a tag name that does not exist, and whether that name
+ * disappeared before or after it was resolved must not change the outcome.
*/
- private List<TagPO> lockTagsForAssignment(List<TagPO> observedTagPOs) {
- return new ArrayList<>(lockTags(observedTagPOs).values());
+ @VisibleForTesting
+ static List<TagPO> lockTagsForAssignment(List<TagPO> observedTagPOs) {
+ if (observedTagPOs.isEmpty()) {
+ return new ArrayList<>();
+ }
+ List<Long> tagIds =
+ observedTagPOs.stream().map(TagPO::getTagId).distinct().collect(Collectors.toList());
+ Map<Long, TagPO> lockedById = new LinkedHashMap<>();
+ SessionUtils.getWithoutCommit(
+ TagMetaMapper.class, mapper -> mapper.listTagPOsByTagIdsForUpdate(tagIds))
+ .forEach(tagPO -> lockedById.put(tagPO.getTagId(), tagPO));
+
+ List<TagPO> liveTagPOs = new ArrayList<>();
+ for (TagPO observedTagPO : observedTagPOs) {
+ TagPO current = lockedById.get(observedTagPO.getTagId());
+ if (current != null
+ && Objects.equals(current.getTagName(), observedTagPO.getTagName())
+ && Objects.equals(current.getMetalakeId(), observedTagPO.getMetalakeId())) {
+ liveTagPOs.add(current);
+ }
+ }
+ return liveTagPOs;
}
/**
diff --git a/core/src/main/java/org/apache/gravitino/tag/TagManager.java b/core/src/main/java/org/apache/gravitino/tag/TagManager.java
index 540db3748f..77e6e4b4a9 100644
--- a/core/src/main/java/org/apache/gravitino/tag/TagManager.java
+++ b/core/src/main/java/org/apache/gravitino/tag/TagManager.java
@@ -51,8 +51,6 @@ import org.apache.gravitino.exceptions.PolicyAlreadyAssociatedException;
import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
-import org.apache.gravitino.lock.LockType;
-import org.apache.gravitino.lock.TreeLockUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.TagEntity;
@@ -98,20 +96,15 @@ public class TagManager implements TagDispatcher {
public Tag[] listTagsInfo(String metalake) {
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(NamespaceUtil.ofTag(metalake).levels()),
- LockType.READ,
- () -> {
- try {
- return entityStore
- .list(NamespaceUtil.ofTag(metalake), TagEntity.class, Entity.EntityType.TAG)
- .stream()
- .toArray(Tag[]::new);
- } catch (IOException ioe) {
- LOG.error("Failed to list tags under metalake {}", metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore
+ .list(NamespaceUtil.ofTag(metalake), TagEntity.class, Entity.EntityType.TAG)
+ .stream()
+ .toArray(Tag[]::new);
+ } catch (IOException ioe) {
+ LOG.error("Failed to list tags under metalake {}", metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
public Tag createTag(String metalake, String name, String comment, Map<String, String> properties)
@@ -128,110 +121,90 @@ public class TagManager implements TagDispatcher {
throws TagAlreadyExistsException {
Map<String, String> tagProperties = properties == null ? Collections.emptyMap() : properties;
checkMetalake(NameIdentifier.of(metalake), entityStore);
+ TagEntity tagEntity =
+ TagEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(metalake))
+ .withComment(comment)
+ .withProperties(tagProperties)
+ .withAllowedValues(allowedValuesForStorage(valueConstraint))
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofTag(metalake, name),
- LockType.WRITE,
- () -> {
- TagEntity tagEntity =
- TagEntity.builder()
- .withId(idGenerator.nextId())
- .withName(name)
- .withNamespace(NamespaceUtil.ofTag(metalake))
- .withComment(comment)
- .withProperties(tagProperties)
- .withAllowedValues(allowedValuesForStorage(valueConstraint))
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .withCreateTime(Instant.now())
- .build())
- .build();
-
- try {
- entityStore.put(tagEntity, false /* overwritten */);
- return tagEntity;
- } catch (EntityAlreadyExistsException e) {
- throw new TagAlreadyExistsException(
- "Tag with name %s under metalake %s already exists", name, metalake);
- } catch (IOException ioe) {
- LOG.error("Failed to create tag {} under metalake {}", name, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ entityStore.put(tagEntity, false /* overwritten */);
+ return tagEntity;
+ } catch (EntityAlreadyExistsException e) {
+ throw new TagAlreadyExistsException(
+ "Tag with name %s under metalake %s already exists", name, metalake);
+ } catch (IOException ioe) {
+ LOG.error("Failed to create tag {} under metalake {}", name, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
public Tag getTag(String metalake, String name) throws NoSuchTagException {
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofTag(metalake, name),
- LockType.READ,
- () -> getTagWithoutLock(metalake, name));
+ return loadTagEntity(metalake, name);
}
public Tag alterTag(String metalake, String name, TagChange... changes)
throws NoSuchTagException, IllegalArgumentException {
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofTag(metalake, name),
- LockType.WRITE,
- () -> {
- try {
- return entityStore.update(
- NameIdentifierUtil.ofTag(metalake, name),
- TagEntity.class,
- Entity.EntityType.TAG,
- tagEntity -> updateTagEntity(tagEntity, changes));
- } catch (NoSuchEntityException e) {
- throw new NoSuchTagException(
- "Tag with name %s under metalake %s does not exist", name, metalake);
- } catch (EntityAlreadyExistsException e) {
- String newName =
- Arrays.stream(changes)
- .filter(c -> c instanceof TagChange.RenameTag)
- .map(c -> ((TagChange.RenameTag) c).getNewName())
- .findFirst()
- .orElse(name);
- throw new TagAlreadyExistsException(
- e, "Tag with name %s under metalake %s already exists", newName, metalake);
- } catch (OptimisticLockException ole) {
- // The store now rejects a stale alter with this exception instead of an IOException,
- // and the REST layer maps it to a conflict. Log it here so the operator-facing record
- // still names the tag and the metalake.
- LOG.warn(
- "Failed to alter tag {} under metalake {} because it changed concurrently",
- name,
- metalake,
- ole);
- throw ole;
- } catch (IOException ioe) {
- LOG.error("Failed to alter tag {} under metalake {}", name, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore.update(
+ NameIdentifierUtil.ofTag(metalake, name),
+ TagEntity.class,
+ Entity.EntityType.TAG,
+ tagEntity -> updateTagEntity(tagEntity, changes));
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchTagException(
+ "Tag with name %s under metalake %s does not exist", name, metalake);
+ } catch (EntityAlreadyExistsException e) {
+ String newName =
+ Arrays.stream(changes)
+ .filter(c -> c instanceof TagChange.RenameTag)
+ .map(c -> ((TagChange.RenameTag) c).getNewName())
+ .findFirst()
+ .orElse(name);
+ throw new TagAlreadyExistsException(
+ e, "Tag with name %s under metalake %s already exists", newName, metalake);
+ } catch (OptimisticLockException ole) {
+ // The store now rejects a stale alter with this exception instead of an IOException,
+ // and the REST layer maps it to a conflict. Log it here so the operator-facing record
+ // still names the tag and the metalake.
+ LOG.warn(
+ "Failed to alter tag {} under metalake {} because it changed concurrently",
+ name,
+ metalake,
+ ole);
+ throw ole;
+ } catch (IOException ioe) {
+ LOG.error("Failed to alter tag {} under metalake {}", name, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
public boolean deleteTag(String metalake, String name) {
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- NameIdentifierUtil.ofTag(metalake, name),
- LockType.WRITE,
- () -> {
- try {
- return entityStore.delete(
- NameIdentifierUtil.ofTag(metalake, name), Entity.EntityType.TAG);
- } catch (OptimisticLockException ole) {
- LOG.warn(
- "Failed to delete tag {} under metalake {} because it changed concurrently",
- name,
- metalake,
- ole);
- throw ole;
- } catch (IOException ioe) {
- LOG.error("Failed to delete tag {} under metalake {}", name, metalake, ioe);
- throw new RuntimeException(ioe);
- }
- });
+ try {
+ return entityStore.delete(NameIdentifierUtil.ofTag(metalake, name), Entity.EntityType.TAG);
+ } catch (OptimisticLockException ole) {
+ LOG.warn(
+ "Failed to delete tag {} under metalake {} because it changed concurrently",
+ name,
+ metalake,
+ ole);
+ throw ole;
+ } catch (IOException ioe) {
+ LOG.error("Failed to delete tag {} under metalake {}", name, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
}
public MetadataObject[] listMetadataObjectsForTag(String metalake, String name)
@@ -243,28 +216,20 @@ public class TagManager implements TagDispatcher {
public RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {
NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, name);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- tagIdentifier,
- LockType.READ,
- () -> {
- getTagWithoutLock(metalake, name);
- try {
- return entityStore
- .relationOperations()
- .batchListEntitiesByRelation(
- SupportsRelationOperations.Type.POLICY_TAG_REL,
- Collections.singletonList(tagIdentifier),
- Entity.EntityType.TAG)
- .toArray(new RelationalEntity<?>[0]);
- } catch (IOException e) {
- LOG.error(
- "Failed to list policy associations for tag {} under metalake {}",
- name,
- metalake,
- e);
- throw new RuntimeException(e);
- }
- });
+ loadTagEntity(metalake, name);
+ try {
+ return entityStore
+ .relationOperations()
+ .batchListEntitiesByRelation(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ Collections.singletonList(tagIdentifier),
+ Entity.EntityType.TAG)
+ .toArray(new RelationalEntity<?>[0]);
+ } catch (IOException e) {
+ LOG.error(
+ "Failed to list policy associations for tag {} under metalake {}", name, metalake, e);
+ throw new RuntimeException(e);
+ }
}
@Override
@@ -273,41 +238,32 @@ public class TagManager implements TagDispatcher {
NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, tagName);
NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- TreeLockUtils.doWithTreeLock(
- tagIdentifier,
- LockType.WRITE,
- () -> {
- RelationUpdate update =
- RelationUpdate.of(
- SupportsRelationOperations.Type.POLICY_TAG_REL,
- tagIdentifier,
- Entity.EntityType.TAG,
- new RelationEdgeTarget[] {
- RelationEdgeTarget.of(
- policyIdentifier,
- Entity.EntityType.POLICY,
- PolicyAssociationSelectorSerde.serialize(selector))
- },
- new RelationEdgeTarget[0]);
- try {
- return entityStore.relationOperations().updateEntityRelations(update);
- } catch (EntityAlreadyExistsException e) {
- throw new PolicyAlreadyAssociatedException(
- e,
- "Policy %s is already associated with tag %s under metalake %s",
- policyName,
- tagName,
- metalake);
- } catch (IOException e) {
- LOG.error(
- "Failed to add policy {} for tag {} under metalake {}",
- policyName,
- tagName,
- metalake,
- e);
- throw new RuntimeException(e);
- }
- });
+ RelationUpdate update =
+ RelationUpdate.of(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ tagIdentifier,
+ Entity.EntityType.TAG,
+ new RelationEdgeTarget[] {
+ RelationEdgeTarget.of(
+ policyIdentifier,
+ Entity.EntityType.POLICY,
+ PolicyAssociationSelectorSerde.serialize(selector))
+ },
+ new RelationEdgeTarget[0]);
+ try {
+ entityStore.relationOperations().updateEntityRelations(update);
+ } catch (EntityAlreadyExistsException e) {
+ throw new PolicyAlreadyAssociatedException(
+ e,
+ "Policy %s is already associated with tag %s under metalake %s",
+ policyName,
+ tagName,
+ metalake);
+ } catch (IOException e) {
+ LOG.error(
+ "Failed to add policy {} for tag {} under metalake {}", policyName, tagName, metalake, e);
+ throw new RuntimeException(e);
+ }
}
@Override
@@ -315,32 +271,26 @@ public class TagManager implements TagDispatcher {
NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, tagName);
NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- TreeLockUtils.doWithTreeLock(
- tagIdentifier,
- LockType.WRITE,
- () -> {
- RelationUpdate update =
- RelationUpdate.of(
- SupportsRelationOperations.Type.POLICY_TAG_REL,
- tagIdentifier,
- Entity.EntityType.TAG,
- new RelationEdgeTarget[0],
- new RelationEdgeTarget[] {
- RelationEdgeTarget.of(policyIdentifier, Entity.EntityType.POLICY, null)
- });
- try {
- entityStore.relationOperations().updateEntityRelations(update);
- } catch (IOException e) {
- LOG.error(
- "Failed to remove policy {} from tag {} under metalake {}",
- policyName,
- tagName,
- metalake,
- e);
- throw new RuntimeException(e);
- }
- return null;
- });
+ RelationUpdate update =
+ RelationUpdate.of(
+ SupportsRelationOperations.Type.POLICY_TAG_REL,
+ tagIdentifier,
+ Entity.EntityType.TAG,
+ new RelationEdgeTarget[0],
+ new RelationEdgeTarget[] {
+ RelationEdgeTarget.of(policyIdentifier, Entity.EntityType.POLICY, null)
+ });
+ try {
+ entityStore.relationOperations().updateEntityRelations(update);
+ } catch (IOException e) {
+ LOG.error(
+ "Failed to remove policy {} from tag {} under metalake {}",
+ policyName,
+ tagName,
+ metalake,
+ e);
+ throw new RuntimeException(e);
+ }
}
@Override
@@ -348,33 +298,27 @@ public class TagManager implements TagDispatcher {
String metalake, String name, @Nullable String value) throws NoSuchTagException {
NameIdentifier tagId = NameIdentifierUtil.ofTag(metalake, name);
checkMetalake(NameIdentifier.of(metalake), entityStore);
- return TreeLockUtils.doWithTreeLock(
- tagId,
- LockType.READ,
- () -> {
- try {
- if (!entityStore.exists(tagId, Entity.EntityType.TAG)) {
- throw new NoSuchTagException(
- "Tag with name %s under metalake %s does not exist", name, metalake);
- }
-
- List<GenericEntity> entities =
- entityStore
- .relationOperations()
- .listEntitiesByRelation(
- RelationQuery.of(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- tagId,
- Entity.EntityType.TAG,
- true,
- value));
- return MetadataObjectService.fromGenericEntities(entities)
- .toArray(new MetadataObject[0]);
- } catch (IOException e) {
- LOG.error("Failed to list metadata objects for tag {}", name, e);
- throw new RuntimeException(e);
- }
- });
+ try {
+ if (!entityStore.exists(tagId, Entity.EntityType.TAG)) {
+ throw new NoSuchTagException(
+ "Tag with name %s under metalake %s does not exist", name, metalake);
+ }
+
+ List<GenericEntity> entities =
+ entityStore
+ .relationOperations()
+ .listEntitiesByRelation(
+ RelationQuery.of(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ tagId,
+ Entity.EntityType.TAG,
+ true,
+ value));
+ return MetadataObjectService.fromGenericEntities(entities).toArray(new MetadataObject[0]);
+ } catch (IOException e) {
+ LOG.error("Failed to list metadata objects for tag {}", name, e);
+ throw new RuntimeException(e);
+ }
}
public String[] listTagsForMetadataObject(String metalake, MetadataObject metadataObject)
@@ -391,28 +335,21 @@ public class TagManager implements TagDispatcher {
MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
- return TreeLockUtils.doWithTreeLock(
- entityIdent,
- LockType.READ,
- () -> {
- try {
- checkMetalake(NameIdentifier.of(metalake), entityStore);
- List<TagEntity> tags =
- entityStore
- .relationOperations()
- .listEntitiesByRelation(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- entityIdent,
- entityType);
- return tags.toArray(new Tag[0]);
- } catch (NoSuchEntityException e) {
- throw new NoSuchMetadataObjectException(
- e, "Failed to list tags for metadata object %s due to not found", metadataObject);
- } catch (IOException e) {
- LOG.error("Failed to list tags for metadata object {}", metadataObject, e);
- throw new RuntimeException(e);
- }
- });
+ try {
+ checkMetalake(NameIdentifier.of(metalake), entityStore);
+ List<TagEntity> tags =
+ entityStore
+ .relationOperations()
+ .listEntitiesByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL, entityIdent, entityType);
+ return tags.toArray(new Tag[0]);
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchMetadataObjectException(
+ e, "Failed to list tags for metadata object %s due to not found", metadataObject);
+ } catch (IOException e) {
+ LOG.error("Failed to list tags for metadata object {}", metadataObject, e);
+ throw new RuntimeException(e);
+ }
}
public Tag getTagForMetadataObject(String metalake, MetadataObject metadataObject, String name)
@@ -423,34 +360,29 @@ public class TagManager implements TagDispatcher {
MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
- return TreeLockUtils.doWithTreeLock(
- entityIdent,
- LockType.READ,
- () -> {
- try {
- checkMetalake(NameIdentifier.of(metalake), entityStore);
- return entityStore
- .relationOperations()
- .<TagEntity>getEntityByRelation(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- entityIdent,
- entityType,
- tagIdent);
- } catch (NoSuchEntityException e) {
- // The store reports a missing tag and a missing metadata object with the same
- // exception type, so the message is the only thing that tells them apart.
- if (isMissingEntity(e, Entity.EntityType.TAG, name)) {
- throw new NoSuchTagException(
- e, "Tag %s does not exist for metadata object %s", name, metadataObject);
- } else {
- throw new NoSuchMetadataObjectException(
- e, "Failed to get tag for metadata object %s due to not found", metadataObject);
- }
- } catch (IOException e) {
- LOG.error("Failed to get tag for metadata object {}", metadataObject, e);
- throw new RuntimeException(e);
- }
- });
+ try {
+ checkMetalake(NameIdentifier.of(metalake), entityStore);
+ return entityStore
+ .relationOperations()
+ .<TagEntity>getEntityByRelation(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ entityIdent,
+ entityType,
+ tagIdent);
+ } catch (NoSuchEntityException e) {
+ // The store reports a missing tag and a missing metadata object with the same
+ // exception type, so the message is the only thing that tells them apart.
+ if (isMissingEntity(e, Entity.EntityType.TAG, name)) {
+ throw new NoSuchTagException(
+ e, "Tag %s does not exist for metadata object %s", name, metadataObject);
+ } else {
+ throw new NoSuchMetadataObjectException(
+ e, "Failed to get tag for metadata object %s due to not found", metadataObject);
+ }
+ } catch (IOException e) {
+ LOG.error("Failed to get tag for metadata object {}", metadataObject, e);
+ throw new RuntimeException(e);
+ }
}
public String[] associateTagsForMetadataObject(
@@ -509,56 +441,47 @@ public class TagManager implements TagDispatcher {
TagValue[] tagValuesToAdd = tagsToAddSet.toArray(new TagValue[0]);
TagValue[] tagValuesToRemove = tagsToRemoveSet.toArray(new TagValue[0]);
- return TreeLockUtils.doWithTreeLock(
- entityIdent,
- LockType.READ,
- () ->
- TreeLockUtils.doWithTreeLock(
- NameIdentifier.of(NamespaceUtil.ofTag(metalake).levels()),
- LockType.WRITE,
- () -> {
- try {
- List<TagEntity> tags;
- if (mode == TagAssociationMode.TAG_VALUES) {
- tags =
- entityStore
- .relationOperations()
- .updateEntityRelations(
- RelationUpdate.of(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- entityIdent,
- entityType,
- toRelationEdgeTargets(metalake, tagValuesToAdd),
- toRelationEdgeTargets(metalake, tagValuesToRemove)));
- } else {
- tags =
- entityStore
- .relationOperations()
- .updateEntityRelations(
- SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
- entityIdent,
- entityType,
- toNameIdentifiers(metalake, tagValuesToAdd),
- toNameIdentifiers(metalake, tagValuesToRemove));
- }
- return tags.stream().map(Tag::name).distinct().toArray(String[]::new);
- } catch (NoSuchEntityException e) {
- throw new NoSuchMetadataObjectException(
- e,
- "Failed to associate tags for metadata object %s due to not found",
- metadataObject);
- } catch (EntityAlreadyExistsException e) {
- throw new TagAlreadyAssociatedException(
- e,
- "Failed to associate tags for metadata object due to some tag values %s already "
- + "associated to the metadata object %s",
- Arrays.toString(tagsToAdd),
- metadataObject);
- } catch (IOException e) {
- LOG.error("Failed to associate tags for metadata object {}", metadataObject, e);
- throw new RuntimeException(e);
- }
- }));
+ try {
+ List<TagEntity> tags;
+ if (mode == TagAssociationMode.TAG_VALUES) {
+ tags =
+ entityStore
+ .relationOperations()
+ .updateEntityRelations(
+ RelationUpdate.of(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ entityIdent,
+ entityType,
+ toRelationEdgeTargets(metalake, tagValuesToAdd),
+ toRelationEdgeTargets(metalake, tagValuesToRemove)));
+ } else {
+ tags =
+ entityStore
+ .relationOperations()
+ .updateEntityRelations(
+ SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
+ entityIdent,
+ entityType,
+ toNameIdentifiers(metalake, tagValuesToAdd),
+ toNameIdentifiers(metalake, tagValuesToRemove));
+ }
+ return tags.stream().map(Tag::name).distinct().toArray(String[]::new);
+ } catch (NoSuchEntityException e) {
+ // Tags that do not exist, including ones dropped or renamed while this change ran, are
+ // ignored by the store, so a missing entity here is the metadata object itself.
+ throw new NoSuchMetadataObjectException(
+ e, "Failed to associate tags for metadata object %s due to not found", metadataObject);
+ } catch (EntityAlreadyExistsException e) {
+ throw new TagAlreadyAssociatedException(
+ e,
+ "Failed to associate tags for metadata object due to some tag values %s already "
+ + "associated to the metadata object %s",
+ Arrays.toString(tagsToAdd),
+ metadataObject);
+ } catch (IOException e) {
+ LOG.error("Failed to associate tags for metadata object {}", metadataObject, e);
+ throw new RuntimeException(e);
+ }
}
private static String[] allowedValuesForStorage(TagValueConstraint valueConstraint) {
@@ -671,7 +594,7 @@ public class TagManager implements TagDispatcher {
.build();
}
- private TagEntity getTagWithoutLock(String metalake, String name) {
+ private TagEntity loadTagEntity(String metalake, String name) {
try {
return entityStore.get(
NameIdentifierUtil.ofTag(metalake, name), Entity.EntityType.TAG, TagEntity.class);
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
index 767e13d582..6a3ab5cb9f 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
@@ -44,7 +44,9 @@ import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
+import java.util.Arrays;
import java.util.Collections;
+import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -61,11 +63,13 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.CatalogTestUtils;
+import org.apache.gravitino.catalog.TreeLockTestSupport;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -74,6 +78,7 @@ import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.utils.RaceTestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -110,7 +115,9 @@ public class TestOwnerManager {
Mockito.when(config.get(ENTITY_STORE)).thenReturn(RELATIONAL_ENTITY_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_STORE)).thenReturn(DEFAULT_ENTITY_RELATIONAL_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))
- .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", DB_DIR));
+ .thenReturn(
+ String.format(
+ "jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL;LOCK_TIMEOUT=30000", DB_DIR));
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS)).thenReturn(100);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_IDLE_CONNECTIONS)).thenReturn(10);
@@ -335,4 +342,70 @@ public class TestOwnerManager {
GravitinoEnv.getInstance(), "gravitinoAuthorizer", originalAuthorizer, true);
}
}
+
+ @Test
+ @Order(6)
+ public void testConcurrentSetOwnerKeepsOneOwner() throws Exception {
+ MetadataObject catalogObject = createCatalog("catalog_owner_race");
+
+ for (int i = 0; i < 10; i++) {
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ Arrays.asList(
+ () -> {
+ ownerManager.setOwner(METALAKE, catalogObject, USER, Owner.Type.USER);
+ return null;
+ },
+ () -> {
+ ownerManager.setOwner(METALAKE, catalogObject, GROUP, Owner.Type.GROUP);
+ return null;
+ }));
+
+ outcomes.forEach(Assertions::assertNull);
+ // getOwner fails if more than one live owner row exists for the object.
+ Owner owner = ownerManager.getOwner(METALAKE, catalogObject).get();
+ Assertions.assertTrue(
+ (USER.equals(owner.name()) && owner.type() == Owner.Type.USER)
+ || (GROUP.equals(owner.name()) && owner.type() == Owner.Type.GROUP),
+ "Unexpected owner " + owner.name());
+ }
+ }
+
+ @Test
+ @Order(7)
+ public void testOwnerOperationsDoNotWaitForMetalakeTreeLock() throws Exception {
+ // Use a catalog of its own so the test does not depend on running after another one.
+ MetadataObject catalogObject = createCatalog("catalog_owner_lock_free");
+
+ // A metalake WRITE lock covers every principal and metadata object below it. Owner writes are
+ // fenced by the entity store, so none of them may wait for it.
+ try (TreeLockTestSupport.HeldLock metalakeWriter =
+ TreeLockTestSupport.HeldLock.acquire(NameIdentifier.of(METALAKE), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () -> ownerManager.setOwner(METALAKE, catalogObject, USER, Owner.Type.USER));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () ->
+ ownerManager.setOwners(
+ METALAKE, Collections.singletonList(catalogObject), GROUP, Owner.Type.GROUP));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> ownerManager.getOwner(METALAKE, catalogObject));
+ }
+ }
+
+ private static MetadataObject createCatalog(String catalogName) throws IOException {
+ AuditInfo audit = AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
+ entityStore.put(
+ CatalogEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(catalogName)
+ .withNamespace(Namespace.of(METALAKE))
+ .withType(Catalog.Type.RELATIONAL)
+ .withProvider("test")
+ .withAuditInfo(audit)
+ .build(),
+ false);
+ return MetadataObjects.of(Lists.newArrayList(catalogName), MetadataObject.Type.CATALOG);
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java
index 1cafd5291d..a667164a19 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java
@@ -36,6 +36,7 @@ import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchModelException;
import org.apache.gravitino.exceptions.NoSuchModelVersionException;
import org.apache.gravitino.exceptions.NoSuchModelVersionURINameException;
@@ -1316,42 +1317,71 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {
}
@Test
- public void testRegisterModelWaitsForRegisterModelOfSameName() throws Exception {
+ public void testModelOperationsDoNotWaitForCatalogTreeLock() throws Exception {
NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema_model_lock_2");
createSchemaForLockTest(schemaIdent);
- NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_model_lock_2", "model1");
+ NameIdentifier modelIdent = NameIdentifier.of(metalake, catalog, "schema_model_lock_2", "m1");
- TreeLockTestSupport.HeldLock sameNameCreate =
- TreeLockTestSupport.HeldLock.acquire(ident, LockType.WRITE);
- TreeLockTestSupport.assertWaitsFor(sameNameCreate, () -> registerModelForLockTest(ident));
- }
-
- @Test
- public void testRegisterModelWaitsForSchemaWriteLock() throws Exception {
- NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema_model_lock_3");
- createSchemaForLockTest(schemaIdent);
-
- TreeLockTestSupport.HeldLock schemaWriter =
- TreeLockTestSupport.HeldLock.acquire(schemaIdent, LockType.WRITE);
- TreeLockTestSupport.assertWaitsFor(
- schemaWriter,
- () ->
- registerModelForLockTest(
- NameIdentifier.of(metalake, catalog, "schema_model_lock_3", "model1")));
- }
-
- @Test
- public void testRegisterModelWaitsForCatalogWriteLock() throws Exception {
- NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, "schema_model_lock_4");
- createSchemaForLockTest(schemaIdent);
+ // A catalog WRITE lock covers every schema, model and version below it. Model operations are
+ // fenced by the entity store, so none of them may wait for it.
+ try (TreeLockTestSupport.HeldLock catalogWriter =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(metalake, catalog), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> registerModelForLockTest(modelIdent));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.listModels(
+ Namespace.of(metalake, catalog, "schema_model_lock_2")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.getModel(modelIdent));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.alterModel(
+ modelIdent, ModelChange.updateComment("changed")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.linkModelVersion(
+ modelIdent, ImmutableMap.of("n1", "u1"), new String[] {"a1"}, null, null));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.getModelVersion(modelIdent, "a1"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.getModelVersion(modelIdent, 0));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.listModelVersions(modelIdent));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.listModelVersionInfos(modelIdent));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.getModelVersionUri(modelIdent, 0, "n1"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.getModelVersionUri(modelIdent, "a1", "n1"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.alterModelVersion(
+ modelIdent, 0, ModelVersionChange.updateComment("changed")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.alterModelVersion(
+ modelIdent, "a1", ModelVersionChange.updateComment("changed by alias")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter,
+ () ->
+ modelOperationDispatcher.linkModelVersion(
+ modelIdent, ImmutableMap.of("n2", "u2"), new String[] {"a2"}, null, null));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.deleteModelVersion(modelIdent, "a2"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.deleteModelVersion(modelIdent, 0));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ catalogWriter, () -> modelOperationDispatcher.deleteModel(modelIdent));
+ }
- TreeLockTestSupport.HeldLock catalogWriter =
- TreeLockTestSupport.HeldLock.acquire(NameIdentifier.of(metalake, catalog), LockType.WRITE);
- TreeLockTestSupport.assertWaitsFor(
- catalogWriter,
- () ->
- registerModelForLockTest(
- NameIdentifier.of(metalake, catalog, "schema_model_lock_4", "model1")));
+ Assertions.assertFalse(modelOperationDispatcher.modelExists(modelIdent));
}
private static void createSchemaForLockTest(NameIdentifier schemaIdent) {
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
index af47be63d9..be2451b932 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java
@@ -33,6 +33,7 @@ import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.expressions.literals.Literal;
import org.apache.gravitino.rel.expressions.literals.Literals;
@@ -161,6 +162,50 @@ public class TestPartitionOperationDispatcher extends TestOperationDispatcher {
partitionOperationDispatcher.partitionExists(TABLE_IDENT, testDrop.name()));
}
+ @Test
+ public void testPartitionOperationsDoNotWaitForTableTreeLock() throws Exception {
+ Partition partition =
+ Partitions.identity(
+ "p_lock",
+ new String[][] {{"col1"}},
+ new Literal[] {Literals.stringLiteral("v_lock")},
+ Maps.newHashMap());
+
+ // Partition operations never write the entity store, so they must not contend with an
+ // in-flight table operation that holds the table tree lock.
+ try (TreeLockTestSupport.HeldLock tableWrite =
+ TreeLockTestSupport.HeldLock.acquire(TABLE_IDENT, LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite, () -> partitionOperationDispatcher.addPartition(TABLE_IDENT, partition));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite,
+ () -> partitionOperationDispatcher.getPartition(TABLE_IDENT, partition.name()));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite, () -> partitionOperationDispatcher.listPartitionNames(TABLE_IDENT));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite,
+ () ->
+ Assertions.assertTrue(
+ Arrays.stream(partitionOperationDispatcher.listPartitions(TABLE_IDENT))
+ .anyMatch(p -> p.name().equals(partition.name()))));
+ // The test catalog does not support purge; reaching its exception proves that this entry
+ // point also proceeds while another thread holds the table lock.
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite,
+ () ->
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () ->
+ partitionOperationDispatcher.purgePartition(TABLE_IDENT, partition.name())));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWrite,
+ () -> partitionOperationDispatcher.dropPartition(TABLE_IDENT, partition.name()));
+ }
+
+ Assertions.assertFalse(
+ partitionOperationDispatcher.partitionExists(TABLE_IDENT, partition.name()));
+ }
+
@Test
public void testPurgePartition() {
Assertions.assertThrows(
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TreeLockTestSupport.java b/core/src/test/java/org/apache/gravitino/catalog/TreeLockTestSupport.java
index 160191f838..577d11be74 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TreeLockTestSupport.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TreeLockTestSupport.java
@@ -39,7 +39,7 @@ import org.junit.jupiter.api.Assertions;
* concurrently with it or waits for it. Waiting is detected by observing the operation thread
* parked inside {@link TreeLockNode}, not by sleeping, so the assertions do not depend on timing.
*/
-final class TreeLockTestSupport {
+public final class TreeLockTestSupport {
private static final Duration TIMEOUT = Duration.ofSeconds(30);
@@ -49,7 +49,8 @@ final class TreeLockTestSupport {
* Asserts that {@code operation} completes while {@code held} is still held, i.e. the operation
* does not contend with that lock.
*/
- static void assertRunsConcurrentlyWith(HeldLock held, Runnable operation) throws Exception {
+ public static void assertRunsConcurrentlyWith(HeldLock held, Runnable operation)
+ throws Exception {
OperationRun run = OperationRun.start(operation);
try {
if (run.awaitDoneOrParked() == Outcome.PARKED) {
@@ -67,7 +68,7 @@ final class TreeLockTestSupport {
* Asserts that {@code operation} parks on a tree lock while {@code held} is held and completes
* once the lock is released.
*/
- static void assertWaitsFor(HeldLock held, Runnable operation) throws Exception {
+ public static void assertWaitsFor(HeldLock held, Runnable operation) throws Exception {
OperationRun run = OperationRun.start(operation);
try {
Assertions.assertEquals(
@@ -151,7 +152,7 @@ final class TreeLockTestSupport {
}
/** A tree lock held by a dedicated thread until {@link #release()} or {@link #close()}. */
- static final class HeldLock implements AutoCloseable {
+ public static final class HeldLock implements AutoCloseable {
private final NameIdentifier identifier;
private final LockType lockType;
private final CountDownLatch acquired = new CountDownLatch(1);
@@ -166,10 +167,13 @@ final class TreeLockTestSupport {
}
/** Acquires the lock on a helper thread and returns once it is held. */
- static HeldLock acquire(NameIdentifier identifier, LockType lockType) throws Exception {
+ public static HeldLock acquire(NameIdentifier identifier, LockType lockType) throws Exception {
HeldLock held = new HeldLock(identifier, lockType);
held.holder.start();
- held.acquired.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ if (!held.acquired.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
+ held.release();
+ throw new AssertionError("Timed out acquiring " + held);
+ }
if (held.failure != null) {
throw new AssertionError("Failed to acquire " + held, held.failure);
}
@@ -196,7 +200,7 @@ final class TreeLockTestSupport {
}
/** Releases the lock and waits for the holder thread to exit. */
- void release() throws InterruptedException {
+ public void release() throws InterruptedException {
releaseSignal.countDown();
holder.join(TIMEOUT.toMillis());
}
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
index eae8c12874..e7933b9fa2 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -50,6 +50,7 @@ import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@@ -64,12 +65,15 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.EntityStoreFactory;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.CatalogDispatcher;
import org.apache.gravitino.catalog.FunctionDispatcher;
import org.apache.gravitino.catalog.SchemaDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.catalog.TreeLockTestSupport;
import org.apache.gravitino.catalog.ViewDispatcher;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchPolicyException;
import org.apache.gravitino.exceptions.NotFoundException;
@@ -77,6 +81,7 @@ import org.apache.gravitino.exceptions.PolicyAlreadyExistsException;
import org.apache.gravitino.function.FunctionDefinition;
import org.apache.gravitino.function.FunctionType;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -96,6 +101,7 @@ import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.tag.TagManager;
import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.RaceTestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@@ -242,7 +248,9 @@ public class TestPolicyManager {
Mockito.when(config.get(ENTITY_STORE)).thenReturn(RELATIONAL_ENTITY_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_STORE)).thenReturn(DEFAULT_ENTITY_RELATIONAL_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))
- .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", DB_DIR));
+ .thenReturn(
+ String.format(
+ "jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL;LOCK_TIMEOUT=30000", DB_DIR));
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS)).thenReturn(100);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_IDLE_CONNECTIONS)).thenReturn(10);
@@ -633,6 +641,78 @@ public class TestPolicyManager {
0, policyManager.listPolicyInfosForMetadataObject(METALAKE, tableObject).length);
}
+ @Test
+ public void testPolicyOperationsDoNotWaitForMetalakeTreeLock() throws Exception {
+ String policyName = "policy_" + UUID.randomUUID().toString().replace("-", "");
+ PolicyContent content =
+ PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null);
+
+ // A metalake WRITE lock covers every policy below it. Policy operations are fenced by the
+ // entity store, so none of them may wait for it.
+ try (TreeLockTestSupport.HeldLock metalakeWriter =
+ TreeLockTestSupport.HeldLock.acquire(NameIdentifier.of(METALAKE), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> createCustomPolicy(METALAKE, policyName, content));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> policyManager.getPolicy(METALAKE, policyName));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> policyManager.listPolicyInfos(METALAKE));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> policyManager.disablePolicy(METALAKE, policyName));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () ->
+ policyManager.alterPolicy(
+ METALAKE, policyName, PolicyChange.updateComment("changed")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> policyManager.listTagAssociationsForPolicy(METALAKE, policyName));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> policyManager.deletePolicy(METALAKE, policyName));
+ }
+ }
+
+ @Test
+ public void testChangePolicyEnabledStateReportsPolicyDroppedBeforeUpdate() throws IOException {
+ String policyName = "policy_" + UUID.randomUUID().toString().replace("-", "");
+ createCustomPolicy(
+ METALAKE,
+ policyName,
+ PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null));
+ EntityStore racingStore = Mockito.spy(entityStore);
+ NoSuchEntityException dropped =
+ new NoSuchEntityException("policy %s was dropped concurrently", policyName);
+ // The policy is still enabled when its state is checked, then dropped before the update.
+ Mockito.doThrow(dropped)
+ .when(racingStore)
+ .update(
+ Mockito.eq(NameIdentifierUtil.ofPolicy(METALAKE, policyName)),
+ Mockito.eq(PolicyEntity.class),
+ Mockito.eq(Entity.EntityType.POLICY),
+ Mockito.any());
+ PolicyManager racingManager = new PolicyManager(new RandomIdGenerator(), racingStore);
+
+ NoSuchPolicyException e =
+ Assertions.assertThrows(
+ NoSuchPolicyException.class, () -> racingManager.disablePolicy(METALAKE, policyName));
+ Assertions.assertSame(dropped, e.getCause());
+ }
+
+ @Test
+ public void testConcurrentCreatePolicyHasOneWinner() throws Exception {
+ String policyName = "policy_" + UUID.randomUUID().toString().replace("-", "");
+ PolicyContent content =
+ PolicyContents.custom(ImmutableMap.of("rule", "value"), SUPPORTS_OBJECT_TYPES, null);
+
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(8, () -> createCustomPolicy(METALAKE, policyName, content));
+
+ Assertions.assertEquals(1, outcomes.stream().filter(o -> o instanceof PolicyEntity).count());
+ outcomes.stream()
+ .filter(o -> !(o instanceof PolicyEntity))
+ .forEach(o -> Assertions.assertInstanceOf(PolicyAlreadyExistsException.class, o));
+ Assertions.assertEquals(policyName, policyManager.getPolicy(METALAKE, policyName).name());
+ }
+
private PolicyEntity createCustomPolicy(
String metalakeName, String policyName, PolicyContent policyContent) {
return policyManager.createPolicy(
diff --git a/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java b/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
index 52f931890b..c18104df6e 100644
--- a/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
+++ b/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
@@ -59,9 +59,12 @@ import org.apache.gravitino.EntityStoreFactory;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.TreeLockTestSupport;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -405,6 +408,81 @@ public class TestStatisticManager {
}
}
+ @Test
+ public void testTableStatisticsDoNotWaitForTableTreeLock() throws Exception {
+ StatisticManager statisticManager = new StatisticManager(entityStore, idGenerator, config);
+ MetadataObject tableObject =
+ MetadataObjects.of(Lists.newArrayList(CATALOG, SCHEMA, TABLE), MetadataObject.Type.TABLE);
+ Map<String, StatisticValue<?>> stats = Maps.newHashMap();
+ stats.put("lock_free", StatisticValues.longValue(1L));
+
+ // Table-level statistic writes are fenced on the table row and version-checked by the entity
+ // store, so they must not contend with an in-flight table operation that holds the table tree
+ // lock.
+ try (TreeLockTestSupport.HeldLock tableWriter =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, TABLE), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWriter, () -> statisticManager.updateStatistics(METALAKE, tableObject, stats));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWriter, () -> statisticManager.listStatistics(METALAKE, tableObject));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ tableWriter,
+ () ->
+ statisticManager.dropStatistics(
+ METALAKE, tableObject, Lists.newArrayList("lock_free")));
+ }
+ }
+
+ @Test
+ public void testPartitionStatisticsStillWaitForTableTreeLock() throws Exception {
+ StatisticManager statisticManager = new StatisticManager(entityStore, idGenerator, config);
+ MetadataObject tableObject =
+ MetadataObjects.of(Lists.newArrayList(CATALOG, SCHEMA, TABLE), MetadataObject.Type.TABLE);
+ Map<String, StatisticValue<?>> stats = Maps.newHashMap();
+ stats.put("locked", StatisticValues.longValue(1L));
+ List<PartitionStatisticsUpdate> updates =
+ Lists.newArrayList(PartitionStatisticsModification.update("p_lock", stats));
+
+ // A pluggable partition statistic storage need not update atomically, so this path keeps the
+ // tree lock until the storages do.
+ try (TreeLockTestSupport.HeldLock tableWriter =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, TABLE), LockType.WRITE)) {
+ TreeLockTestSupport.assertWaitsFor(
+ tableWriter,
+ () -> statisticManager.updatePartitionStatistics(METALAKE, tableObject, updates));
+ }
+ try (TreeLockTestSupport.HeldLock tableWriter =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, TABLE), LockType.WRITE)) {
+ TreeLockTestSupport.assertWaitsFor(
+ tableWriter,
+ () ->
+ statisticManager.listPartitionStatistics(
+ METALAKE,
+ tableObject,
+ PartitionRange.between(
+ "p_lock",
+ PartitionRange.BoundType.CLOSED,
+ "p_lock",
+ PartitionRange.BoundType.CLOSED)));
+ }
+ try (TreeLockTestSupport.HeldLock tableWriter =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, TABLE), LockType.WRITE)) {
+ TreeLockTestSupport.assertWaitsFor(
+ tableWriter,
+ () ->
+ statisticManager.dropPartitionStatistics(
+ METALAKE,
+ tableObject,
+ Lists.newArrayList(
+ PartitionStatisticsModification.drop(
+ "p_lock", Lists.newArrayList("locked")))));
+ }
+ }
+
@Test
public void testCustomStatisticWithNullValue() {
AuditInfo audit = AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
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 e67f665dc2..a83f646909 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
@@ -34,6 +34,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -1864,6 +1865,183 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
Assertions.assertFalse(ModelVersionMetaService.getInstance().deleteModelVersion(ident));
}
+ @TestTemplate
+ public void testGetModelVersionByNumberRereadsConcurrentUpdate() throws IOException {
+ assertModelVersionReadRereads(
+ version ->
+ List.of(
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(version.nameIdentifier())));
+ }
+
+ @TestTemplate
+ public void testGetModelVersionByAliasRereadsConcurrentUpdate() throws IOException {
+ assertModelVersionReadRereads(
+ version ->
+ List.of(
+ ModelVersionMetaService.getInstance()
+ .getModelVersionByIdentifier(
+ NameIdentifier.of(version.namespace(), "stable_read_alias"))));
+ }
+
+ @TestTemplate
+ public void testListModelVersionsRereadsConcurrentUpdate() throws IOException {
+ assertModelVersionReadRereads(
+ version ->
+ ModelVersionMetaService.getInstance()
+ .listModelVersionsByNamespace(version.namespace()));
+ }
+
+ @TestTemplate
+ public void testReadWithStableModelRereadsAfterConcurrentVersionChange() throws IOException {
+ ModelVersionEntity version = insertModelWithVersion("stable_read_alias");
+ AtomicInteger reads = new AtomicInteger();
+
+ String result =
+ ModelVersionMetaService.getInstance()
+ .readWithStableModel(
+ version.modelIdentifier(),
+ modelPO -> {
+ if (reads.incrementAndGet() == 1) {
+ // A writer commits between the version-row and alias-row reads of the first
+ // attempt, so that attempt may have combined two states.
+ updateModelVersionUnchecked(
+ version.nameIdentifier(), current -> copyModelVersion(current, "changed"));
+ return "torn";
+ }
+ return "stable";
+ });
+
+ Assertions.assertEquals("stable", result);
+ Assertions.assertEquals(2, reads.get());
+ }
+
+ @TestTemplate
+ public void testReadWithStableModelRereadsAfterConcurrentModelAlter() throws IOException {
+ ModelVersionEntity version = insertModelWithVersion("model_alter_read_alias");
+ AtomicInteger reads = new AtomicInteger();
+
+ String result =
+ ModelVersionMetaService.getInstance()
+ .readWithStableModel(
+ version.modelIdentifier(),
+ modelPO -> {
+ if (reads.incrementAndGet() == 1) {
+ // A comment-only alter cannot tear the version rows, but it advances the
+ // model's aggregate token, so the read is re-run.
+ updateModelUnchecked(version.modelIdentifier(), "altered model comment");
+ return "before alter";
+ }
+ return "after alter";
+ });
+
+ Assertions.assertEquals("after alter", result);
+ Assertions.assertEquals(2, reads.get());
+ }
+
+ @TestTemplate
+ public void testReadWithStableModelGivesUpWhenModelKeepsChanging() throws IOException {
+ ModelVersionEntity version = insertModelWithVersion("busy_read_alias");
+ AtomicInteger reads = new AtomicInteger();
+
+ Assertions.assertThrows(
+ OptimisticLockException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .readWithStableModel(
+ version.modelIdentifier(),
+ modelPO -> {
+ updateModelVersionUnchecked(
+ version.nameIdentifier(),
+ current ->
+ copyModelVersion(current, "change " + reads.incrementAndGet()));
+ return null;
+ }));
+ Assertions.assertEquals(ModelVersionMetaService.MAX_STABLE_READ_ATTEMPTS, reads.get());
+ }
+
+ @TestTemplate
+ public void testReadWithStableModelReportsModelDroppedDuringRead() throws IOException {
+ ModelVersionEntity version = insertModelWithVersion("dropped_read_alias");
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ ModelVersionMetaService.getInstance()
+ .readWithStableModel(
+ version.modelIdentifier(),
+ modelPO -> {
+ Assertions.assertTrue(
+ ModelMetaService.getInstance().deleteModel(version.modelIdentifier()));
+ return null;
+ }));
+ }
+
+ private void assertModelVersionReadRereads(
+ Function<ModelVersionEntity, List<ModelVersionEntity>> read) throws IOException {
+ ModelVersionEntity version = insertModelWithVersion("stable_read_alias");
+ AtomicInteger versionReads = new AtomicInteger();
+ try (MockedStatic<SessionUtils> sessions =
+ Mockito.mockStatic(SessionUtils.class, Mockito.CALLS_REAL_METHODS)) {
+ sessions
+ .when(
+ () ->
+ SessionUtils.getWithoutCommit(
+ Mockito.eq(ModelVersionMetaMapper.class), Mockito.any()))
+ .thenAnswer(
+ invocation -> {
+ Object rows = invocation.callRealMethod();
+ if (versionReads.incrementAndGet() == 1) {
+ // Commit after the first version-row query, before its alias query. Without
+ // the stable-read check the caller would see the old URI and the new alias.
+ updateModelVersionUnchecked(
+ version.nameIdentifier(),
+ current ->
+ ModelVersionEntity.builder()
+ .withModelIdentifier(current.modelIdentifier())
+ .withVersion(current.version())
+ .withUris(ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "new_path"))
+ .withAliases(ImmutableList.of("stable_read_alias", "new_alias"))
+ .withComment(current.comment())
+ .withProperties(current.properties())
+ .withAuditInfo(current.auditInfo())
+ .build());
+ }
+ return rows;
+ });
+
+ List<ModelVersionEntity> result = read.apply(version);
+ Assertions.assertEquals(1, result.size());
+ Assertions.assertEquals("new_path", result.get(0).uris().get(ModelVersion.URI_NAME_UNKNOWN));
+ Assertions.assertTrue(result.get(0).aliases().contains("new_alias"));
+ }
+ }
+
+ private ModelVersionEntity insertModelWithVersion(String alias) 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(alias),
+ "version comment",
+ properties,
+ AUDIT_INFO);
+ ModelVersionMetaService.getInstance().insertModelVersion(version);
+ return version;
+ }
+
private String randomModelName() {
return "model_" + UUID.randomUUID().toString().replace("-", "");
}
@@ -1924,6 +2102,24 @@ public class TestModelVersionMetaService extends TestJDBCBackend {
}
}
+ private void updateModelUnchecked(NameIdentifier modelIdent, String comment) {
+ try {
+ Function<ModelEntity, ModelEntity> updater =
+ current ->
+ createModelEntity(
+ current.id(),
+ current.namespace(),
+ current.name(),
+ comment,
+ current.latestVersion(),
+ current.properties(),
+ current.auditInfo());
+ ModelMetaService.getInstance().updateModel(modelIdent, updater);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
private Throwable runAfterConcurrentModelWrite(
ModelPO modelPO, Runnable winnerMutation, Runnable loserMutation) throws Exception {
CountDownLatch modelLocked = new CountDownLatch(1);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticConcurrentWrites.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticConcurrentWrites.java
new file mode 100644
index 0000000000..facf9e0c21
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticConcurrentWrites.java
@@ -0,0 +1,277 @@
+/*
+ * 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.service;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.StatisticEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TableStatisticEntity;
+import org.apache.gravitino.stats.StatisticValues;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.utils.RaceTestUtils;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+/**
+ * Concurrent table-level statistic writes, which do not take the table tree lock. Every outcome
+ * must be a success or a conflict the caller can retry; a deadlock must never surface as an
+ * internal error, and no statistic may outlive its table.
+ */
+public class TestStatisticConcurrentWrites extends TestJDBCBackend {
+
+ private static final String METALAKE = "metalake_statistic_race";
+ private static final String CATALOG = "catalog_statistic_race";
+ private static final String SCHEMA = "schema_statistic_race";
+ private static final List<String> NAMES = ImmutableList.of("s0", "s1", "s2", "s3", "s4");
+ private static final int ROUNDS = 20;
+
+ private final AuditInfo auditInfo =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ @TestTemplate
+ public void testOverlappingUpsertsInOppositeOrderSucceedOrConflict() throws Exception {
+ raiseDefaultLockTimeout();
+ createParentEntities(METALAKE, CATALOG, SCHEMA, auditInfo);
+ TableEntity table = createTable("table_upsert_race");
+
+ for (int round = 0; round < ROUNDS; round++) {
+ AtomicInteger writer = new AtomicInteger();
+ long base = round * 100L;
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ 8,
+ () -> {
+ int index = writer.getAndIncrement();
+ upsert(table, index % 2 == 0 ? NAMES : Lists.reverse(NAMES), base + index);
+ return null;
+ });
+
+ // The version check lets one writer of a statistic win and reports the others as conflicts.
+ // Locking the rows in name order keeps opposite request orders from deadlocking.
+ Assertions.assertTrue(outcomes.contains(null), "One writer must win: " + outcomes);
+ for (Object outcome : outcomes) {
+ Assertions.assertTrue(
+ outcome == null || outcome instanceof OptimisticLockException,
+ "Unexpected outcome: " + outcome);
+ }
+ Assertions.assertEquals(NAMES, liveNames(table));
+ }
+ }
+
+ @TestTemplate
+ public void testUpsertsRacingStatisticDropsSucceedOrConflict() throws Exception {
+ raiseDefaultLockTimeout();
+ createParentEntities(METALAKE, CATALOG, SCHEMA, auditInfo);
+ TableEntity table = createTable("table_drop_race");
+
+ for (int round = 0; round < ROUNDS; round++) {
+ upsert(table, NAMES, round);
+ AtomicInteger worker = new AtomicInteger();
+ long value = round * 100L;
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ 8,
+ () -> {
+ int index = worker.getAndIncrement();
+ if (index % 2 == 0) {
+ upsert(table, Lists.reverse(NAMES), value + index);
+ return null;
+ }
+ return StatisticMetaService.getInstance()
+ .batchDeleteStatisticPOs(
+ table.nameIdentifier(), Entity.EntityType.TABLE, NAMES);
+ });
+
+ for (Object outcome : outcomes) {
+ Assertions.assertTrue(
+ outcome == null
+ || outcome instanceof Integer
+ || outcome instanceof OptimisticLockException,
+ "Unexpected outcome: " + outcome);
+ }
+ // Each upsert and each drop is all-or-nothing, so a round ends with every name or none.
+ List<String> live = liveNames(table);
+ Assertions.assertTrue(live.isEmpty() || live.equals(NAMES), "Partial batch: " + live);
+ }
+ }
+
+ @TestTemplate
+ public void testUpsertsRacingTableDropLeaveNoStatistics() throws Exception {
+ raiseDefaultLockTimeout();
+ createParentEntities(METALAKE, CATALOG, SCHEMA, auditInfo);
+
+ for (int round = 0; round < ROUNDS; round++) {
+ TableEntity table = createTable("table_cascade_race_" + round);
+ // Insert in reverse name order, so the row ids of the cascade delete and the names of the
+ // upserts order the statistic rows differently.
+ for (String name : Lists.reverse(NAMES)) {
+ upsert(table, ImmutableList.of(name), 0);
+ }
+ AtomicInteger worker = new AtomicInteger();
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ 8,
+ (Callable<Object>)
+ () -> {
+ if (worker.getAndIncrement() == 0) {
+ return TableMetaService.getInstance().deleteTable(table.nameIdentifier());
+ }
+ upsert(table, NAMES, 1);
+ return null;
+ });
+
+ Assertions.assertTrue(
+ outcomes.contains(Boolean.TRUE), "The table drop must win: " + outcomes);
+ for (Object outcome : outcomes) {
+ Assertions.assertTrue(
+ outcome == null
+ || Boolean.TRUE.equals(outcome)
+ || outcome instanceof NoSuchEntityException
+ || outcome instanceof OptimisticLockException,
+ "Unexpected outcome: " + outcome);
+ // The drop and the writers queue on the table row, so a conflict here is a version check
+ // that lost, never a deadlock mapped to a conflict.
+ Assertions.assertFalse(isDeadlock(outcome), "Deadlock between drop and writer: " + outcome);
+ }
+ Assertions.assertEquals(0, countLiveStatistics(table.id()));
+ }
+ }
+
+ private static boolean isDeadlock(Object outcome) {
+ for (Throwable cause = outcome instanceof Throwable ? (Throwable) outcome : null;
+ cause != null;
+ cause = cause.getCause()) {
+ if (cause instanceof SQLException) {
+ SQLException sql = (SQLException) cause;
+ if ("40001".equals(sql.getSQLState())
+ || "40P01".equals(sql.getSQLState())
+ || sql.getErrorCode() == 1213) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private TableEntity createTable(String name) throws Exception {
+ TableEntity table =
+ createTableEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ Namespace.of(METALAKE, CATALOG, SCHEMA),
+ name,
+ auditInfo);
+ backend.insert(table, false);
+ return table;
+ }
+
+ private void upsert(TableEntity table, List<String> names, long value) {
+ List<StatisticEntity> statistics =
+ names.stream()
+ .map(
+ name ->
+ (StatisticEntity)
+ TableStatisticEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withValue(StatisticValues.longValue(value))
+ .withAuditInfo(auditInfo)
+ .build())
+ .collect(Collectors.toList());
+ StatisticMetaService.getInstance()
+ .writeStatisticsWithVersion(statistics, table.nameIdentifier(), Entity.EntityType.TABLE);
+ }
+
+ private List<String> liveNames(TableEntity table) {
+ return StatisticMetaService.getInstance()
+ .listStatisticsByEntity(table.nameIdentifier(), Entity.EntityType.TABLE)
+ .stream()
+ .map(StatisticEntity::name)
+ .sorted()
+ .collect(Collectors.toList());
+ }
+
+ private int countLiveStatistics(long tableId) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Statement statement = session.getConnection().createStatement();
+ ResultSet rs =
+ statement.executeQuery(
+ "SELECT COUNT(*) FROM statistic_meta WHERE metadata_object_id = "
+ + tableId
+ + " AND deleted_at = 0")) {
+ rs.next();
+ return rs.getInt(1);
+ }
+ }
+
+ /**
+ * H2 gives new sessions a short lock timeout, so writers that queue behind each other would fail
+ * on a slow machine. The other backends wait long enough by default. The database default only
+ * reaches sessions opened later, so the sessions already idle in the pool are raised one by one:
+ * they are all borrowed at once, which hands out every idle connection exactly once.
+ */
+ private void raiseDefaultLockTimeout() throws SQLException {
+ if (!"h2".equals(backendType)) {
+ return;
+ }
+ BasicDataSource dataSource =
+ (BasicDataSource)
+ SqlSessionFactoryHelper.getInstance()
+ .getSqlSessionFactory()
+ .getConfiguration()
+ .getEnvironment()
+ .getDataSource();
+ List<Connection> idle = new ArrayList<>();
+ try {
+ for (int i = Math.max(1, dataSource.getNumIdle()); i > 0; i--) {
+ idle.add(dataSource.getConnection());
+ }
+ for (Connection connection : idle) {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("SET DEFAULT_LOCK_TIMEOUT 30000");
+ statement.execute("SET LOCK_TIMEOUT 30000");
+ }
+ }
+ } finally {
+ for (Connection connection : idle) {
+ connection.close();
+ }
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
index 1d79cefa67..7781afbd51 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
@@ -31,6 +31,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
@@ -41,6 +42,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.MetadataObject;
@@ -126,6 +128,45 @@ public class TestTagMetaService extends TestJDBCBackend {
assertEquals(replacement.id(), service.getTagByIdentifier(tag.nameIdentifier()).id());
}
+ /** Verifies an assignment ignores tags dropped or renamed after they were resolved by name. */
+ @TestTemplate
+ public void testAssignmentLockSkipsTagsDroppedOrRenamedAfterResolution() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ TagMetaService service = TagMetaService.getInstance();
+ List<TagPO> observed = new ArrayList<>();
+ for (String name : List.of("kept_tag", "dropped_tag", "renamed_tag")) {
+ TagEntity tag =
+ TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ service.insertTag(tag, false);
+ observed.add(
+ SessionUtils.getWithoutCommit(
+ TagMetaMapper.class, mapper -> mapper.selectTagByTagIdForUpdate(tag.id())));
+ }
+
+ // Both changes commit after the assignment resolved the names but before it locks the rows.
+ assertTrue(service.deleteTag(NameIdentifierUtil.ofTag(METALAKE_NAME, "dropped_tag")));
+ service.updateTag(
+ NameIdentifierUtil.ofTag(METALAKE_NAME, "renamed_tag"),
+ tag ->
+ TagEntity.builder()
+ .withId(tag.id())
+ .withName("renamed_tag_new")
+ .withNamespace(tag.namespace())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+
+ List<TagPO> locked =
+ SessionUtils.doWithCommitAndFetchResult(
+ TagMetaMapper.class, ignored -> TagMetaService.lockTagsForAssignment(observed));
+ assertEquals(
+ List.of("kept_tag"), locked.stream().map(TagPO::getTagName).collect(Collectors.toList()));
+ }
+
/** Verifies first-time overwrites either serialize or report a retryable insert conflict. */
@TestTemplate
public void testConcurrentOverwriteOfMissingTag() throws Exception {
@@ -678,7 +719,7 @@ public class TestTagMetaService extends TestJDBCBackend {
}
@TestTemplate
- public void testTagAssignmentWaitsForConcurrentRenameAndRollsBack() throws Exception {
+ public void testTagAssignmentWaitsForConcurrentRenameAndSkipsRenamedTag() throws Exception {
createAndInsertMakeLake(METALAKE_NAME);
CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog_tag_rename_race");
TagMetaService tagMetaService = TagMetaService.getInstance();
@@ -743,9 +784,9 @@ public class TestTagMetaService extends TestJDBCBackend {
allowRenameCommit.countDown();
Assertions.assertNull(renameResult.get(30, TimeUnit.SECONDS));
- Throwable assignmentFailure = assignmentResult.get(30, TimeUnit.SECONDS);
- Assertions.assertTrue(
- assignmentFailure instanceof NoSuchEntityException, String.valueOf(assignmentFailure));
+ // The assignment waits for the rename, then treats the old name as a missing tag: it is
+ // ignored like a name that never existed, and nothing is written against the renamed tag.
+ Assertions.assertNull(assignmentResult.get(30, TimeUnit.SECONDS));
} finally {
allowRenameCommit.countDown();
executor.shutdownNow();
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
index 31ea975306..13af7fb477 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -49,6 +49,7 @@ import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@@ -65,6 +66,7 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.EntityStoreFactory;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.catalog.CatalogDispatcher;
@@ -72,6 +74,7 @@ import org.apache.gravitino.catalog.FunctionDispatcher;
import org.apache.gravitino.catalog.SchemaDispatcher;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.catalog.TreeLockTestSupport;
import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
@@ -89,6 +92,7 @@ import org.apache.gravitino.function.FunctionParams;
import org.apache.gravitino.function.FunctionType;
import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
import org.apache.gravitino.lock.LockManager;
+import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
@@ -111,6 +115,7 @@ import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.RaceTestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@@ -167,7 +172,9 @@ public class TestTagManager {
Mockito.when(config.get(ENTITY_STORE)).thenReturn(RELATIONAL_ENTITY_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_STORE)).thenReturn(DEFAULT_ENTITY_RELATIONAL_STORE);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))
- .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", DB_DIR));
+ .thenReturn(
+ String.format(
+ "jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL;LOCK_TIMEOUT=30000", DB_DIR));
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS)).thenReturn(100);
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_IDLE_CONNECTIONS)).thenReturn(10);
@@ -1259,6 +1266,114 @@ public class TestTagManager {
}
}
+ @Test
+ public void testTagOperationsDoNotWaitForMetalakeTreeLock() throws Exception {
+ MetadataObject tableObject =
+ NameIdentifierUtil.toMetadataObject(
+ NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
+ String policyName = "lock_free_policy";
+ entityStore.put(
+ PolicyEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(policyName)
+ .withNamespace(Namespace.of(METALAKE))
+ .withPolicyType(Policy.BuiltInType.CUSTOM)
+ .withEnabled(true)
+ .withContent(
+ PolicyContents.custom(
+ ImmutableMap.of("rule", "value"),
+ ImmutableSet.of(MetadataObject.Type.TABLE),
+ null))
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build(),
+ false);
+
+ // A metalake WRITE lock covers every tag, policy and metadata object below it. Tag operations
+ // are fenced by the entity store, so none of them may wait for it.
+ try (TreeLockTestSupport.HeldLock metalakeWriter =
+ TreeLockTestSupport.HeldLock.acquire(NameIdentifier.of(METALAKE), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.createTag(METALAKE, "lock_free_tag", null, null));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.getTag(METALAKE, "lock_free_tag"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.listTagsInfo(METALAKE));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () -> tagManager.alterTag(METALAKE, "lock_free_tag", TagChange.updateComment("changed")));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () ->
+ tagManager.addPolicyForTag(
+ METALAKE, "lock_free_tag", policyName, AllValuesSelector.get()));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.listPolicyAssociationsForTag(METALAKE, "lock_free_tag"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () -> tagManager.removePolicyFromTag(METALAKE, "lock_free_tag", policyName));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () ->
+ tagManager.associateTagsForMetadataObject(
+ METALAKE, tableObject, new String[] {"lock_free_tag"}, null));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.listTagsForMetadataObject(METALAKE, tableObject));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter,
+ () -> tagManager.getTagForMetadataObject(METALAKE, tableObject, "lock_free_tag"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.listMetadataObjectsForTag(METALAKE, "lock_free_tag"));
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ metalakeWriter, () -> tagManager.deleteTag(METALAKE, "lock_free_tag"));
+ } finally {
+ entityStore.delete(
+ NameIdentifierUtil.ofPolicy(METALAKE, policyName), Entity.EntityType.POLICY);
+ }
+ }
+
+ @Test
+ public void testConcurrentCreateTagHasOneWinner() throws Exception {
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(8, () -> tagManager.createTag(METALAKE, "race_tag", null, null));
+
+ Assertions.assertEquals(1, outcomes.stream().filter(o -> o instanceof Tag).count());
+ outcomes.stream()
+ .filter(o -> !(o instanceof Tag))
+ .forEach(o -> Assertions.assertInstanceOf(TagAlreadyExistsException.class, o));
+ Assertions.assertEquals("race_tag", tagManager.getTag(METALAKE, "race_tag").name());
+ }
+
+ @Test
+ public void testConcurrentDeleteTagAndAssociateLeavesNoAssignment() throws Exception {
+ MetadataObject tableObject =
+ NameIdentifierUtil.toMetadataObject(
+ NameIdentifierUtil.ofTable(METALAKE, CATALOG, SCHEMA, TABLE), Entity.EntityType.TABLE);
+
+ for (int i = 0; i < 10; i++) {
+ String tagName = "race_delete_tag_" + i;
+ tagManager.createTag(METALAKE, tagName, null, null);
+
+ List<Object> outcomes =
+ RaceTestUtils.runTogether(
+ Arrays.asList(
+ () -> tagManager.deleteTag(METALAKE, tagName),
+ () ->
+ tagManager.associateTagsForMetadataObject(
+ METALAKE, tableObject, new String[] {tagName}, null)));
+
+ Assertions.assertEquals(Boolean.TRUE, outcomes.get(0));
+ Object associate = outcomes.get(1);
+ // A tag dropped while the association runs is ignored like a tag that never existed, so the
+ // association always succeeds, whichever change commits first.
+ Assertions.assertInstanceOf(String[].class, associate);
+ Assertions.assertThrows(NoSuchTagException.class, () -> tagManager.getTag(METALAKE, tagName));
+ Assertions.assertFalse(
+ Arrays.asList(tagManager.listTagsForMetadataObject(METALAKE, tableObject))
+ .contains(tagName));
+ }
+ }
+
private static Set<String> tagNames(Tag[] tags) {
return Arrays.stream(tags).map(Tag::name).collect(Collectors.toSet());
}
diff --git a/core/src/test/java/org/apache/gravitino/utils/RaceTestUtils.java b/core/src/test/java/org/apache/gravitino/utils/RaceTestUtils.java
new file mode 100644
index 0000000000..8c5335c13c
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/utils/RaceTestUtils.java
@@ -0,0 +1,85 @@
+/*
+ * 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.utils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+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;
+
+/** Runs actions on separate threads that are released together by a barrier. */
+public final class RaceTestUtils {
+
+ private static final long TIMEOUT_SECONDS = 30;
+
+ private RaceTestUtils() {}
+
+ /**
+ * Runs {@code action} on {@code threads} threads at the same time.
+ *
+ * @param threads the number of threads
+ * @param action the action every thread runs
+ * @return each thread's outcome, see {@link #runTogether(List)}
+ * @throws Exception if a thread does not finish in time
+ */
+ public static List<Object> runTogether(int threads, Callable<?> action) throws Exception {
+ return runTogether(Collections.nCopies(threads, action));
+ }
+
+ /**
+ * Runs every action on its own thread, released at the same time by a barrier.
+ *
+ * @param actions the actions to run
+ * @return the outcome of each action in input order: its return value, or the exception it threw
+ * @throws Exception if an action does not finish in time
+ */
+ public static List<Object> runTogether(List<? extends Callable<?>> actions) throws Exception {
+ CyclicBarrier barrier = new CyclicBarrier(actions.size());
+ ExecutorService executor = Executors.newFixedThreadPool(actions.size());
+ try {
+ List<Future<?>> futures = new ArrayList<>();
+ for (Callable<?> action : actions) {
+ futures.add(
+ executor.submit(
+ () -> {
+ barrier.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ return action.call();
+ }));
+ }
+
+ List<Object> outcomes = new ArrayList<>();
+ for (Future<?> future : futures) {
+ try {
+ outcomes.add(future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
+ } catch (ExecutionException e) {
+ outcomes.add(e.getCause());
+ }
+ }
+ return outcomes;
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+}
diff --git a/docs/gravitino-server-config.md b/docs/gravitino-server-config.md
index 44ca811a29..f4cf1fe400 100644
--- a/docs/gravitino-server-config.md
+++ b/docs/gravitino-server-config.md
@@ -348,8 +348,13 @@ in memory, so raise `pollBatchSize` in moderate steps.
#### Tree Lock
-Gravitino serializes conflicting metadata operations with an in-memory tree lock. It is the only
-lock implementation available, and it is per-server.
+Gravitino serializes some conflicting metadata operations with an in-memory tree lock. It is the
+only lock implementation available, and it is per-server. Partition, tag, policy, owner, model and
+table-level statistic operations do not take it. Partition operations delegate consistency to the
+catalog implementation; the other operations rely on the entity store's transaction and concurrency
+controls. Conflicting writes may return HTTP 409, while an idempotent delete may return `false` if
+another delete or rename wins. Partition statistics still take the tree lock, because a partition
+statistic storage need not update atomically.
| Configuration Item | Description | Default Value |
|--------------------------------------|------------------------------------------------------|---------------|
diff --git a/docs/how-to-use-gravitino-client.md b/docs/how-to-use-gravitino-client.md
index 5bb35a4aa3..04bc0f2a6b 100644
--- a/docs/how-to-use-gravitino-client.md
+++ b/docs/how-to-use-gravitino-client.md
@@ -81,8 +81,11 @@ finally:
## Retrying concurrent metadata changes
-If another writer changes metadata during an alter or drop, the server returns HTTP 409
-with error code `1012`. The Java and Python clients raise `OptimisticLockException`.
+If another writer changes metadata during a write, such as an alter, a drop, a statistic update
+or a model-version link, the server may return HTTP 409 with error code `1012`. An idempotent delete may instead return `false` if another delete or
+rename wins. A model-version read may also return this conflict if concurrent changes prevent
+obtaining consistent metadata within the server's bounded read attempts. The Java and Python
+clients raise `OptimisticLockException` for error code `1012`.
Import the exception in Java:
```java
@@ -98,3 +101,4 @@ from gravitino.exceptions.base import OptimisticLockException
Catch this exception, reload the latest metadata, reconsider your intended change, and
retry with a bounded number of attempts. Do not replay a stale update unchanged or
retry every HTTP 409 response, since other conflicts may require a different action.
+For a model-version read conflict, retry the read with a bounded number of attempts.