World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15168] fix(core): Coordinate entity cache with pending writes on standalone mutations (#15169)
MaSai8db817a8c002
diff --git a/core/src/main/java/org/apache/gravitino/cache/CachedEntityIdResolver.java b/core/src/main/java/org/apache/gravitino/cache/CachedEntityIdResolver.javaindex d77c685d40..2de3eaea8f 100644--- a/core/src/main/java/org/apache/gravitino/cache/CachedEntityIdResolver.java+++ b/core/src/main/java/org/apache/gravitino/cache/CachedEntityIdResolver.java@@ -18,6 +18,8 @@*/package org.apache.gravitino.cache;+import java.util.Optional;+import java.util.function.BiPredicate;import org.apache.gravitino.Entity;import org.apache.gravitino.HasIdentifier;import org.apache.gravitino.NameIdentifier;@@ -29,36 +31,72 @@ public class CachedEntityIdResolver implements EntityIdResolver {private final EntityCache entityCache;private final EntityIdResolver underlyingResolver;+ private final BiPredicate<NameIdentifier, Entity.EntityType> allowCacheRead;public CachedEntityIdResolver(EntityCache entityCache, EntityIdResolver underlyingResolver) {+ this(entityCache, underlyingResolver, (ident, type) -> true);+ }++ /**+ * Creates a resolver that consults {@code allowCacheRead} before using a cache hit.+ *+ * @param entityCache The entity cache.+ * @param underlyingResolver Resolver used on a cache miss or when the predicate disallows a cache+ * read.+ * @param allowCacheRead Whether a cache hit may be used for the given key.+ */+ public CachedEntityIdResolver(+ EntityCache entityCache,+ EntityIdResolver underlyingResolver,+ BiPredicate<NameIdentifier, Entity.EntityType> allowCacheRead) {this.entityCache = entityCache;this.underlyingResolver = underlyingResolver;+ this.allowCacheRead = allowCacheRead;}@Overridepublic NamespacedEntityId getEntityIds(NameIdentifier nameIdentifier, Entity.EntityType type) {- return entityCache- .getIfPresent(nameIdentifier, type)- .map(- entity -> {- if (nameIdentifier.hasNamespace()) {- NamespacedEntityId namespaceIds =- getEntityIds(- NameIdentifierUtil.parentNameIdentifier(nameIdentifier, type),- NameIdentifierUtil.parentEntityType(type));- return new NamespacedEntityId(entity.id(), namespaceIds.fullIds());- } else {- return new NamespacedEntityId(entity.id());- }- })+ // All-or-nothing: never stitch a cached leaf id with parents from another resolution. Gate ++ // getIfPresent stay under the key lock (matching RelationalEntityStore#get); JDBC stays+ // outside.+ return tryCachedEntityIds(nameIdentifier, type).orElseGet(() -> underlyingResolver.getEntityIds(nameIdentifier, type));}@Overridepublic Long getEntityId(NameIdentifier nameIdentifier, Entity.EntityType type) {- return entityCache- .getIfPresent(nameIdentifier, type)- .map(HasIdentifier::id)+ // Same all-or-nothing gate as getEntityIds: an ancestor pending/publishing blocks the leaf+ // cache hit so the two entry points stay consistent.+ return tryCachedEntityIds(nameIdentifier, type)+ .map(NamespacedEntityId::entityId).orElseGet(() -> underlyingResolver.getEntityId(nameIdentifier, type));}++ /**+ * Returns a namespaced id only when every ancestor is also resolved from cache. Empty means the+ * caller must use the underlying resolver for the original identifier.+ */+ private Optional<NamespacedEntityId> tryCachedEntityIds(+ NameIdentifier nameIdentifier, Entity.EntityType type) {+ Optional<Long> cachedId =+ entityCache.withCacheLock(+ EntityCacheKey.of(nameIdentifier, type),+ () -> {+ if (!allowCacheRead.test(nameIdentifier, type)) {+ return Optional.empty();+ }+ return entityCache.getIfPresent(nameIdentifier, type).map(HasIdentifier::id);+ });+ if (cachedId.isEmpty()) {+ return Optional.empty();+ }+ if (!nameIdentifier.hasNamespace()) {+ return Optional.of(new NamespacedEntityId(cachedId.get()));+ }+ Optional<NamespacedEntityId> parents =+ tryCachedEntityIds(+ NameIdentifierUtil.parentNameIdentifier(nameIdentifier, type),+ NameIdentifierUtil.parentEntityType(type));+ return parents.map(p -> new NamespacedEntityId(cachedId.get(), p.fullIds()));+ }}diff --git a/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.javaindex d4ba1846c9..d30c894cc5 100644--- a/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java+++ b/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java@@ -341,10 +341,8 @@ public class CaffeineEntityCache extends BaseEntityCache {cacheData.invalidate(key);removeIndexEntryIfAbsent(key);- String identifier = indexText(key.identifier());- invalidateDescendants(identifier + NAME_LEVEL_BOUNDARY);- if (key.entityType() == Entity.EntityType.SCHEMA) {- invalidateDescendants(identifier + HierarchicalSchemaUtil.schemaSeparator());+ for (String prefix : descendantPrefixes(key.identifier(), key.entityType())) {+ invalidateDescendants(prefix);}}@@ -389,6 +387,76 @@ public class CaffeineEntityCache extends BaseEntityCache {return appendEscaped(text, ident.name()).toString();}+ /**+ * Returns the descendant index prefixes used when cascading from {@code ident}.+ *+ * <p>Same prefixes {@link #invalidateHierarchy} uses. Does not include {@code ident} itself.+ *+ * @param ident The ancestor identifier.+ * @param type The ancestor entity type.+ * @return One or two prefixes ending at a name-level or schema-separator boundary.+ */+ public static List<String> descendantPrefixes(NameIdentifier ident, Entity.EntityType type) {+ String identifier = indexText(ident);+ List<String> prefixes = Lists.newArrayListWithCapacity(2);+ prefixes.add(identifier + NAME_LEVEL_BOUNDARY);+ if (type == Entity.EntityType.SCHEMA) {+ prefixes.add(identifier + HierarchicalSchemaUtil.schemaSeparator());+ }+ return prefixes;+ }++ /**+ * Returns whether {@code ident} lies under a hierarchy prefix from {@link #descendantPrefixes}.+ *+ * @param ident The identifier to test.+ * @param prefix A prefix from {@link #descendantPrefixes}.+ * @return {@code true} if {@code ident} is matched by {@code prefix}.+ */+ public static boolean isUnderHierarchyPrefix(NameIdentifier ident, String prefix) {+ return indexText(ident).startsWith(prefix);+ }++ /**+ * Returns the hierarchy prefixes an ancestor may have registered that would match {@code ident}.+ *+ * <p>Each value is a boundary-terminated prefix of {@link #indexText(NameIdentifier)} (name-level+ * {@code .} or the schema separator). Looking these up in a pending-prefix map is O(depth)+ * instead of scanning every active write.+ *+ * @param ident The identifier to test.+ * @return Candidate prefixes, nearest ancestors last; never includes {@code ident} itself.+ */+ public static List<String> ancestorHierarchyPrefixes(NameIdentifier ident) {+ String text = indexText(ident);+ String schemaSeparator = HierarchicalSchemaUtil.schemaSeparator();+ List<String> prefixes = Lists.newArrayList();+ for (int i = 0; i < text.length(); i++) {+ char c = text.charAt(i);+ if (c == INDEX_ESCAPE) {+ // Skip the escaped character so a literal '.' inside a level is not a boundary.+ i++;+ continue;+ }+ if (c == NAME_LEVEL_BOUNDARY.charAt(0)) {+ prefixes.add(text.substring(0, i + 1));+ continue;+ }+ if (schemaSeparator.isEmpty()) {+ continue;+ }+ if (schemaSeparator.length() == 1) {+ if (c == schemaSeparator.charAt(0)) {+ prefixes.add(text.substring(0, i + 1));+ }+ } else if (text.startsWith(schemaSeparator, i)) {+ prefixes.add(text.substring(0, i + schemaSeparator.length()));+ i += schemaSeparator.length() - 1;+ }+ }+ return prefixes;+ }+/*** Appends a level to prefix-index text, prefixing {@code "."} and the escape character with the* escape character.diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.javaindex 3350d6f4c4..13ef64a546 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java@@ -31,7 +31,9 @@ import java.util.Locale;import java.util.Map;import java.util.Optional;import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.function.Consumer;import java.util.function.Function;@@ -57,6 +59,7 @@ import org.apache.gravitino.SupportsTableIdLookup;import org.apache.gravitino.cache.BaseEntityCache;import org.apache.gravitino.cache.CacheFactory;import org.apache.gravitino.cache.CachedEntityIdResolver;+import org.apache.gravitino.cache.CaffeineEntityCache;import org.apache.gravitino.cache.Coherence;import org.apache.gravitino.cache.EntityCache;import org.apache.gravitino.cache.EntityCacheKey;@@ -117,6 +120,11 @@ public class RelationalEntityStore// version check: this counter cannot detect changes made on another node.private final AtomicLong cacheInvalidationEpoch = new AtomicLong();+ // One refcount map for every reason a cache hit must be ignored:+ // {@code w:} exact key and hierarchy prefixes while a write is in flight, {@code p:} exact key+ // while a value is being published and may still be rolled back.+ private final ConcurrentHashMap<String, AtomicInteger> cacheBlocks = new ConcurrentHashMap<>();+// Non-null only for a LOCAL_PER_NODE cache, which needs cross-node invalidation. SHARED and NONE// caches have no per-node copy to invalidate, so no listener is registered.@Nullable private EntityCacheChangeLogListener entityCacheChangeLogListener;@@ -150,7 +158,10 @@ public class RelationalEntityStoreif (config.get(Configs.CACHE_ENABLED)) {this.cache = CacheFactory.getEntityCache(config);EntityIdService.initialize(- new CachedEntityIdResolver(cache, new RelationalEntityStoreIdResolver()));+ new CachedEntityIdResolver(+ cache,+ new RelationalEntityStoreIdResolver(),+ (ident, type) -> !isCacheObservationBlocked(ident, type)));} else {this.cache = new NoOpsCache(config);EntityIdService.initialize(new RelationalEntityStoreIdResolver());@@ -213,7 +224,7 @@ public class RelationalEntityStorenew EntityCacheChangeLogListener.Target() {@Overridepublic void invalidate(NameIdentifier ident, Entity.EntityType type) {- invalidateCache(ident, type);+ invalidateOrClear(ident, type);}@Override@@ -274,26 +285,52 @@ public class RelationalEntityStore@Overridepublic boolean exists(NameIdentifier ident, Entity.EntityType entityType) throws IOException {- boolean existsInCache = cache.contains(ident, entityType);- return existsInCache || backend.exists(ident, entityType);+ // Same-key lock as get/publish so a mid-publication put cannot land between the blocked check+ // and contains.+ boolean cached =+ cache.withCacheLock(+ EntityCacheKey.of(ident, entityType),+ () ->+ !isCacheObservationBlocked(ident, entityType) && cache.contains(ident, entityType));+ return cached || backend.exists(ident, entityType);}@Overridepublic <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException {- long epochBeforeWrite = cacheInvalidationEpoch.get();+ NameIdentifier ident = e.nameIdentifier();+ Entity.EntityType type = e.type();try {- backend.insert(e, overwritten);+ if (overwritten) {+ // Drop the cache and block refill before the overwrite commits. Do not publish {@code e}:+ // the database may keep the identity and version of the row it already had.+ beginPendingWrite(ident, type);+ try {+ backend.insert(e, true);+ } finally {+ endPendingWrite(ident, type);+ }+ } else {+ // Clear any same-key stale row (for example a peer-dropped identity still cached here)+ // before insert, but keep the pre-insert epoch so a concurrent ancestor delete during+ // insert still fences publication.+ beginPendingWrite(ident, type);+ long epochBeforeInsert = cacheInvalidationEpoch.get();+ try {+ backend.insert(e, false);+ } finally {+ // Release without endPendingWrite's post-commit invalidate/epoch bumps so the insert+ // epoch fence below stays meaningful. Exact-key pending is enough to drop the stale row.+ releasePendingWrite(ident, type);+ }+ cacheIfEpochUnchanged(e, epochBeforeInsert);+ if (cacheInvalidationEpoch.get() != epochBeforeInsert) {+ // Publication was fenced; make sure the key stays empty for SHARED peer fills too.+ invalidateOrClear(ident, type);+ }+ }} catch (RuntimeException re) {- throw ExceptionUtils.lockWaitTimeoutAsConflict(re, e.type(), e.nameIdentifier());- }- if (overwritten) {- // An overwrite is resolved by the database, which may keep the identity and version of the- // row it already had. Caching the copy handed in here would publish values the stored row- // does not carry, so the next read is served from the backend instead.- invalidateCache(e.nameIdentifier(), e.type());- } else {- cacheIfEpochUnchanged(e, epochBeforeWrite);+ throw ExceptionUtils.lockWaitTimeoutAsConflict(re, type, ident);}}@@ -301,47 +338,83 @@ public class RelationalEntityStorepublic <E extends Entity & HasIdentifier> E update(NameIdentifier ident, Class<E> type, Entity.EntityType entityType, Function<E, E> updater)throws IOException, NoSuchEntityException, EntityAlreadyExistsException {- E updatedEntity;+ // Populated inside the wrapped updater when it renames; ended in finally. The updater runs+ // inside backend.updateEntity before a backend-owned commit, so the new name is pending+ // before the renamed row is visible to other connections.+ NameIdentifier[] renamedTo = new NameIdentifier[1];+ beginPendingWrite(ident, entityType);try {- updatedEntity = backend.update(ident, entityType, updater);- } catch (RuntimeException re) {- throw ExceptionUtils.lockWaitTimeoutAsConflict(re, entityType, ident);+ try {+ return backend.update(+ ident,+ entityType,+ current -> {+ E updated = updater.apply(current);+ NameIdentifier newIdent = updated.nameIdentifier();+ if (!ident.equals(newIdent)) {+ // Record renamedTo only after begin succeeds so finally does not end a pending+ // write that never started.+ beginPendingWrite(newIdent, entityType);+ renamedTo[0] = newIdent;+ }+ return updated;+ });+ } catch (RuntimeException re) {+ throw ExceptionUtils.lockWaitTimeoutAsConflict(re, entityType, ident);+ }+ } finally {+ // Release rename target even if ending the old name fails (or the reverse).+ try {+ if (renamedTo[0] != null) {+ endPendingWrite(renamedTo[0], entityType);+ }+ } finally {+ endPendingWrite(ident, entityType);+ }}- invalidateCache(ident, entityType);- return updatedEntity;}@Overridepublic <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Entity.EntityType entityType, Class<E> e)throws NoSuchEntityException, IOException {- return cache.withCacheLock(- EntityCacheKey.of(ident, entityType),- () -> {- Optional<E> entityFromCache = cache.getIfPresent(ident, entityType);- if (entityFromCache.isPresent()) {- return entityFromCache.get();- }+ Optional<E> cached =+ cache.withCacheLock(+ EntityCacheKey.of(ident, entityType),+ () ->+ isCacheObservationBlocked(ident, entityType)+ ? Optional.empty()+ : cache.getIfPresent(ident, entityType));+ if (cached.isPresent()) {+ return cached.get();+ }- long epochBeforeRead = cacheInvalidationEpoch.get();- E entity = backend.get(ident, entityType);- // The SPI does not require reentrant locks. Publish under the lock already held here.- publishIfEpochUnchanged(entity, epochBeforeRead);- return entity;- });+ // DB I/O stays outside the cache lock so this thread never holds both.+ long epochBeforeRead = cacheInvalidationEpoch.get();+ E entity = backend.get(ident, entityType);+ cacheIfEpochUnchanged(entity, epochBeforeRead);+ return entity;}@Overridepublic long getTableId(NameIdentifier ident) throws IOException {Entity.EntityType entityType = Entity.EntityType.TABLE;-- return cache.withCacheLock(- EntityCacheKey.of(ident, entityType),- () -> {- Optional<TableEntity> cached = cache.getIfPresent(ident, entityType);- // Do not publish a partial TableEntity or introduce a separate name-to-ID cache.- return cached.isPresent() ? cached.get().id() : backend.getTableId(ident);- });+ Optional<Long> cachedId =+ cache.withCacheLock(+ EntityCacheKey.of(ident, entityType),+ () -> {+ if (isCacheObservationBlocked(ident, entityType)) {+ return Optional.empty();+ }+ Optional<TableEntity> cached = cache.getIfPresent(ident, entityType);+ return cached.map(TableEntity::id);+ });+ // Do not publish a partial TableEntity or introduce a separate name-to-ID cache. JDBC stays+ // outside the segment lock, matching get().+ if (cachedId.isPresent()) {+ return cachedId.get();+ }+ return backend.getTableId(ident);}@Override@@ -352,7 +425,14 @@ public class RelationalEntityStoreidents.stream().filter(ident -> {- Optional<E> entity = cache.getIfPresent(ident, entityType);+ // Per-key lock matches get(): blocked check and getIfPresent are not separable.+ Optional<E> entity =+ cache.withCacheLock(+ EntityCacheKey.of(ident, entityType),+ () ->+ isCacheObservationBlocked(ident, entityType)+ ? Optional.empty()+ : cache.getIfPresent(ident, entityType));entity.ifPresent(allEntities::add);return entity.isEmpty();})@@ -372,15 +452,15 @@ public class RelationalEntityStore@Overridepublic boolean delete(NameIdentifier ident, Entity.EntityType entityType, boolean cascade)throws IOException {+ beginPendingWrite(ident, entityType);try {- boolean deleted = backend.delete(ident, entityType, cascade);- return deleted;+ return backend.delete(ident, entityType, cascade);} catch (NoSuchEntityException e) {return false;} catch (RuntimeException re) {throw ExceptionUtils.lockWaitTimeoutAsConflict(re, entityType, ident);} finally {- invalidateCache(ident, entityType);+ endPendingWrite(ident, entityType);}}@@ -391,12 +471,13 @@ public class RelationalEntityStoreClass<E> clazz,Consumer<E> postDeleteAction)throws IOException {+ beginPendingWrite(ident, entityType);try {return backend.deleteAndGet(ident, entityType, clazz, postDeleteAction);} catch (RuntimeException re) {throw ExceptionUtils.lockWaitTimeoutAsConflict(re, entityType, ident);} finally {- invalidateCache(ident, entityType);+ endPendingWrite(ident, entityType);}}@@ -404,12 +485,13 @@ public class RelationalEntityStorepublic Optional<SchemaEntity> deleteSchemaAndGet(NameIdentifier ident, boolean cascadeFunctions, Consumer<SchemaEntity> postDeleteAction)throws IOException {+ beginPendingWrite(ident, Entity.EntityType.SCHEMA);try {return backend.deleteSchemaAndGet(ident, cascadeFunctions, postDeleteAction);} catch (RuntimeException re) {throw ExceptionUtils.lockWaitTimeoutAsConflict(re, Entity.EntityType.SCHEMA, ident);} finally {- invalidateCache(ident, Entity.EntityType.SCHEMA);+ endPendingWrite(ident, Entity.EntityType.SCHEMA);}}@@ -858,24 +940,31 @@ public class RelationalEntityStorecache.put(entity);return;}- cache.withCacheLock(- EntityCacheKey.of(entity.nameIdentifier(), entity.type()),- () -> publishIfEpochUnchanged(entity, epoch));- }-- // The caller holds the entry's cache lock; do not acquire it again here.- private <E extends Entity & HasIdentifier> void publishIfEpochUnchanged(E entity, long epoch) {- if (cache instanceof BaseEntityCache && !BaseEntityCache.isCacheable(entity.type())) {- cache.put(entity);+ NameIdentifier ident = entity.nameIdentifier();+ Entity.EntityType type = entity.type();+ if (isPendingWrite(ident, type) || cacheInvalidationEpoch.get() != epoch) {return;}- if (cacheInvalidationEpoch.get() == epoch) {- cache.put(entity);- // The key lock excludes same-key invalidation, but an ancestor can advance the epoch- // while put runs on another segment. Remove a raced publication before releasing it.- if (cacheInvalidationEpoch.get() != epoch) {- cache.invalidate(entity.nameIdentifier(), entity.type());+ // Hide the entry until publish finishes. Rollback invalidate runs outside the segment lock:+ // the SPI does not require that lock to be reentrant.+ String publishKey = "p\0" + type.name() + "\0" + ident;+ bumpBlock(publishKey);+ try {+ boolean[] published = new boolean[1];+ cache.withCacheLock(+ EntityCacheKey.of(ident, type),+ () -> {+ if (isPendingWrite(ident, type) || cacheInvalidationEpoch.get() != epoch) {+ return;+ }+ cache.put(entity);+ published[0] = true;+ });+ if (published[0] && (isPendingWrite(ident, type) || cacheInvalidationEpoch.get() != epoch)) {+ invalidateOrClear(ident, type);}+ } finally {+ dropBlock(publishKey);}}@@ -886,8 +975,117 @@ public class RelationalEntityStorecache.invalidate(ident, type);}+ /** Drops {@code ident}. If that fails, clears the whole cache so no stale entry remains. */+ private void invalidateOrClear(NameIdentifier ident, Entity.EntityType type) {+ try {+ invalidateCache(ident, type);+ } catch (RuntimeException | Error e) {+ try {+ cache.clear();+ } catch (RuntimeException | Error clearFailure) {+ e.addSuppressed(clearFailure);+ }+ throw e;+ }+ }++ /**+ * Marks {@code ident} and its hierarchy prefixes pending, then invalidates. Register pending+ * before dropping the cache so a concurrent descendant read sees the block before it can+ * republish.+ *+ * <p>Does not hold the cache key lock across {@link EntityCache#invalidate}: the SPI does not+ * require {@code invalidate} to reenter that lock, and Caffeine acquires it internally.+ */+ private void beginPendingWrite(NameIdentifier ident, Entity.EntityType entityType) {+ retainPendingWrite(ident, entityType);+ try {+ invalidateOrClear(ident, entityType);+ } catch (RuntimeException | Error e) {+ // Roll the block back so a failed begin cannot leak it (rename records the new name only+ // after begin returns). invalidateOrClear already emptied the cache if the drop failed.+ releasePendingWrite(ident, entityType);+ throw e;+ }+ }++ /**+ * Invalidates while the write block is still held, then releases it. {@link #invalidateOrClear}+ * clears the whole cache if the targeted drop fails, so readers neither observe a stale entry nor+ * keep a leaked block. The epoch advances before the block is released.+ */+ private void endPendingWrite(NameIdentifier ident, Entity.EntityType entityType) {+ try {+ invalidateOrClear(ident, entityType);+ } finally {+ releasePendingWrite(ident, entityType);+ }+ }++ private void retainPendingWrite(NameIdentifier ident, Entity.EntityType entityType) {+ bumpBlock("w\0" + entityType.name() + "\0" + ident);+ for (String prefix : CaffeineEntityCache.descendantPrefixes(ident, entityType)) {+ bumpBlock("h\0" + prefix);+ }+ }++ private void releasePendingWrite(NameIdentifier ident, Entity.EntityType entityType) {+ dropBlock("w\0" + entityType.name() + "\0" + ident);+ for (String prefix : CaffeineEntityCache.descendantPrefixes(ident, entityType)) {+ dropBlock("h\0" + prefix);+ }+ }++ private void bumpBlock(String key) {+ cacheBlocks.compute(+ key,+ (ignored, count) -> {+ if (count == null) {+ return new AtomicInteger(1);+ }+ count.incrementAndGet();+ return count;+ });+ }++ private void dropBlock(String key) {+ cacheBlocks.compute(+ key,+ (ignored, count) -> {+ if (count == null) {+ return null;+ }+ return count.decrementAndGet() == 0 ? null : count;+ });+ }++ private boolean isPendingWrite(NameIdentifier ident, Entity.EntityType entityType) {+ AtomicInteger exact = cacheBlocks.get("w\0" + entityType.name() + "\0" + ident);+ if (exact != null && exact.get() > 0) {+ return true;+ }+ for (String prefix : CaffeineEntityCache.ancestorHierarchyPrefixes(ident)) {+ AtomicInteger count = cacheBlocks.get("h\0" + prefix);+ if (count != null && count.get() > 0) {+ return true;+ }+ }+ return false;+ }++ /**+ * Returns whether cache hits must be ignored: an in-flight write (this key or an ancestor) or a+ * publication that may still be rolled back.+ */+ private boolean isCacheObservationBlocked(NameIdentifier ident, Entity.EntityType entityType) {+ AtomicInteger publishing = cacheBlocks.get("p\0" + entityType.name() + "\0" + ident);+ return isPendingWrite(ident, entityType) || (publishing != null && publishing.get() > 0);+ }+@VisibleForTestingvoid clearCache() {+ // Advance the epoch and drop cache entries only. In-flight writers own their blocks and must+ // release them; clearing the map would let readers refill while a write is still committing.cacheInvalidationEpoch.incrementAndGet();cache.clear();}diff --git a/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java b/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.javaindex 4890c5bc16..687375da36 100644--- a/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java+++ b/core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCacheInvalidation.java@@ -410,4 +410,55 @@ public class TestCaffeineEntityCacheInvalidation {Assertions.assertEquals(0, cache.size());Assertions.assertFalse(cache.contains(catalog.nameIdentifier(), Entity.EntityType.CATALOG));}++ @Test+ void testDescendantPrefixesUseNameLevelBoundary() {+ NameIdentifier catalog1 = NameIdentifier.of("metalake", "catalog1");+ java.util.List<String> prefixes =+ CaffeineEntityCache.descendantPrefixes(catalog1, Entity.EntityType.CATALOG);++ Assertions.assertEquals(1, prefixes.size());+ Assertions.assertTrue(+ CaffeineEntityCache.isUnderHierarchyPrefix(+ NameIdentifier.of("metalake", "catalog1", "schema"), prefixes.get(0)));+ Assertions.assertFalse(+ CaffeineEntityCache.isUnderHierarchyPrefix(+ NameIdentifier.of("metalake", "catalog10"), prefixes.get(0)));+ Assertions.assertFalse(+ CaffeineEntityCache.isUnderHierarchyPrefix(+ NameIdentifier.of("metalake", "catalog1"), prefixes.get(0)));+ }++ @Test+ void testSchemaAddsHierarchicalSeparatorPrefix() {+ NameIdentifier schema = NameIdentifier.of("metalake", "catalog", "schema");+ java.util.List<String> prefixes =+ CaffeineEntityCache.descendantPrefixes(schema, Entity.EntityType.SCHEMA);++ Assertions.assertEquals(2, prefixes.size());+ Assertions.assertTrue(prefixes.get(0).endsWith("."));+ Assertions.assertTrue(prefixes.get(1).endsWith(HierarchicalSchemaUtil.schemaSeparator()));+ Assertions.assertTrue(+ CaffeineEntityCache.isUnderHierarchyPrefix(+ NameIdentifier.of("metalake", "catalog", "schema", "table"), prefixes.get(0)));+ }++ @Test+ void testAncestorHierarchyPrefixesCoverDescendantRegistrations() {+ NameIdentifier catalog = NameIdentifier.of("metalake", "catalog");+ NameIdentifier schema = NameIdentifier.of("metalake", "catalog", "schema");+ NameIdentifier table = NameIdentifier.of("metalake", "catalog", "schema", "table");+ java.util.List<String> ancestors = CaffeineEntityCache.ancestorHierarchyPrefixes(table);++ Assertions.assertTrue(+ ancestors.containsAll(+ CaffeineEntityCache.descendantPrefixes(catalog, Entity.EntityType.CATALOG)));+ Assertions.assertTrue(+ ancestors.contains(+ CaffeineEntityCache.descendantPrefixes(schema, Entity.EntityType.SCHEMA).get(0)));+ Assertions.assertFalse(+ ancestors.containsAll(+ CaffeineEntityCache.descendantPrefixes(+ NameIdentifier.of("metalake", "catalog10"), Entity.EntityType.CATALOG)));+ }}diff --git a/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java b/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.javaindex d4b1d96a47..153d570c1c 100644--- a/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java+++ b/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java@@ -46,7 +46,7 @@ import org.mockito.Mockito;/** Deterministic regression probes for cache invalidation races. */public class TestEntityCachePublicationRace {@Test- void testPointReadDoesNotReacquireSpiLockForPublication() throws Exception {+ void testPointReadUsesSeparateSpiLocksForLookupAndPublication() throws Exception {NonReentrantCache cache = new NonReentrantCache();RelationalEntityStore store = new RelationalEntityStore();RelationalBackend backend = Mockito.mock(RelationalBackend.class);@@ -56,7 +56,9 @@ public class TestEntityCachePublicationRace {Mockito.when(backend.get(entity.nameIdentifier(), EntityType.TABLE)).thenReturn(entity);Assertions.assertSame(entity, store.get(entity.nameIdentifier(), EntityType.TABLE, TableEntity.class));- Assertions.assertEquals(1, cache.acquisitions);+ // Cold get looks up under the key lock, drops it for JDBC, then acquires again to publish.+ // The two acquisitions must be sequential (NonReentrantCache rejects nested reentry).+ Assertions.assertEquals(2, cache.acquisitions);Mockito.verify(backend).get(entity.nameIdentifier(), EntityType.TABLE);}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.javaindex cbfc483136..2713358c87 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java@@ -24,7 +24,11 @@ import static org.mockito.ArgumentMatchers.eq;import java.io.IOException;import java.time.Instant;import java.util.List;+import java.util.Map;import java.util.Optional;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicLong;import java.util.function.Consumer;import java.util.function.Function;import org.apache.commons.lang3.reflect.FieldUtils;@@ -39,16 +43,21 @@ import org.apache.gravitino.RelationUpdate;import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;import org.apache.gravitino.SupportsRelationOperations;import org.apache.gravitino.cache.BaseEntityCache;+import org.apache.gravitino.cache.CachedEntityIdResolver;import org.apache.gravitino.cache.CaffeineEntityCache;import org.apache.gravitino.cache.Coherence;import org.apache.gravitino.cache.EntityCache;+import org.apache.gravitino.cache.EntityCacheKey;import org.apache.gravitino.cache.NoOpsCache;import org.apache.gravitino.domain.Domain;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.TagAlreadyExistsException;import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.DomainEntity;+import org.apache.gravitino.meta.EntityIdResolver;import org.apache.gravitino.meta.ModelEntity;+import org.apache.gravitino.meta.NamespacedEntityId;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.TopicEntity;@@ -79,12 +88,25 @@ public class TestRelationalEntityStore {FieldUtils.writeField(store, "cache", Mockito.spy(new NoOpsCache(config)), true);}+ @SuppressWarnings("unchecked")+ private Map<String, AtomicInteger> cacheBlocks() throws IllegalAccessException {+ return (Map<String, AtomicInteger>) FieldUtils.readField(store, "cacheBlocks", true);+ }++ private boolean writeBlocked(NameIdentifier ident, Entity.EntityType type)+ throws IllegalAccessException {+ AtomicInteger count = cacheBlocks().get("w\0" + type.name() + "\0" + ident);+ return count != null && count.get() > 0;+ }+@Testvoid testUncachedInsertStillInvokesRelatedInvalidationAfterEpochChanges() throws Exception {BaseEntityCache cache = Mockito.mock(BaseEntityCache.class);FieldUtils.writeField(store, "cache", cache, true);+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "model");ModelEntity entity = Mockito.mock(ModelEntity.class);Mockito.when(entity.type()).thenReturn(Entity.EntityType.MODEL);+ Mockito.when(entity.nameIdentifier()).thenReturn(ident);Mockito.doAnswer(invocation -> {store.clearCache();@@ -93,7 +115,9 @@ public class TestRelationalEntityStore {.when(backend).insert(entity, false);store.put(entity, false);- Mockito.verify(cache).put(entity);+ // Epoch advanced during insert, so publication is fenced; related invalidation still ran via+ // beginPendingWrite / the final invalidateCache path.+ Mockito.verify(cache, Mockito.atLeastOnce()).invalidate(ident, Entity.EntityType.MODEL);}@Test@@ -171,39 +195,328 @@ public class TestRelationalEntityStore {}@Test- void testUpdateInvalidatesCacheAfterBackendUpdate()+ void testUpdateDropsCacheBeforeBackendUpdate()throws IOException, NoSuchEntityException, EntityAlreadyExistsException,IllegalAccessException {NameIdentifier ident = NameIdentifier.of("metalake", "catalog");NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicBoolean invalidatedBeforeBackend = new AtomicBoolean(false);+ AtomicBoolean pendingDuringBackend = new AtomicBoolean(false);++ CatalogEntity updated = Mockito.mock(CatalogEntity.class);+ Mockito.when(updated.nameIdentifier()).thenReturn(ident);Mockito.doAnswer(invocation -> {- Mockito.verify(cache, Mockito.never()).invalidate(ident, Entity.EntityType.CATALOG);- return null;+ Mockito.verify(cache).invalidate(ident, Entity.EntityType.CATALOG);+ invalidatedBeforeBackend.set(true);+ pendingDuringBackend.set(writeBlocked(ident, Entity.EntityType.CATALOG));+ @SuppressWarnings("unchecked")+ Function<CatalogEntity, CatalogEntity> updater = invocation.getArgument(2);+ return updater.apply(updated);}).when(backend).update(eq(ident), eq(Entity.EntityType.CATALOG), any(Function.class));store.update(ident, null, Entity.EntityType.CATALOG, entity -> entity);- InOrder inOrder = Mockito.inOrder(backend, cache);- inOrder.verify(backend).update(eq(ident), eq(Entity.EntityType.CATALOG), any(Function.class));- inOrder.verify(cache).invalidate(ident, Entity.EntityType.CATALOG);+ Assertions.assertTrue(invalidatedBeforeBackend.get());+ Assertions.assertTrue(pendingDuringBackend.get());+ Assertions.assertFalse(writeBlocked(ident, Entity.EntityType.CATALOG));}@Test- void testOverwriteInvalidatesCacheAfterBackendInsert()+ void testRenamePendingBlocksNewIdentBeforeCommit()+ throws IOException, NoSuchEntityException, EntityAlreadyExistsException,+ IllegalAccessException {+ NameIdentifier oldIdent = NameIdentifier.of("metalake", "catalog", "schema", "old");+ NameIdentifier newIdent = NameIdentifier.of("metalake", "catalog", "schema", "new");+ TopicEntity renamed = Mockito.mock(TopicEntity.class);+ Mockito.when(renamed.nameIdentifier()).thenReturn(newIdent);+ Mockito.when(renamed.type()).thenReturn(Entity.EntityType.TOPIC);++ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicBoolean newPendingBeforeReturn = new AtomicBoolean(false);+ AtomicBoolean newInvalidatedBeforeReturn = new AtomicBoolean(false);++ Mockito.doAnswer(+ invocation -> {+ @SuppressWarnings("unchecked")+ Function<TopicEntity, TopicEntity> updater = invocation.getArgument(2);+ TopicEntity result = updater.apply(renamed);+ newPendingBeforeReturn.set(writeBlocked(newIdent, Entity.EntityType.TOPIC));+ Mockito.verify(cache).invalidate(newIdent, Entity.EntityType.TOPIC);+ newInvalidatedBeforeReturn.set(true);+ return result;+ })+ .when(backend)+ .update(eq(oldIdent), eq(Entity.EntityType.TOPIC), any(Function.class));++ Assertions.assertSame(+ renamed, store.update(oldIdent, null, Entity.EntityType.TOPIC, entity -> renamed));++ Assertions.assertTrue(newPendingBeforeReturn.get());+ Assertions.assertTrue(newInvalidatedBeforeReturn.get());+ Assertions.assertFalse(writeBlocked(newIdent, Entity.EntityType.TOPIC));+ Assertions.assertFalse(writeBlocked(oldIdent, Entity.EntityType.TOPIC));+ }++ @Test+ void testRenameBeginPendingRollsBackWhenInvalidateFails()+ throws IOException, NoSuchEntityException, EntityAlreadyExistsException,+ IllegalAccessException {+ NameIdentifier oldIdent = NameIdentifier.of("metalake", "catalog", "schema", "old");+ NameIdentifier newIdent = NameIdentifier.of("metalake", "catalog", "schema", "new");+ TopicEntity renamed = Mockito.mock(TopicEntity.class);+ Mockito.when(renamed.nameIdentifier()).thenReturn(newIdent);++ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);++ Mockito.doReturn(true).when(cache).invalidate(eq(oldIdent), eq(Entity.EntityType.TOPIC));+ Mockito.doThrow(new RuntimeException("invalidate failed"))+ .when(cache)+ .invalidate(eq(newIdent), eq(Entity.EntityType.TOPIC));++ Mockito.doAnswer(+ invocation -> {+ @SuppressWarnings("unchecked")+ Function<TopicEntity, TopicEntity> updater = invocation.getArgument(2);+ return updater.apply(renamed);+ })+ .when(backend)+ .update(eq(oldIdent), eq(Entity.EntityType.TOPIC), any(Function.class));++ Assertions.assertThrows(+ RuntimeException.class,+ () -> store.update(oldIdent, null, Entity.EntityType.TOPIC, entity -> renamed));++ Assertions.assertFalse(writeBlocked(newIdent, Entity.EntityType.TOPIC));+ Assertions.assertFalse(writeBlocked(oldIdent, Entity.EntityType.TOPIC));+ Assertions.assertTrue(cacheBlocks().isEmpty());+ }++ @Test+ void testClearCacheKeepsPendingRegistrations() throws Exception {+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog");+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", ident, Entity.EntityType.CATALOG);++ store.clearCache();++ Assertions.assertTrue(writeBlocked(ident, Entity.EntityType.CATALOG));+ Assertions.assertFalse(cacheBlocks().isEmpty());+ }++ @Test+ void testExistsAndBatchGetSkipCacheWhilePublishing() throws Exception {+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "topic");+ TopicEntity cached = Mockito.mock(TopicEntity.class);+ Mockito.when(cached.nameIdentifier()).thenReturn(ident);+ Mockito.when(cached.type()).thenReturn(Entity.EntityType.TOPIC);++ EntityCache cache = Mockito.mock(EntityCache.class);+ FieldUtils.writeField(store, "cache", cache, true);+ Mockito.when(cache.contains(ident, Entity.EntityType.TOPIC)).thenReturn(true);+ Mockito.when(cache.getIfPresent(ident, Entity.EntityType.TOPIC))+ .thenReturn(Optional.of(cached));+ Mockito.when(+ cache.withCacheLock(any(EntityCacheKey.class), any(EntityCache.ThrowingSupplier.class)))+ .thenAnswer(+ invocation -> {+ @SuppressWarnings("unchecked")+ EntityCache.ThrowingSupplier<?, Exception> action = invocation.getArgument(1);+ return action.get();+ });+ Mockito.when(backend.exists(ident, Entity.EntityType.TOPIC)).thenReturn(false);+ Mockito.when(backend.batchGet(List.of(ident), Entity.EntityType.TOPIC)).thenReturn(List.of());++ cacheBlocks().put("p\0" + Entity.EntityType.TOPIC.name() + "\0" + ident, new AtomicInteger(1));++ Assertions.assertFalse(store.exists(ident, Entity.EntityType.TOPIC));+ Assertions.assertTrue(+ store.batchGet(List.of(ident), Entity.EntityType.TOPIC, TopicEntity.class).isEmpty());+ Mockito.verify(backend).exists(ident, Entity.EntityType.TOPIC);+ Mockito.verify(backend).batchGet(List.of(ident), Entity.EntityType.TOPIC);+ }++ @Test+ void testCachedEntityIdResolverSkipsCacheWhenGateDisallows() {+ // Root entity: no parent chain, so the gate alone decides cache vs underlying.+ NameIdentifier ident = NameIdentifier.of("metalake");+ TopicEntity cachedEntity = Mockito.mock(TopicEntity.class);+ Mockito.when(cachedEntity.id()).thenReturn(1L);+ EntityCache cache = Mockito.mock(EntityCache.class);+ Mockito.when(+ cache.withCacheLock(any(EntityCacheKey.class), any(EntityCache.ThrowingSupplier.class)))+ .thenAnswer(+ invocation -> {+ @SuppressWarnings("unchecked")+ EntityCache.ThrowingSupplier<?, Exception> action = invocation.getArgument(1);+ return action.get();+ });+ Mockito.when(cache.getIfPresent(ident, Entity.EntityType.METALAKE))+ .thenReturn(Optional.of(cachedEntity));+ EntityIdResolver underlying = Mockito.mock(EntityIdResolver.class);+ Mockito.when(underlying.getEntityId(ident, Entity.EntityType.METALAKE)).thenReturn(99L);++ AtomicBoolean allowCache = new AtomicBoolean(false);+ EntityIdResolver resolver =+ new CachedEntityIdResolver(cache, underlying, (id, type) -> allowCache.get());++ Assertions.assertEquals(99L, resolver.getEntityId(ident, Entity.EntityType.METALAKE));+ Mockito.verify(underlying).getEntityId(ident, Entity.EntityType.METALAKE);+ Mockito.verify(cache, Mockito.never()).getIfPresent(ident, Entity.EntityType.METALAKE);++ allowCache.set(true);+ Assertions.assertEquals(1L, resolver.getEntityId(ident, Entity.EntityType.METALAKE));+ Mockito.verify(cache).getIfPresent(ident, Entity.EntityType.METALAKE);+ }++ @Test+ void testCachedEntityIdResolverFallsBackWhenParentChainMisses() {+ NameIdentifier topic = NameIdentifier.of("metalake", "catalog", "schema", "topic");+ NameIdentifier schema = NameIdentifier.of("metalake", "catalog", "schema");+ TopicEntity cachedTopic = Mockito.mock(TopicEntity.class);+ Mockito.when(cachedTopic.id()).thenReturn(1L);+ EntityCache cache = Mockito.mock(EntityCache.class);+ Mockito.when(+ cache.withCacheLock(any(EntityCacheKey.class), any(EntityCache.ThrowingSupplier.class)))+ .thenAnswer(+ invocation -> {+ @SuppressWarnings("unchecked")+ EntityCache.ThrowingSupplier<?, Exception> action = invocation.getArgument(1);+ return action.get();+ });+ Mockito.when(cache.getIfPresent(topic, Entity.EntityType.TOPIC))+ .thenReturn(Optional.of(cachedTopic));+ Mockito.when(cache.getIfPresent(schema, Entity.EntityType.SCHEMA)).thenReturn(Optional.empty());+ EntityIdResolver underlying = Mockito.mock(EntityIdResolver.class);+ NamespacedEntityId fromDb = new NamespacedEntityId(99L, 10L, 20L, 30L);+ Mockito.when(underlying.getEntityIds(topic, Entity.EntityType.TOPIC)).thenReturn(fromDb);+ Mockito.when(underlying.getEntityId(topic, Entity.EntityType.TOPIC)).thenReturn(99L);++ EntityIdResolver resolver = new CachedEntityIdResolver(cache, underlying);++ Assertions.assertSame(fromDb, resolver.getEntityIds(topic, Entity.EntityType.TOPIC));+ Mockito.verify(underlying).getEntityIds(topic, Entity.EntityType.TOPIC);+ Assertions.assertEquals(99L, resolver.getEntityId(topic, Entity.EntityType.TOPIC));+ Mockito.verify(underlying).getEntityId(topic, Entity.EntityType.TOPIC);+ }++ @Test+ void testEndPendingWriteInvalidatesBeforeReleasingPrefixes() throws Exception {+ NameIdentifier schema = NameIdentifier.of("metalake", "catalog", "schema");+ NameIdentifier table = NameIdentifier.of("metalake", "catalog", "schema", "table");+ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicLong epoch = (AtomicLong) FieldUtils.readField(store, "cacheInvalidationEpoch", true);+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", schema, Entity.EntityType.SCHEMA);+ long epochBefore = epoch.get();+ Assertions.assertTrue(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isPendingWrite", table, Entity.EntityType.TABLE));++ AtomicBoolean pendingDuringInvalidate = new AtomicBoolean(false);+ Mockito.doAnswer(+ invocation -> {+ pendingDuringInvalidate.set(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isPendingWrite", table, Entity.EntityType.TABLE));+ return false;+ })+ .when(cache)+ .invalidate(schema, Entity.EntityType.SCHEMA);++ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "endPendingWrite", schema, Entity.EntityType.SCHEMA);++ Assertions.assertTrue(pendingDuringInvalidate.get());+ Assertions.assertTrue(epoch.get() > epochBefore);+ Assertions.assertTrue(cacheBlocks().isEmpty());+ Assertions.assertFalse(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isPendingWrite", table, Entity.EntityType.TABLE));+ }++ @Test+ void testEndPendingWriteClearsCacheWhenInvalidateFails() throws Exception {+ NameIdentifier schema = NameIdentifier.of("metalake", "catalog", "schema");+ NameIdentifier table = NameIdentifier.of("metalake", "catalog", "schema", "table");+ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", schema, Entity.EntityType.SCHEMA);+ Mockito.doThrow(new IllegalStateException("interrupted invalidate"))+ .when(cache)+ .invalidate(schema, Entity.EntityType.SCHEMA);++ Exception thrown =+ Assertions.assertThrows(+ Exception.class,+ () ->+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "endPendingWrite", schema, Entity.EntityType.SCHEMA));+ Assertions.assertInstanceOf(IllegalStateException.class, thrown.getCause());++ Mockito.verify(cache).clear();+ Assertions.assertTrue(cacheBlocks().isEmpty());+ Assertions.assertFalse(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isCacheObservationBlocked", table, Entity.EntityType.TABLE));+ }++ @Test+ void testGetDoesNotPublishWhileWritePending() throws Exception {+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "topic");+ TopicEntity entity = Mockito.mock(TopicEntity.class);+ Mockito.when(entity.nameIdentifier()).thenReturn(ident);+ Mockito.when(entity.type()).thenReturn(Entity.EntityType.TOPIC);+ Mockito.when(backend.get(ident, Entity.EntityType.TOPIC)).thenReturn(entity);++ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", ident, Entity.EntityType.TOPIC);++ Assertions.assertSame(entity, store.get(ident, Entity.EntityType.TOPIC, TopicEntity.class));+ Mockito.verify(cache, Mockito.never()).put(entity);+ }++ @Test+ void testGetDoesNotPublishWhileAncestorWritePending() throws Exception {+ NameIdentifier catalog = NameIdentifier.of("metalake", "catalog");+ NameIdentifier topic = NameIdentifier.of("metalake", "catalog", "schema", "topic");+ TopicEntity entity = Mockito.mock(TopicEntity.class);+ Mockito.when(entity.nameIdentifier()).thenReturn(topic);+ Mockito.when(entity.type()).thenReturn(Entity.EntityType.TOPIC);+ Mockito.when(backend.get(topic, Entity.EntityType.TOPIC)).thenReturn(entity);++ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", catalog, Entity.EntityType.CATALOG);++ Assertions.assertSame(entity, store.get(topic, Entity.EntityType.TOPIC, TopicEntity.class));+ Mockito.verify(cache, Mockito.never()).put(entity);+ }++ @Test+ void testOverwriteDropsCacheBeforeBackendInsert()throws IOException, EntityAlreadyExistsException, IllegalAccessException {NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "topic");TopicEntity topic = Mockito.mock(TopicEntity.class);Mockito.when(topic.nameIdentifier()).thenReturn(ident);Mockito.when(topic.type()).thenReturn(Entity.EntityType.TOPIC);NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicBoolean invalidatedBeforeBackend = new AtomicBoolean(false);+ AtomicBoolean pendingDuringBackend = new AtomicBoolean(false);Mockito.doAnswer(invocation -> {- Mockito.verify(cache, Mockito.never()).invalidate(ident, Entity.EntityType.TOPIC);+ Mockito.verify(cache).invalidate(ident, Entity.EntityType.TOPIC);+ invalidatedBeforeBackend.set(true);+ pendingDuringBackend.set(writeBlocked(ident, Entity.EntityType.TOPIC));return null;}).when(backend)@@ -211,21 +524,72 @@ public class TestRelationalEntityStore {store.put(topic, true);- InOrder inOrder = Mockito.inOrder(backend, cache);- inOrder.verify(backend).insert(topic, true);- inOrder.verify(cache).invalidate(ident, Entity.EntityType.TOPIC);+ Assertions.assertTrue(invalidatedBeforeBackend.get());+ Assertions.assertTrue(pendingDuringBackend.get());+ Assertions.assertFalse(writeBlocked(ident, Entity.EntityType.TOPIC));Mockito.verify(cache, Mockito.never()).put(topic);}@Test- void testDeleteInvalidatesCacheAfterBackendDelete()+ void testNonOverwritePutDropsStaleCacheBeforeInsertAndPublishesAfter()+ throws IOException, EntityAlreadyExistsException, IllegalAccessException {+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "topic");+ TopicEntity created = Mockito.mock(TopicEntity.class);+ Mockito.when(created.nameIdentifier()).thenReturn(ident);+ Mockito.when(created.type()).thenReturn(Entity.EntityType.TOPIC);+ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicBoolean invalidatedBeforeBackend = new AtomicBoolean(false);+ AtomicBoolean pendingDuringBackend = new AtomicBoolean(false);++ Mockito.doAnswer(+ invocation -> {+ Mockito.verify(cache).invalidate(ident, Entity.EntityType.TOPIC);+ invalidatedBeforeBackend.set(true);+ pendingDuringBackend.set(writeBlocked(ident, Entity.EntityType.TOPIC));+ return null;+ })+ .when(backend)+ .insert(created, false);++ store.put(created, false);++ Assertions.assertTrue(invalidatedBeforeBackend.get());+ Assertions.assertTrue(pendingDuringBackend.get());+ Assertions.assertFalse(writeBlocked(ident, Entity.EntityType.TOPIC));+ Mockito.verify(cache).put(created);+ }++ @Test+ void testIsPendingWriteLooksUpAncestorPrefixes() throws Exception {+ NameIdentifier catalog = NameIdentifier.of("metalake", "catalog");+ NameIdentifier table = NameIdentifier.of("metalake", "catalog", "schema", "table");+ NameIdentifier other = NameIdentifier.of("metalake", "other", "schema", "table");+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "retainPendingWrite", catalog, Entity.EntityType.CATALOG);++ Assertions.assertTrue(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isPendingWrite", table, Entity.EntityType.TABLE));+ Assertions.assertFalse(+ (boolean)+ org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(+ store, true, "isPendingWrite", other, Entity.EntityType.TABLE));+ }++ @Test+ void testDeleteDropsCacheBeforeBackendDelete()throws IOException, NoSuchEntityException, IllegalAccessException {NameIdentifier ident = NameIdentifier.of("metalake", "catalog");NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);+ AtomicBoolean invalidatedBeforeBackend = new AtomicBoolean(false);+ AtomicBoolean pendingDuringBackend = new AtomicBoolean(false);Mockito.doAnswer(invocation -> {- Mockito.verify(cache, Mockito.never()).invalidate(ident, Entity.EntityType.CATALOG);+ Mockito.verify(cache).invalidate(ident, Entity.EntityType.CATALOG);+ invalidatedBeforeBackend.set(true);+ pendingDuringBackend.set(writeBlocked(ident, Entity.EntityType.CATALOG));return true;}).when(backend)@@ -233,9 +597,9 @@ public class TestRelationalEntityStore {Assertions.assertTrue(store.delete(ident, Entity.EntityType.CATALOG, true));- InOrder inOrder = Mockito.inOrder(backend, cache);- inOrder.verify(backend).delete(ident, Entity.EntityType.CATALOG, true);- inOrder.verify(cache).invalidate(ident, Entity.EntityType.CATALOG);+ Assertions.assertTrue(invalidatedBeforeBackend.get());+ Assertions.assertTrue(pendingDuringBackend.get());+ Assertions.assertFalse(writeBlocked(ident, Entity.EntityType.CATALOG));}@Testdiff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreBatchGetLateFill.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreBatchGetLateFill.javaindex 0a0b8892ab..59160cefc3 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreBatchGetLateFill.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreBatchGetLateFill.java@@ -229,7 +229,9 @@ public class TestRelationalEntityStoreBatchGetLateFill {store.batchGet(List.of(ident), Entity.EntityType.TABLE, TableEntity.class);- Mockito.verify(cache).clear();+ // invalidateOrClear clears when the targeted drop throws, then the listener fallback clears+ // again. Either clear fences the in-flight fill.+ Mockito.verify(cache, Mockito.atLeastOnce()).clear();Assertions.assertFalse(cache.contains(ident, Entity.EntityType.TABLE));}