Skip to content

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

[#13893] fix(cache): Recover late change logs and fence cache publication (#13831)

Qi Yu28fd283135a5
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
index 1141c5536c..f0d5030965 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
@@ -19,10 +19,14 @@
package org.apache.gravitino.catalog.fileset;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -290,6 +294,10 @@ public class TestFilesetCatalogOperations {
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
// Fix cache config for test
diff --git a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
index 727bf38882..c2c0a5d60e 100644
--- a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
+++ b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
@@ -20,10 +20,14 @@ package org.apache.gravitino.catalog.kafka;
import static org.apache.gravitino.Catalog.Type.MESSAGING;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -171,6 +175,10 @@ public class TestKafkaCatalogOperations extends KafkaClusterEmbedded {
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
// Fix cache config for test
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
index df25b219c6..5e86bd2ffa 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
@@ -19,10 +19,14 @@
package org.apache.gravitino.catalog.lakehouse.generic;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -130,6 +134,10 @@ public class TestGenericCatalogOperations {
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(false);
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 cc1798ac37..510f9b9e4a 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
@@ -19,10 +19,14 @@
package org.apache.gravtitino.catalog.model;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -138,6 +142,10 @@ public class TestModelCatalogOperations {
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
// Fix cache config for test
diff --git a/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java b/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
index c78aacde16..429bc087ac 100644
--- a/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
+++ b/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
@@ -20,11 +20,15 @@
package org.apache.gravitino.cache.it;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_IDLE_CONNECTIONS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -302,6 +306,10 @@ public class AbstractEntityStorageBenchmark<E extends Entity & HasIdentifier> {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
diff --git a/core/src/main/java/org/apache/gravitino/Configs.java b/core/src/main/java/org/apache/gravitino/Configs.java
index 600d5da8e5..e41901efa9 100644
--- a/core/src/main/java/org/apache/gravitino/Configs.java
+++ b/core/src/main/java/org/apache/gravitino/Configs.java
@@ -233,6 +233,32 @@ public class Configs {
.checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
.createWithDefault(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ /** Default recent-history replay window in seconds. */
+ public static final long DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS = 60L;
+
+ /** Default maximum locally remembered event IDs. */
+ public static final int DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES = 100000;
+
+ /** Window for replaying recent change records to catch out-of-order commits. */
+ public static final ConfigEntry<Long> ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS =
+ new ConfigBuilder("gravitino.entityChangeLog.replayWindowSecs")
+ .doc(
+ "Recent change log replay window in seconds; 0 disables replay. This bounds recorded created_at age, not commit age. "
+ + "Replay sweeps start at most once per max(pollIntervalSecs, replayWindowSecs / 4)")
+ .version(ConfigConstants.VERSION_2_0_0)
+ .longConf()
+ .checkValue(value -> value >= 0 && value <= 86400, "Must be between 0 and 86400 seconds")
+ .createWithDefault(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+
+ /** Maximum event IDs retained locally to suppress repeated replay invalidations. */
+ public static final ConfigEntry<Integer> ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES =
+ new ConfigBuilder("gravitino.entityChangeLog.replayMaxEntries")
+ .doc("Maximum locally remembered event IDs for recent change log replay deduplication")
+ .version(ConfigConstants.VERSION_2_0_0)
+ .intConf()
+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
+ .createWithDefault(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
+
public static final ConfigEntry<Long> ENTITY_CHANGE_LOG_RETENTION_SECS =
new ConfigBuilder("gravitino.entityChangeLog.retentionSecs")
.doc("The retention time in seconds for entity change logs. Set 0 to disable cleanup")
diff --git a/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
index 89ada1ad2f..38321236b7 100644
--- a/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java
@@ -107,10 +107,10 @@ public abstract class BaseEntityCache implements EntityCache {
public final <E extends Entity & HasIdentifier> void put(E entity) {
Preconditions.checkArgument(entity != null, "Entity cannot be null");
- // Called before the cacheability check and before any subclass takes this entity's lock: it
- // may take another key's lock (e.g. the model key when inserting a model version), and nesting
- // two entity locks could deadlock. A non-cacheable entity can still invalidate a cacheable one,
- // so this runs for every entity.
+ // Called before the cacheability check: a non-cacheable entity can still invalidate a cacheable
+ // one, so this runs for every entity. The caller may already hold this entity's lock, so the
+ // hook must not take another entity's lock (see
+ // SupportsEntityStoreCache#invalidateOnKeyChange).
invalidateOnKeyChange(entity);
if (!isCacheable(entity.type())) {
diff --git a/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java b/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
index 2f46846091..78ec6b1401 100644
--- a/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
+++ b/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java
@@ -89,6 +89,12 @@ public interface SupportsEntityStoreCache {
* <p>For example, inserting a {@code ModelVersion} may require invalidating the corresponding
* {@code Model} entry in the cache to maintain consistency.
*
+ * <p>Callers may run {@link #put(Entity)}, and therefore this method, while holding the inserted
+ * entity's own cache lock (see {@link EntityCache#withCacheLock(EntityCacheKey,
+ * EntityCache.ThrowingRunnable)}); the relational entity store publishes reads and inserts that
+ * way. Implementations must therefore not acquire another entity's cache lock here, since nesting
+ * two entity locks can deadlock.
+ *
* @param entity The entity being inserted
* @param <E> The type of the entity
*/
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
index e68e95e75c..01a397e389 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java
@@ -36,18 +36,17 @@ import org.slf4j.LoggerFactory;
* <p>This listener is called <em>synchronously</em> in the poller thread. Implementations must not
* block or perform expensive I/O; only fast, in-memory cache invalidations are permitted.
*
- * <p>The poller hands each batch to a listener only once, so a listener has to clean up after
- * itself when it fails. This one does what {@code EntityCacheChangeLogListener} and {@code
+ * <p>The poller does not retry a failed callback, so a listener has to clean up after itself when
+ * it fails. This one does what {@code EntityCacheChangeLogListener} and {@code
* JcasbinChangeListener} do: if removing one catalog from the cache fails, it clears the whole
* catalog cache, which also covers the entry it failed to remove and the rest of the batch. A row
* that cannot be parsed is simply skipped, because it does not point at any catalog and so cannot
* leave anything stale.
*
- * <p>Before removing anything, the listener first goes through the whole batch and marks off the
- * changes this node made itself. Doing it in that order means a later failure cannot leave one of
- * those marks behind, which would otherwise make a future change from another node look like a
- * local one. If the clear itself fails, the exception goes up to the poller, which logs it at
- * {@code ERROR} and moves on, and the catalog stays stale until it expires.
+ * <p>Every valid catalog event invalidates its entry, including local events and replayed rows. A
+ * name-based local marker cannot reliably identify an originating transaction. Extra removals are
+ * preferable to suppressing a remote mutation; operation leases protect wrappers in use. If the
+ * clear itself fails, the exception goes to the poller for error logging.
*
* <p><b>What clearing costs:</b> dropping a catalog from the cache retires its {@code
* CatalogWrapper}. Idle wrappers release their connection pools and {@code IsolatedClassLoader}s
@@ -72,9 +71,15 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
this.catalogManager = catalogManager;
}
+ /** {@inheritDoc} */
+ @Override
+ public boolean supportsReplay() {
+ return true;
+ }
+
@Override
public void onEntityChange(List<EntityChangeRecord> changes) {
- List<CatalogInvalidation> remoteInvalidations = new ArrayList<>();
+ List<CatalogInvalidation> invalidations = new ArrayList<>();
for (EntityChangeRecord change : changes) {
if (!isCatalogChange(change)) {
continue;
@@ -88,41 +93,17 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
}
NameIdentifier ident = identOpt.get();
- boolean localMutation;
- try {
- localMutation = catalogManager.consumeLocalMutation(ident);
- } catch (RuntimeException e) {
- // We could not tell whether this change came from this node or another one. The name is
- // valid, so assume it came from another node: the worst case is one extra cache removal,
- // while skipping it could leave an old catalog cached forever.
- LOG.error(
- "Failed to check local mutation state for catalog {}, treating change log record id {} "
- + "as remote to avoid serving stale metadata",
- ident,
- change.getId(),
- e);
- localMutation = false;
- }
-
- if (localMutation) {
- LOG.debug(
- "Skipping catalog cache invalidation for local mutation: {}, change log id {}",
- ident,
- change.getId());
- continue;
- }
-
- remoteInvalidations.add(new CatalogInvalidation(change, ident));
+ invalidations.add(new CatalogInvalidation(change, ident));
}
- for (CatalogInvalidation invalidation : remoteInvalidations) {
+ for (CatalogInvalidation invalidation : invalidations) {
EntityChangeRecord change = invalidation.change;
NameIdentifier ident = invalidation.ident;
// INFO on purpose: dropping the catalog from the cache retires its wrapper and eventually
// closes the connection pool and isolated classloader, either immediately or after active
// leases finish. This is the main thing the change log does across nodes.
LOG.info(
- "Invalidating catalog cache for {} due to a remote {} recorded in change log id {}",
+ "Invalidating catalog cache for {} due to a {} recorded in change log id {}",
ident,
change.getOperateType(),
change.getId());
@@ -130,8 +111,8 @@ public class CatalogChangeLogListener implements EntityChangeLogListener {
try {
catalogManager.getCatalogCache().invalidate(ident);
} catch (RuntimeException e) {
- // This batch will never be sent again, so giving up here would keep serving the old
- // catalog until it expires on its own. Clear the whole cache instead; active operation
+ // Failed callbacks have no guaranteed retry; bounded replay may not redeliver this row.
+ // Clear the whole cache instead of serving an old catalog until expiry; active operation
// leases defer resource cleanup until those operations finish.
LOG.error(
"Failed to evict catalog {} for change log id {}, clearing the whole catalog cache to "
diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
index 0342080457..a47e450415 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
@@ -52,11 +52,9 @@ import java.util.Optional;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
@@ -527,8 +525,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
// Copy-on-write: listeners may be registered while the cache's removal listener (running on a
// cache executor thread) is iterating this list.
private final List<Consumer<NameIdentifier>> removalListeners = new CopyOnWriteArrayList<>();
- private final ConcurrentHashMap<NameIdentifier, AtomicInteger> localMutationCounts =
- new ConcurrentHashMap<>();
// Cache loads and publications take the read lock; close() takes the write lock. Operations do
// not hold this lock after acquiring a CatalogLease because the lease itself keeps the wrapper
@@ -538,11 +534,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
/** Guarded by {@link #lifecycleLock}. */
private boolean closed;
- // Set to true when a CatalogChangeLogListener is active. markLocalMutation() is a no-op
- // unless this flag is set, preventing unbounded growth of localMutationCounts in deployments
- // that do not use a relational entity store (where the poller never runs).
- private volatile boolean trackLocalMutations = false;
-
/**
* Constructs a CatalogManager instance.
*
@@ -590,15 +581,10 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
.build())))
.build();
- // If the entity store maintains a change log, register a listener that invalidates this
- // manager's local catalog cache from cross-node changes, and enable local-mutation tracking so
- // changes made by this node are not redundantly re-invalidated. Registration is the last step
- // of
- // the constructor so the listener never sees a half-initialized manager (catalogCache and
- // localMutationCounts are already set). CatalogChangeLogListener stays an implementation detail
- // of this class rather than being wired externally.
+ // Register last so the listener cannot observe a half-initialized manager. All consumed
+ // catalog events invalidate the cache: name-based markers cannot identify the originating
+ // transaction reliably, particularly when polling races the caller or replays recent rows.
if (store instanceof SupportsEntityChangeLog) {
- this.trackLocalMutations = true;
this.catalogChangeLogListener = new CatalogChangeLogListener(this);
((SupportsEntityChangeLog) store).registerEntityChangeLogListener(catalogChangeLogListener);
} else {
@@ -638,9 +624,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
.unregisterEntityChangeLogListener(catalogChangeLogListener);
} catch (RuntimeException e) {
LOG.warn("Failed to unregister the catalog change-log listener", e);
- } finally {
- trackLocalMutations = false;
- localMutationCounts.clear();
}
}
}
@@ -681,50 +664,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
removalListeners.add(listener);
}
- /**
- * Records that this process has just mutated the given catalog locally. The entity change log
- * poller will see the corresponding change log row and should skip cache invalidation for it
- * because this process already updated the cache.
- *
- * @param ident the catalog identifier (pre-mutation name for renames)
- */
- void markLocalMutation(NameIdentifier ident) {
- if (!trackLocalMutations) {
- return;
- }
- int pending =
- localMutationCounts.computeIfAbsent(ident, k -> new AtomicInteger()).incrementAndGet();
- LOG.debug("Marked a local mutation for catalog {}, {} pending marker(s)", ident, pending);
- }
-
- /**
- * Attempts to consume one local mutation marker for the given identifier.
- *
- * <p>Thread-safety note: {@link ConcurrentHashMap#computeIfPresent} executes the remapping
- * function atomically under a per-bucket lock, so {@code consumed[0]} is set and the counter is
- * decremented as a single atomic step. {@code consumed[0]} is a single-element array (the
- * standard Java pattern for a mutable capture in a lambda) that is only read by this thread after
- * {@code computeIfPresent} returns, so no additional synchronization is needed.
- *
- * @return true if a local mutation was pending and has been consumed (caller should skip
- * invalidation), false if the change originated from a remote node
- */
- boolean consumeLocalMutation(NameIdentifier ident) {
- boolean[] consumed = {false};
- localMutationCounts.computeIfPresent(
- ident,
- (k, count) -> {
- consumed[0] = true;
- return count.decrementAndGet() <= 0 ? null : count;
- });
- return consumed[0];
- }
-
- @VisibleForTesting
- void setTrackLocalMutations(boolean trackLocalMutations) {
- this.trackLocalMutations = trackLocalMutations;
- }
-
/**
* Lists the catalogs within the specified namespace.
*
@@ -1164,7 +1103,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
return newCatalogBuilder.build();
});
- markLocalMutation(ident);
catalogCache.invalidate(ident);
return null;
} catch (IOException e) {
@@ -1205,7 +1143,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
return newCatalogBuilder.build();
});
- markLocalMutation(ident);
catalogCache.invalidate(ident);
return null;
} catch (IOException e) {
@@ -1283,7 +1220,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
// the old catalog identifier from the store (after the invalidate) will get
// NoSuchCatalogException instead of stale data. Invalidating before the update creates
// a window where the background thread repopulates the cache with the old entity.
- markLocalMutation(ident);
catalogCache.invalidate(ident);
// The old fileset catalog's provider is "hadoop", whereas the new fileset catalog's
// provider is "fileset", still using "hadoop" will lead to catalog loading issue. So
@@ -1425,7 +1361,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
copyProperties(catalogWrapper.catalog().entity().getProperties());
boolean deleted = store.delete(ident, EntityType.CATALOG, true);
if (deleted) {
- markLocalMutation(ident);
try {
catalogWrapper.doWithCatalogOps(
operations -> {
@@ -2252,7 +2187,6 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
return newCatalogBuilder.build();
});
- markLocalMutation(nameIdentifier);
catalogCache.invalidate(nameIdentifier);
} catch (NoSuchCatalogException e) {
@@ -2283,14 +2217,7 @@ public class CatalogManager implements CatalogDispatcher, Closeable {
}
catalogCache.invalidate(ident);
try {
- if (store.delete(ident, EntityType.CATALOG, true)) {
- // This cleanup deletion writes a DROP record to the entity change log. Mark it as a local
- // mutation so the change-log poller consumes that record's token instead of one meant for
- // a later mutation of the same identifier. Without this, the poller could treat a
- // subsequent local change as remote and spuriously invalidate (and asynchronously close) a
- // cached catalog wrapper that is still in use, causing a NullPointerException.
- markLocalMutation(ident);
- }
+ store.delete(ident, EntityType.CATALOG, true);
} catch (IOException e) {
LOG.error("Failed to clean up catalog {}", ident, e);
}
diff --git a/core/src/main/java/org/apache/gravitino/metrics/source/EntityChangeLogMetricsSource.java b/core/src/main/java/org/apache/gravitino/metrics/source/EntityChangeLogMetricsSource.java
index ffbaed05d7..19e8426d4c 100644
--- a/core/src/main/java/org/apache/gravitino/metrics/source/EntityChangeLogMetricsSource.java
+++ b/core/src/main/java/org/apache/gravitino/metrics/source/EntityChangeLogMetricsSource.java
@@ -38,6 +38,9 @@ public class EntityChangeLogMetricsSource extends MetricsSource {
private final Counter recordsApplied = getCounter("records-applied-total");
private final Counter invalidationFailures = getCounter("invalidation-failures-total");
private final Counter fallbackClears = getCounter("fallback-clears-total");
+ private final Counter replayFailures = getCounter("replay-failures-total");
+ private final Counter replayRecords = getCounter("replay-records-total");
+ private final Counter dedupEvictions = getCounter("dedup-evictions-total");
private final Histogram batchSize = getHistogram("batch-size-records");
private final Timer pollDuration = getTimer("poll-duration");
@@ -112,6 +115,21 @@ public class EntityChangeLogMetricsSource extends MetricsSource {
fallbackClears.inc();
}
+ /** Records a failed recent-history replay query; incremental delivery is not affected. */
+ public void replayFailed() {
+ replayFailures.inc();
+ }
+
+ /** Records previously unseen rows found behind the cursor by recent-history replay. */
+ public void replayRecordsFound(int count) {
+ replayRecords.inc(count);
+ }
+
+ /** Records remembered IDs evicted at capacity, which may allow duplicate invalidations. */
+ public void dedupEvicted(int count) {
+ dedupEvictions.inc(count);
+ }
+
/** Starts a poll duration measurement. */
public Timer.Context timePoll() {
return pollDuration.time();
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java
index d208d2899a..ae40b0584e 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java
@@ -55,8 +55,8 @@ import org.slf4j.LoggerFactory;
* whole cache is cleared instead, which is strictly stronger than the invalidation that
* failed and only costs a cold-cache penalty, since the cache is derived state. If even the
* clear also fails, the exception goes up to {@link EntityChangeLogPoller}, which only logs
- * it and moves on. The batch is never sent again, so this node may keep serving stale entries
- * until they expire.
+ * it and moves on. Failed delivery has no guaranteed retry, so this node may serve stale
+ * entries until they expire.
* </ul>
*/
public class EntityCacheChangeLogListener implements EntityChangeLogListener {
@@ -143,6 +143,12 @@ public class EntityCacheChangeLogListener implements EntityChangeLogListener {
};
}
+ /** {@inheritDoc} */
+ @Override
+ public boolean supportsReplay() {
+ return true;
+ }
+
@Override
public void onEntityChange(List<EntityChangeRecord> changes) {
long startNanos = System.nanoTime();
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogListener.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogListener.java
index cbc139e5c3..c8c55834ae 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogListener.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogListener.java
@@ -28,13 +28,28 @@ public interface EntityChangeLogListener {
/**
* Handles a batch of entity changes.
*
- * <p>A batch is handed to the listener only once and is never sent again, so the listener has to
- * clean up after itself when something goes wrong. The simplest way is to clear the whole cache
- * this listener keeps, because that also removes whatever entry it failed to remove. Do not count
- * on the poller retrying. If this method throws, the poller only logs the error at {@code ERROR}
- * and moves on, and this listener's cache can stay wrong from then on.
+ * <p>Listeners opting into {@link #supportsReplay()} must tolerate repeated invalidations:
+ * recent-history replay can redeliver rows after bounded deduplication expires or evicts an ID. A
+ * failed callback is not retried, so the listener has to clean up after itself when something
+ * goes wrong. The simplest way is to clear the whole cache this listener keeps, because that also
+ * removes whatever entry it failed to remove. Do not count on the poller retrying. If this method
+ * throws, the poller only logs the error at {@code ERROR} and moves on, and this listener's cache
+ * can stay wrong from then on.
*
* @param changes the entity changes fetched in one poller cycle
*/
void onEntityChange(List<EntityChangeRecord> changes);
+
+ /**
+ * Whether this listener accepts recent-history replay and duplicate event IDs.
+ *
+ * <p>The default preserves incremental-only delivery for existing implementations. Opt-in
+ * callbacks must be idempotent. This method runs on the poller thread and must not block; a
+ * failure skips replay for this listener without preventing other listeners from receiving it.
+ *
+ * @return true to receive replayed records, false to receive only incremental batches
+ */
+ default boolean supportsReplay() {
+ return false;
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
index 9624a4b9f3..971e0dd483 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogPoller.java
@@ -21,7 +21,12 @@ package org.apache.gravitino.storage.relational;
import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
@@ -40,15 +45,15 @@ import org.slf4j.LoggerFactory;
* Global poller for {@code entity_change_log}.
*
* <p>There is one poller per Gravitino server process, and it keeps one read position (the id of
- * the last row it has read). It reads a batch of rows, hands that batch to every listener once, and
+ * the last incremental row it has read). It reads a batch of rows, hands it to every listener, and
* then always moves the read position forward, even if a listener failed. The read position is
* shared by all listeners, so holding it back to retry one listener would stop every other listener
* from seeing new changes, and all the caches in this process would fall behind.
*
- * <p>Because a batch is handed out only once and is never sent again, every listener must be able
- * to fix itself when it fails. The usual way to do that is to clear its whole cache: clearing
- * everything also covers whatever the listener failed to remove, so nothing stale is left behind.
- * The three listeners registered today do exactly that:
+ * <p>Listener failures are not retried, so every listener must be able to fix itself when it fails.
+ * The usual way to do that is to clear its whole cache: clearing everything also covers whatever
+ * the listener failed to remove, so nothing stale is left behind. The three listeners registered
+ * today do exactly that:
*
* <ul>
* <li>{@code EntityCacheChangeLogListener} clears its whole entity cache.
@@ -67,10 +72,23 @@ import org.slf4j.LoggerFactory;
* <p>Every listener failure is logged at {@code ERROR}, so a listener that keeps failing stays
* visible in the logs even though the poller keeps going.
*
- * <p>Each poll cycle reads at most one batch. A full batch means more rows may be waiting, so the
- * next cycle starts right away instead of after the poll interval; an empty or partial batch, or a
- * failed cycle, waits the full interval. A backlog is therefore drained as fast as batches can be
- * read and delivered, while an idle or failing poller still polls only once per interval.
+ * <p>Each poll cycle reads at most one incremental batch and one recent-history replay page. Replay
+ * catches out-of-order commits within a configured record-age window, deduplicates recently
+ * delivered IDs, and never moves the incremental cursor backwards. It does not guarantee delivery
+ * beyond the window or after log pruning. Replay is delivered only to listeners opting into {@link
+ * EntityChangeLogListener#supportsReplay()}. Their callbacks must be idempotent because bounded
+ * deduplication may evict IDs and startup replay can include historical rows.
+ *
+ * <p>Each replay sweep rereads every row in the window, so a new sweep starts at most once per
+ * {@code max(pollIntervalSecs, replayWindowSecs / 4)}. This bounds rereads to about four per row
+ * and delays recovery of a late row by up to one sweep interval; a row is caught only if it becomes
+ * visible before its recorded age exceeds the window minus one sweep interval.
+ *
+ * <p>A full incremental batch or replay page means more rows may be waiting, so the next cycle
+ * starts right away instead of after the poll interval. When both reads are empty or partial, or
+ * the cycle fails, the poller waits the full interval. A backlog is therefore drained as fast as
+ * batches can be read and delivered, while an idle or failing poller still polls only once per
+ * interval.
*/
public class EntityChangeLogPoller implements AutoCloseable {
@@ -83,6 +101,27 @@ public class EntityChangeLogPoller implements AutoCloseable {
private final long pollIntervalSecs;
private final int batchSize;
private final EntityChangeLogMetricsSource metrics;
+ private final long replayWindowMs;
+ private final int replayMaxEntries;
+ // Minimum gap between the starts of two replay sweeps. Each sweep rereads the whole window, so
+ // starting one every poll would reread every recent row about window/interval times.
+ private final long replaySweepIntervalNanos;
+ // Guarded by doPollChanges' monitor. Insertion order makes expiry and capacity eviction bounded.
+ private final Map<Long, Long> rememberedIds = new LinkedHashMap<>();
+ private long replayAfterCreatedAt = -1;
+ private long replayAfterId;
+ private long replayUpperId;
+ private long startupHighWaterId;
+ private boolean replayFailed;
+ private long replayFailureNanos;
+ private boolean capacityWarningReported;
+ private long capacityWarningNanos;
+ private long pendingDedupEvictions;
+ private boolean replaySweepStarted;
+ // The dedup set is empty until the first sweep completes, so every row it finds is expected
+ // startup history rather than evidence of a late commit.
+ private boolean replaySweepCompleted;
+ private long lastReplaySweepStartNanos;
private ScheduledExecutorService scheduler;
private volatile boolean closed = false;
@@ -120,7 +159,38 @@ public class EntityChangeLogPoller implements AutoCloseable {
*/
public EntityChangeLogPoller(
long pollIntervalSecs, int batchSize, EntityChangeLogMetricsSource metrics) {
+ this(
+ pollIntervalSecs,
+ batchSize,
+ Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS,
+ Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES,
+ metrics);
+ }
+
+ /**
+ * Creates a poller with bounded recent-history replay.
+ *
+ * @param pollIntervalSecs interval between caught-up polling cycles
+ * @param batchSize maximum records per query
+ * @param replayWindowSecs maximum stored timestamp age replayed, or zero to disable replay
+ * @param replayMaxEntries maximum remembered IDs; eviction permits duplicate delivery
+ * @param metrics process-local change log metrics
+ */
+ public EntityChangeLogPoller(
+ long pollIntervalSecs,
+ int batchSize,
+ long replayWindowSecs,
+ int replayMaxEntries,
+ EntityChangeLogMetricsSource metrics) {
+ Preconditions.checkArgument(
+ replayWindowSecs >= 0 && replayWindowSecs <= 86400,
+ "replayWindowSecs must be between 0 and 86400");
+ Preconditions.checkArgument(replayMaxEntries > 0, "replayMaxEntries must be positive");
+ this.replayWindowMs = TimeUnit.SECONDS.toMillis(replayWindowSecs);
+ this.replayMaxEntries = replayMaxEntries;
Preconditions.checkArgument(pollIntervalSecs > 0, "pollIntervalSecs must be positive");
+ this.replaySweepIntervalNanos =
+ TimeUnit.SECONDS.toNanos(Math.max(pollIntervalSecs, replayWindowSecs / 4));
Preconditions.checkArgument(batchSize > 0, "batchSize must be positive");
this.metrics = Preconditions.checkNotNull(metrics, "metrics cannot be null");
this.pollIntervalSecs = pollIntervalSecs;
@@ -163,10 +233,9 @@ public class EntityChangeLogPoller implements AutoCloseable {
* interval later. A poller cannot be started again after {@link #close()}.
*
* <p>On every start (including restarts), the cursor is set to the current maximum change ID in
- * the DB, so historical change records written before this server process started are NOT
- * replayed. This is intentional: on startup the local cache is cold, so there is no stale state
- * to invalidate. Only changes written after this server started need to be applied to the warming
- * cache.
+ * the DB for the incremental stream. Recent-history replay also examines records at or below that
+ * initial cursor: a transaction may have allocated a lower ID before startup but commit after the
+ * local cache warms. Already committed recent rows can therefore be replayed too.
*/
public void start() {
Preconditions.checkState(!closed, "A closed entity change log poller cannot be restarted");
@@ -174,6 +243,12 @@ public class EntityChangeLogPoller implements AutoCloseable {
getOrDefault(
SessionUtils.getWithoutCommit(
EntityChangeLogMapper.class, EntityChangeLogMapper::selectMaxChangeId));
+ startupHighWaterId = entityPollHighWaterId;
+ LOG.info(
+ "Entity change log replay windowMs={} maxRememberedIds={}; recorded created_at age is not commit age; "
+ + "transactions older than the window or pruned history may still be missed",
+ replayWindowMs,
+ replayMaxEntries);
metrics.setDbTailId(entityPollHighWaterId);
tailSampleAttempted = true;
lastTailSampleNanos = nanoTime();
@@ -245,9 +320,9 @@ public class EntityChangeLogPoller implements AutoCloseable {
long nextDelayMillis = TimeUnit.SECONDS.toMillis(pollIntervalSecs);
try {
if (pollChanges()) {
- // Continuous draining is intentional: every cycle advances the cursor and is bounded by
- // batchSize. Tail sampling is rate-limited separately so diagnostics do not double the
- // database query rate while a sustained backlog is being consumed.
+ // Full batches advance the incremental cursor or the replay page cursor. Each query is
+ // bounded by batchSize. Tail sampling is rate-limited during full incremental batches;
+ // replay-only drains still sample the tail when their incremental query is partial.
nextDelayMillis = 0;
}
} finally {
@@ -272,10 +347,11 @@ public class EntityChangeLogPoller implements AutoCloseable {
}
/**
- * Polls one batch and delivers it to the listeners.
+ * Polls an incremental batch and a bounded recent-history page, delivering unseen records.
*
- * @return true if the batch was full, so more rows may be waiting and the next poll should not
- * wait for the interval; false if the poller caught up or the poll failed
+ * @return true if the incremental batch or the replay page was full, so more rows may be waiting
+ * and the next poll should not wait for the interval; false if both caught up or the poll
+ * failed
*/
@VisibleForTesting
boolean pollChanges() {
@@ -296,14 +372,218 @@ public class EntityChangeLogPoller implements AutoCloseable {
private synchronized boolean doPollChanges() {
BatchDelivery delivery = fetchNextDelivery();
- if (delivery == null) {
+ if (replayWindowMs > 0) {
+ expireRememberedIds();
+ }
+ boolean incrementalBacklog = delivery != null && delivery.changes.size() >= batchSize;
+ if (delivery != null) {
+ deliver(delivery);
+ remember(delivery.changes);
+ }
+ // Replay failure must not discard or delay delivery of a successfully fetched new batch.
+ boolean replayBacklog = false;
+ if (replayWindowMs > 0
+ && entityPollHighWaterId > 0
+ && (replayUpperId != 0 || replaySweepDue())
+ && (!replayFailed
+ || nanoTime() - replayFailureNanos >= TimeUnit.SECONDS.toNanos(pollIntervalSecs))) {
+ try {
+ replayBacklog = replayRecentChanges();
+ replayFailed = false;
+ } catch (RuntimeException e) {
+ if (handleInterruptIfAny(e, "Entity change log replay")) {
+ return false;
+ }
+ replayFailed = true;
+ metrics.replayFailed();
+ replayFailureNanos = nanoTime();
+ LOG.warn(
+ "Entity change log replay failed cursor={} replayAfterCreatedAt={} replayAfterId={} "
+ + "replayUpperId={} windowMs={}; incremental delivery continues; replay retries after the poll interval",
+ entityPollHighWaterId,
+ replayAfterCreatedAt,
+ replayAfterId,
+ replayUpperId,
+ replayWindowMs,
+ e);
+ }
+ }
+ return incrementalBacklog || replayBacklog;
+ }
+
+ private boolean replayRecentChanges() {
+ if (replayUpperId == 0) {
+ replaySweepStarted = true;
+ lastReplaySweepStartNanos = nanoTime();
+ replayUpperId = entityPollHighWaterId;
+ }
+ List<EntityChangeRecord> page =
+ SessionUtils.getWithoutCommit(
+ EntityChangeLogMapper.class,
+ m ->
+ m.selectRecentEntityChanges(
+ replayAfterCreatedAt, replayAfterId, replayUpperId, replayWindowMs, batchSize));
+ List<EntityChangeRecord> unseen = new ArrayList<>();
+ for (EntityChangeRecord change : page) {
+ if (!rememberedIds.containsKey(change.getId())) {
+ unseen.add(change);
+ // Absence from this bounded set is evidence of a possible late commit, not proof:
+ // startup history and capacity eviction can also produce previously unseen IDs.
+ LOG.debug(
+ "Replaying previously unseen entity change behind cursor: changeId={} cursor={} "
+ + "startupCursor={} entityType={} fullName={} operation={} createdAt={} approximateAgeMs={} "
+ + "windowMs={}; possible late commit, startup history, or dedup eviction; "
+ + "age uses JVM time and is not transaction duration",
+ change.getId(),
+ entityPollHighWaterId,
+ startupHighWaterId,
+ change.getEntityType(),
+ change.getFullName(),
+ change.getOperateType(),
+ change.getCreatedAt(),
+ System.currentTimeMillis() - change.getCreatedAt(),
+ replayWindowMs);
+ }
+ }
+ if (!unseen.isEmpty()) {
+ metrics.replayRecordsFound(unseen.size());
+ unseen.sort(Comparator.comparingLong(EntityChangeRecord::getId));
+ if (!replaySweepCompleted) {
+ LOG.info(
+ "Entity change log startup replay delivered {} recent record(s) behind cursor={} "
+ + "startupCursor={} windowMs={} records={}; expected after a restart because "
+ + "deduplication starts empty",
+ unseen.size(),
+ entityPollHighWaterId,
+ startupHighWaterId,
+ replayWindowMs,
+ summarize(unseen));
+ } else {
+ LOG.warn(
+ "Entity change log replay found {} previously unseen record(s) behind cursor={} "
+ + "startupCursor={} windowMs={} approximateOldestAgeMs={} records={}; "
+ + "possible late commit or dedup eviction; record details at DEBUG; "
+ + "age uses JVM time, not transaction duration",
+ unseen.size(),
+ entityPollHighWaterId,
+ startupHighWaterId,
+ replayWindowMs,
+ System.currentTimeMillis()
+ - unseen.stream().mapToLong(EntityChangeRecord::getCreatedAt).min().orElse(0),
+ summarize(unseen));
+ }
+ List<EntityChangeRecord> immutable = List.copyOf(unseen);
+ notifyListeners(
+ new BatchDelivery(
+ immutable, immutable.get(immutable.size() - 1).getId(), replayListeners()));
+ remember(immutable);
+ }
+ if (page.size() < batchSize) {
+ LOG.debug(
+ "Entity change log replay sweep complete cursor={} upperId={} fetched={} replayed={} "
+ + "deduplicated={} windowMs={}",
+ entityPollHighWaterId,
+ replayUpperId,
+ page.size(),
+ unseen.size(),
+ page.size() - unseen.size(),
+ replayWindowMs);
+ replaySweepCompleted = true;
+ replayAfterCreatedAt = -1;
+ replayAfterId = 0;
+ replayUpperId = 0;
return false;
}
- deliver(delivery);
- // A full batch is the backlog signal. The sampled tail id would be more precise, but that
- // sample is best-effort and may be missing; a full batch with nothing behind it only costs one
- // extra empty poll before the normal interval resumes.
- return delivery.changes.size() >= batchSize;
+ EntityChangeRecord last = page.get(page.size() - 1);
+ replayAfterCreatedAt = last.getCreatedAt();
+ replayAfterId = last.getId();
+ LOG.debug(
+ "Entity change log replay page cursor={} upperId={} afterCreatedAt={} afterId={} "
+ + "fetched={} replayed={} deduplicated={}",
+ entityPollHighWaterId,
+ replayUpperId,
+ replayAfterCreatedAt,
+ replayAfterId,
+ page.size(),
+ unseen.size(),
+ page.size() - unseen.size());
+ return true;
+ }
+
+ /**
+ * A new sweep starts at most once per sweep interval; pages of a sweep in progress are not
+ * throttled. The first sweep after startup runs at once to cover history below the start cursor.
+ * A row is caught when it becomes visible before its recorded age exceeds the window minus one
+ * sweep interval.
+ */
+ private boolean replaySweepDue() {
+ return !replaySweepStarted
+ || nanoTime() - lastReplaySweepStartNanos >= replaySweepIntervalNanos;
+ }
+
+ private List<EntityChangeLogListener> replayListeners() {
+ List<EntityChangeLogListener> eligible = new ArrayList<>();
+ for (EntityChangeLogListener listener : listeners) {
+ try {
+ if (listener.supportsReplay()) {
+ eligible.add(listener);
+ }
+ } catch (Throwable e) {
+ LOG.warn(
+ "Entity change log replay capability check failed listener={}; skipping its replay",
+ listener.getClass().getName(),
+ e);
+ }
+ }
+ return List.copyOf(eligible);
+ }
+
+ private void expireRememberedIds() {
+ long now = nanoTime();
+ Iterator<Map.Entry<Long, Long>> entries = rememberedIds.entrySet().iterator();
+ while (entries.hasNext()) {
+ if (now - entries.next().getValue() < TimeUnit.MILLISECONDS.toNanos(replayWindowMs)) {
+ break;
+ }
+ entries.remove();
+ }
+ }
+
+ private void remember(List<EntityChangeRecord> changes) {
+ if (replayWindowMs == 0) {
+ return;
+ }
+ long now = nanoTime();
+ int evicted = 0;
+ for (EntityChangeRecord change : changes) {
+ // Keep first-delivery time and insertion order aligned with prefix expiry. Seeing an ID
+ // again in a replay query does not deliver it again or extend its deduplication lifetime.
+ rememberedIds.putIfAbsent(change.getId(), now);
+ if (rememberedIds.size() > replayMaxEntries) {
+ Iterator<Long> ids = rememberedIds.keySet().iterator();
+ ids.next();
+ ids.remove();
+ evicted++;
+ }
+ }
+ if (evicted > 0) {
+ metrics.dedupEvicted(evicted);
+ }
+ pendingDedupEvictions += evicted;
+ if (pendingDedupEvictions > 0
+ && (!capacityWarningReported
+ || now - capacityWarningNanos >= TimeUnit.SECONDS.toNanos(pollIntervalSecs))) {
+ capacityWarningReported = true;
+ capacityWarningNanos = now;
+ LOG.warn(
+ "Entity change log replay dedup capacity reached cursor={} evictedIds={} maxEntries={} "
+ + "windowMs={}; duplicate invalidations may occur; consider increasing replayMaxEntries",
+ entityPollHighWaterId,
+ pendingDedupEvictions,
+ replayMaxEntries,
+ replayWindowMs);
+ pendingDedupEvictions = 0;
+ }
}
@Nullable
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.java
index dd61110ffc..876e0c6c84 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
@@ -133,6 +133,8 @@ public class RelationalEntityStore
new EntityChangeLogPoller(
config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS),
config.get(Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE),
+ config.get(Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS),
+ config.get(Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES),
changeLogMetrics);
this.entityChangeLogCleaner =
new EntityChangeLogCleaner(
@@ -226,6 +228,7 @@ public class RelationalEntityStore
@Override
public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
throws IOException, EntityAlreadyExistsException {
+ long epochBeforeWrite = cacheInvalidationEpoch.get();
try {
backend.insert(e, overwritten);
} catch (RuntimeException re) {
@@ -237,7 +240,7 @@ public class RelationalEntityStore
// does not carry, so the next read is served from the backend instead.
invalidateCache(e.nameIdentifier(), e.type());
} else {
- cache.put(e);
+ cacheIfEpochUnchanged(e, epochBeforeWrite);
}
}
@@ -267,8 +270,10 @@ public class RelationalEntityStore
return entityFromCache.get();
}
+ long epochBeforeRead = cacheInvalidationEpoch.get();
E entity = backend.get(ident, entityType);
- cache.put(entity);
+ // The SPI does not require reentrant locks. Publish under the lock already held here.
+ publishIfEpochUnchanged(entity, epochBeforeRead);
return entity;
});
}
@@ -286,35 +291,13 @@ public class RelationalEntityStore
return entity.isEmpty();
})
.toList();
- // Unlike get(), the backend read is not done under the entries' cache locks: holding one lock
- // per key across a batch DB round trip would stall unrelated reads on the same segments. So an
- // invalidation can land between the read and the write-back. The epoch sampled here detects
- // that and skips the write-back, otherwise the stale copy would survive until the TTL. The
- // per-key lock makes the check and the put atomic against an invalidation of the same key.
+ // Batch reads avoid holding multiple key locks across database I/O. Both point and batch
+ // reads use an epoch guard: ancestor invalidation can race a point read too, because ancestor
+ // and child keys need not share a segment lock.
long epochBeforeRead = cacheInvalidationEpoch.get();
List<E> fetchEntities = backend.batchGet(noCacheIdents, entityType);
for (E entity : fetchEntities) {
- if (cache instanceof BaseEntityCache && !BaseEntityCache.isCacheable(entity.type())) {
- // BaseEntityCache.put may invalidate a related entry even when it does not cache this
- // entity. Keep that hook, but avoid taking a key lock for a value that cannot be cached.
- if (cacheInvalidationEpoch.get() == epochBeforeRead) {
- cache.put(entity);
- }
- allEntities.add(entity);
- continue;
- }
- cache.withCacheLock(
- EntityCacheKey.of(entity.nameIdentifier(), entity.type()),
- () -> {
- if (cacheInvalidationEpoch.get() == epochBeforeRead) {
- cache.put(entity);
- // Invalidation of another key or an ancestor can advance the epoch while this key
- // lock is held. Remove the value if that happened during the put.
- if (cacheInvalidationEpoch.get() != epochBeforeRead) {
- cache.invalidate(entity.nameIdentifier(), entity.type());
- }
- }
- });
+ cacheIfEpochUnchanged(entity, epochBeforeRead);
allEntities.add(entity);
}
return allEntities;
@@ -667,6 +650,34 @@ public class RelationalEntityStore
}
}
+ private <E extends Entity & HasIdentifier> void cacheIfEpochUnchanged(E entity, long epoch) {
+ if (cache instanceof BaseEntityCache && !BaseEntityCache.isCacheable(entity.type())) {
+ // Uncached entities still invoke the cache's related-invalidation hook. There is no stale
+ // value to publish, and taking this entity's key lock can nest locks inside that hook.
+ cache.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);
+ 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());
+ }
+ }
+ }
+
private void invalidateCache(NameIdentifier ident, Entity.EntityType type) {
// Advance before removing, so a batchGet() that samples the epoch after this point reads the
// backend after the change that triggered the invalidation is visible.
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java
index b82faceb7e..21803b998c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java
@@ -43,6 +43,27 @@ public interface EntityChangeLogMapper {
List<EntityChangeRecord> selectEntityChanges(
@Param("lastConsumedId") long lastConsumedId, @Param("maxRows") int maxRows);
+ /**
+ * Reads a page of recent rows at or behind the incremental cursor using the database clock.
+ * Timestamp and ID together preserve page boundaries when timestamps are equal.
+ *
+ * @param afterCreatedAt exclusive timestamp/ID page cursor timestamp
+ * @param afterId exclusive timestamp/ID page cursor ID
+ * @param upperId inclusive incremental high-water ID captured at the start of the sweep
+ * @param windowMs maximum recorded created_at age in milliseconds
+ * @param maxRows maximum rows in this page
+ * @return recent records ordered by recorded created_at timestamp and ID
+ */
+ @SelectProvider(
+ type = EntityChangeLogSQLProviderFactory.class,
+ method = "selectRecentEntityChanges")
+ List<EntityChangeRecord> selectRecentEntityChanges(
+ @Param("afterCreatedAt") long afterCreatedAt,
+ @Param("afterId") long afterId,
+ @Param("upperId") long upperId,
+ @Param("windowMs") long windowMs,
+ @Param("maxRows") int maxRows);
+
@SelectProvider(type = EntityChangeLogSQLProviderFactory.class, method = "selectMaxChangeId")
Long selectMaxChangeId();
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java
index 36620bd905..2da306d61f 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java
@@ -55,6 +55,27 @@ public class EntityChangeLogSQLProviderFactory {
return getProvider().selectEntityChanges(lastConsumedId, maxRows);
}
+ /**
+ * Reads a page of recent rows at or behind the incremental cursor using the database clock.
+ * Timestamp and ID together preserve page boundaries when timestamps are equal.
+ *
+ * @param afterCreatedAt exclusive timestamp/ID page cursor timestamp
+ * @param afterId exclusive timestamp/ID page cursor ID
+ * @param upperId inclusive incremental high-water ID captured at the start of the sweep
+ * @param windowMs maximum recorded created_at age in milliseconds
+ * @param maxRows maximum rows in this page
+ * @return recent records ordered by recorded created_at timestamp and ID
+ */
+ public static String selectRecentEntityChanges(
+ @Param("afterCreatedAt") long afterCreatedAt,
+ @Param("afterId") long afterId,
+ @Param("upperId") long upperId,
+ @Param("windowMs") long windowMs,
+ @Param("maxRows") int maxRows) {
+ return getProvider()
+ .selectRecentEntityChanges(afterCreatedAt, afterId, upperId, windowMs, maxRows);
+ }
+
public static String selectMaxChangeId() {
return getProvider().selectMaxChangeId();
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java
index d5c4685efb..46610333b7 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java
@@ -39,8 +39,8 @@ public class EntityChangeLogBaseSQLProvider {
private static final String CURRENT_TIME_MILLIS_SQL = DatabaseTimeSQL.MYSQL;
/**
- * Cursor-advance contract for the entity change poller: {@code id} is monotonic and unique, so
- * callers only need to remember the last consumed id.
+ * Reads the incremental ID stream. IDs are unique but allocation order is not commit order;
+ * callers also replay recent rows to catch late commits below the cursor.
*
* <p>This table is a short-lived broadcast log for local cache invalidation, not a queue. In a
* multi-node deployment every server instance has its own local cache and should independently
@@ -58,6 +58,35 @@ public class EntityChangeLogBaseSQLProvider {
+ " WHERE id > #{lastConsumedId} ORDER BY id LIMIT #{maxRows}";
}
+ /**
+ * Reads a page of recent rows at or behind the incremental cursor using the database clock.
+ * Timestamp and ID together preserve page boundaries when timestamps are equal.
+ *
+ * @param afterCreatedAt exclusive timestamp/ID page cursor timestamp
+ * @param afterId exclusive timestamp/ID page cursor ID
+ * @param upperId inclusive incremental high-water ID captured at the start of the sweep
+ * @param windowMs maximum recorded created_at age in milliseconds
+ * @param maxRows maximum rows in this page
+ * @return recent records ordered by recorded created_at timestamp and ID
+ */
+ public String selectRecentEntityChanges(
+ @Param("afterCreatedAt") long afterCreatedAt,
+ @Param("afterId") long afterId,
+ @Param("upperId") long upperId,
+ @Param("windowMs") long windowMs,
+ @Param("maxRows") int maxRows) {
+ return "SELECT id, metalake_name as metalakeName, entity_type as entityType,"
+ + " entity_full_name as fullName, operate_type as operateType, created_at as createdAt"
+ + " FROM "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " WHERE created_at >= "
+ + currentTimeMillisSql()
+ + " - #{windowMs}"
+ + " AND id <= #{upperId}"
+ + " AND (created_at > #{afterCreatedAt} OR (created_at = #{afterCreatedAt} AND id > #{afterId}))"
+ + " ORDER BY created_at, id LIMIT #{maxRows}";
+ }
+
public String selectMaxChangeId() {
return "SELECT COALESCE(MAX(id), 0) FROM " + ENTITY_CHANGE_LOG_TABLE_NAME;
}
@@ -91,4 +120,13 @@ public class EntityChangeLogBaseSQLProvider {
+ " - #{retentionMs} LIMIT "
+ ENTITY_CHANGE_LOG_PRUNE_BATCH_SIZE;
}
+
+ /**
+ * Returns the database-specific current-time expression.
+ *
+ * @return the database-specific current-time expression in epoch milliseconds
+ */
+ protected String currentTimeMillisSql() {
+ return CURRENT_TIME_MILLIS_SQL;
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java
index 4f41fe018f..732c921751 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java
@@ -60,4 +60,10 @@ public class EntityChangeLogPostgreSQLProvider extends EntityChangeLogBaseSQLPro
+ ENTITY_CHANGE_LOG_PRUNE_BATCH_SIZE
+ ")";
}
+
+ /** {@inheritDoc} */
+ @Override
+ protected String currentTimeMillisSql() {
+ return CURRENT_TIME_MILLIS_SQL;
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
index dd4310cf18..4719912553 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
@@ -20,10 +20,14 @@ package org.apache.gravitino.authorization;
import static org.apache.gravitino.Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -160,6 +164,10 @@ public class TestAccessControlManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
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 6a3ab5cb9f..5661819242 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
@@ -20,10 +20,14 @@ package org.apache.gravitino.authorization;
import static org.apache.gravitino.Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -127,6 +131,10 @@ public class TestOwnerManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
diff --git a/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java b/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java
new file mode 100644
index 0000000000..d4b1d96a47
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/cache/TestEntityCachePublicationRace.java
@@ -0,0 +1,272 @@
+/*
+ * 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.cache;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.lang.reflect.Field;
+import java.time.Instant;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.IntStream;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.storage.relational.RelationalBackend;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+/** Deterministic regression probes for cache invalidation races. */
+public class TestEntityCachePublicationRace {
+ @Test
+ void testPointReadDoesNotReacquireSpiLockForPublication() throws Exception {
+ NonReentrantCache cache = new NonReentrantCache();
+ RelationalEntityStore store = new RelationalEntityStore();
+ RelationalBackend backend = Mockito.mock(RelationalBackend.class);
+ setField(store, RelationalEntityStore.class, "cache", cache);
+ setField(store, RelationalEntityStore.class, "backend", backend);
+ TableEntity entity = table("non_reentrant");
+ 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);
+ Mockito.verify(backend).get(entity.nameIdentifier(), EntityType.TABLE);
+ }
+
+ @Test
+ void testParentDropMustFenceAnInflightChildPointRead() throws Exception {
+ CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {});
+ RelationalEntityStore store = new RelationalEntityStore();
+ RelationalBackend backend = Mockito.mock(RelationalBackend.class);
+ setField(store, RelationalEntityStore.class, "cache", cache);
+ setField(store, RelationalEntityStore.class, "backend", backend);
+ NameIdentifier parent = NameIdentifier.of("lake", "catalog", "schema");
+ Field lockField = CaffeineEntityCache.class.getDeclaredField("segmentedLock");
+ lockField.setAccessible(true);
+ SegmentedLock locks = (SegmentedLock) lockField.get(cache);
+ // Enum identity hash codes differ across JVMs. Select keys on distinct real segments instead
+ // of assuming fixed names always exercise the ancestor/child race.
+ TableEntity old =
+ IntStream.range(0, 1000)
+ .mapToObj(i -> table("table" + i))
+ .filter(
+ t ->
+ locks.getSegmentLock(EntityCacheKey.of(parent, EntityType.SCHEMA))
+ != locks.getSegmentLock(
+ EntityCacheKey.of(t.nameIdentifier(), EntityType.TABLE)))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No distinct child cache segment"));
+ Assertions.assertNotSame(
+ locks.getSegmentLock(EntityCacheKey.of(parent, EntityType.SCHEMA)),
+ locks.getSegmentLock(EntityCacheKey.of(old.nameIdentifier(), EntityType.TABLE)));
+ CountDownLatch readOld = new CountDownLatch(1);
+ CountDownLatch finishRead = new CountDownLatch(1);
+ Mockito.when(backend.get(old.nameIdentifier(), EntityType.TABLE))
+ .thenAnswer(
+ invocation -> {
+ readOld.countDown();
+ Assertions.assertTrue(finishRead.await(10, TimeUnit.SECONDS));
+ return old;
+ });
+ ExecutorService readers = Executors.newSingleThreadExecutor();
+ try {
+ Future<TableEntity> read =
+ readers.submit(
+ () -> store.get(old.nameIdentifier(), EntityType.TABLE, TableEntity.class));
+ Assertions.assertTrue(readOld.await(10, TimeUnit.SECONDS));
+ Mockito.when(backend.delete(parent, EntityType.SCHEMA, true)).thenReturn(true);
+ Assertions.assertTrue(store.delete(parent, EntityType.SCHEMA, true));
+ finishRead.countDown();
+ read.get(10, TimeUnit.SECONDS);
+ Assertions.assertFalse(
+ cache.contains(old.nameIdentifier(), EntityType.TABLE),
+ "A child loaded before the committed parent drop must not survive its invalidation");
+ } finally {
+ finishRead.countDown();
+ readers.shutdownNow();
+ try {
+ Assertions.assertTrue(readers.awaitTermination(10, TimeUnit.SECONDS));
+ } finally {
+ cache.clear();
+ }
+ }
+ }
+
+ @Test
+ void testParentDropFencesDelayedInsertPublication() throws Exception {
+ CaffeineEntityCache cache = new CaffeineEntityCache(new Config() {});
+ RelationalEntityStore store = new RelationalEntityStore();
+ RelationalBackend backend = Mockito.mock(RelationalBackend.class);
+ setField(store, RelationalEntityStore.class, "cache", cache);
+ setField(store, RelationalEntityStore.class, "backend", backend);
+ TableEntity entity = table("inserted");
+ NameIdentifier parent = NameIdentifier.of("lake", "catalog", "schema");
+ CountDownLatch insertionCompleted = new CountDownLatch(1);
+ CountDownLatch returnFromInsert = new CountDownLatch(1);
+ Mockito.doAnswer(
+ invocation -> {
+ insertionCompleted.countDown();
+ Assertions.assertTrue(returnFromInsert.await(10, TimeUnit.SECONDS));
+ return null;
+ })
+ .when(backend)
+ .insert(entity, false);
+ Mockito.when(backend.delete(parent, EntityType.SCHEMA, true)).thenReturn(true);
+ ExecutorService writer = Executors.newSingleThreadExecutor();
+ try {
+ Future<?> write =
+ writer.submit(
+ () -> {
+ store.put(entity, false);
+ return null;
+ });
+ Assertions.assertTrue(insertionCompleted.await(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(store.delete(parent, EntityType.SCHEMA, true));
+ returnFromInsert.countDown();
+ write.get(10, TimeUnit.SECONDS);
+ Assertions.assertFalse(cache.contains(entity.nameIdentifier(), EntityType.TABLE));
+ } finally {
+ returnFromInsert.countDown();
+ writer.shutdownNow();
+ try {
+ Assertions.assertTrue(writer.awaitTermination(10, TimeUnit.SECONDS));
+ } finally {
+ cache.clear();
+ }
+ }
+ }
+
+ @Test
+ void testInvalidationDuringPublicationRemovesJustCachedValue() throws Exception {
+ PublicationHookCache cache = new PublicationHookCache();
+ RelationalEntityStore store = new RelationalEntityStore();
+ RelationalBackend backend = Mockito.mock(RelationalBackend.class);
+ setField(store, RelationalEntityStore.class, "cache", cache);
+ setField(store, RelationalEntityStore.class, "backend", backend);
+ NameIdentifier parent = NameIdentifier.of("lake", "catalog", "schema");
+ Field lockField = CaffeineEntityCache.class.getDeclaredField("segmentedLock");
+ lockField.setAccessible(true);
+ SegmentedLock locks = (SegmentedLock) lockField.get(cache);
+ TableEntity entity =
+ IntStream.range(0, 1000)
+ .mapToObj(i -> table("published" + i))
+ .filter(
+ t ->
+ locks.getSegmentLock(EntityCacheKey.of(parent, EntityType.SCHEMA))
+ != locks.getSegmentLock(
+ EntityCacheKey.of(t.nameIdentifier(), EntityType.TABLE)))
+ .findFirst()
+ .orElseThrow();
+ Mockito.when(backend.get(entity.nameIdentifier(), EntityType.TABLE)).thenReturn(entity);
+ Mockito.when(backend.delete(parent, EntityType.SCHEMA, true)).thenReturn(true);
+ cache.beforePut =
+ () -> {
+ try {
+ Assertions.assertTrue(store.delete(parent, EntityType.SCHEMA, true));
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ };
+ try {
+ Assertions.assertSame(
+ entity, store.get(entity.nameIdentifier(), EntityType.TABLE, TableEntity.class));
+ Assertions.assertFalse(cache.contains(entity.nameIdentifier(), EntityType.TABLE));
+ } finally {
+ cache.clear();
+ }
+ }
+
+ private static TableEntity table(String name) {
+ return TableEntity.builder()
+ .withId(123L)
+ .withName(name)
+ .withNamespace(Namespace.of("lake", "catalog", "schema"))
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ private static void setField(Object instance, Class<?> clazz, String name, Object value)
+ throws Exception {
+ Field field = clazz.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(instance, value);
+ }
+
+ private static class NonReentrantCache extends NoOpsCache {
+ private final Semaphore lock = new Semaphore(1);
+ private int acquisitions;
+
+ private NonReentrantCache() {
+ super(new Config() {});
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public <T, E extends Exception> T withCacheLock(
+ EntityCacheKey key, ThrowingSupplier<T, E> action) throws E {
+ // Fail immediately rather than hanging the suite when the caller tries to reenter.
+ Assertions.assertTrue(lock.tryAcquire(), "EntityCache SPI lock was acquired recursively");
+ acquisitions++;
+ try {
+ return action.get();
+ } finally {
+ lock.release();
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public <E extends Exception> void withCacheLock(EntityCacheKey key, ThrowingRunnable<E> action)
+ throws E {
+ withCacheLock(
+ key,
+ () -> {
+ action.run();
+ return null;
+ });
+ }
+ }
+
+ private static class PublicationHookCache extends CaffeineEntityCache {
+ private Runnable beforePut = () -> {};
+
+ private PublicationHookCache() {
+ super(new Config() {});
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected <E extends Entity & HasIdentifier> void doPut(E entity) {
+ beforePut.run();
+ super.doPut(entity);
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
index 056385102f..7de1473af1 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogChangeLogListener.java
@@ -18,7 +18,6 @@
*/
package org.apache.gravitino.catalog;
-import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -46,29 +45,20 @@ public class TestCatalogChangeLogListener {
CatalogManager catalogManager = mock(CatalogManager.class);
Cache<NameIdentifier, CatalogWrapper> catalogCache = mock(Cache.class);
NameIdentifier failing = NameIdentifier.of("metalake", "failing");
- NameIdentifier laterLocal = NameIdentifier.of("metalake", "later_local");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(failing)).thenReturn(false);
- when(catalogManager.consumeLocalMutation(laterLocal)).thenReturn(true);
doThrow(new RuntimeException("eviction failed")).when(catalogCache).invalidate(failing);
doThrow(new RuntimeException("clear failed")).when(catalogCache).invalidateAll();
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
- // There is nothing else we can do here, so let the exception go up. That is fine now: the
- // poller only logs it and never sends the batch again. Re-sending was the dangerous part,
- // because consumeLocalMutation() works only once and a second pass would mistake a change made
- // by this node for one made by another node.
+ // Preserve whole-cache recovery failures for the poller's error log.
Assertions.assertThrows(
RuntimeException.class,
() ->
listener.onEntityChange(
List.of(change(1L, "metalake.failing"), change(2L, "metalake.later_local"))));
- // The "made by this node" marks are all read before any removal starts, even when both the
- // removal and the clear fail.
- verify(catalogManager).consumeLocalMutation(laterLocal);
verify(catalogCache).invalidateAll();
}
@@ -82,9 +72,6 @@ public class TestCatalogChangeLogListener {
NameIdentifier laterLocal = NameIdentifier.of("metalake", "later_local");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(failing)).thenReturn(false);
- when(catalogManager.consumeLocalMutation(laterRemote)).thenReturn(false);
- when(catalogManager.consumeLocalMutation(laterLocal)).thenReturn(true);
doThrow(new RuntimeException("eviction failed")).when(catalogCache).invalidate(failing);
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
@@ -97,9 +84,7 @@ public class TestCatalogChangeLogListener {
change(2L, "metalake.later_remote"),
change(3L, "metalake.later_local"))));
- // The later local mark is read before any removal starts. Clearing the whole cache then covers
- // both the removal that failed and every remote record, so nothing else has to be removed.
- verify(catalogManager).consumeLocalMutation(laterLocal);
+ // Whole-cache recovery covers the failed removal and the rest of the batch.
verify(catalogCache).invalidateAll();
verify(catalogCache, never()).invalidate(laterRemote);
verify(catalogCache, never()).invalidate(laterLocal);
@@ -114,7 +99,6 @@ public class TestCatalogChangeLogListener {
NameIdentifier second = NameIdentifier.of("metalake", "cat2");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(any())).thenReturn(false);
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
@@ -122,8 +106,7 @@ public class TestCatalogChangeLogListener {
verify(catalogCache).invalidate(first);
verify(catalogCache).invalidate(second);
- // Clearing closes IsolatedClassLoaders that are still in use, so it must never happen during
- // normal operation.
+ // Successful targeted eviction does not need whole-cache recovery.
verify(catalogCache, never()).invalidateAll();
}
@@ -135,7 +118,6 @@ public class TestCatalogChangeLogListener {
NameIdentifier healthy = NameIdentifier.of("metalake", "healthy");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(any())).thenReturn(false);
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
@@ -155,40 +137,12 @@ public class TestCatalogChangeLogListener {
@Test
@SuppressWarnings("unchecked")
- void testFailedLocalMutationProbeTreatsTheRecordAsRemote() {
- CatalogManager catalogManager = mock(CatalogManager.class);
- Cache<NameIdentifier, CatalogWrapper> catalogCache = mock(Cache.class);
- NameIdentifier failing = NameIdentifier.of("metalake", "failing");
- NameIdentifier healthy = NameIdentifier.of("metalake", "healthy");
-
- when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(failing))
- .thenThrow(new RuntimeException("probe failed"));
- when(catalogManager.consumeLocalMutation(healthy)).thenReturn(false);
-
- CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
-
- // When we cannot tell which node made the change, assume another node did. Removing one entry
- // for nothing is cheaper than missing a real remote change, which we would never see again.
- Assertions.assertDoesNotThrow(
- () ->
- listener.onEntityChange(
- List.of(change(1L, "metalake.failing"), change(2L, "metalake.healthy"))));
-
- verify(catalogCache).invalidate(failing);
- verify(catalogCache).invalidate(healthy);
- verify(catalogCache, never()).invalidateAll();
- }
-
- @Test
- @SuppressWarnings("unchecked")
- void testSkipsLocalMutationAndNonCatalogRecords() {
+ void testInvalidatesLocalCatalogAndSkipsNonCatalogRecords() {
CatalogManager catalogManager = mock(CatalogManager.class);
Cache<NameIdentifier, CatalogWrapper> catalogCache = mock(Cache.class);
NameIdentifier localIdentifier = NameIdentifier.of("metalake", "local");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(localIdentifier)).thenReturn(true);
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
@@ -202,7 +156,9 @@ public class TestCatalogChangeLogListener {
new EntityChangeRecord(
4L, "metalake", "SCHEMA", "metalake.cat.sch", OperateType.ALTER, 0L))));
- verify(catalogCache, never()).invalidate(any());
+ verify(catalogCache).invalidate(localIdentifier);
+ verify(catalogCache, never()).invalidate(NameIdentifier.of("metalake", "cat"));
+ verify(catalogCache, never()).invalidateAll();
}
@Test
@@ -227,7 +183,6 @@ public class TestCatalogChangeLogListener {
NameIdentifier healthy = NameIdentifier.of("metalake", "healthy");
when(catalogManager.getCatalogCache()).thenReturn(catalogCache);
- when(catalogManager.consumeLocalMutation(any())).thenReturn(false);
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
index 0515edfdab..6a9bdb9bb5 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
@@ -1002,7 +1002,63 @@ public class TestCatalogManager {
}
@Test
- void testCatalogChangeLogListenerSkipsInvalidationForLocalMutation() throws Exception {
+ void testPollBeforeLocalMutationReturnsDoesNotMaskRemoteMutation() throws Exception {
+ ChangeLogAwareEntityStore store = Mockito.spy(new ChangeLogAwareEntityStore());
+ store.initialize(config);
+ store.put(metalakeEntity, true);
+ CatalogManager manager =
+ new CatalogManager(config, store, new RandomIdGenerator(), new SecretManager(config));
+ NameIdentifier ident = NameIdentifier.of("metalake", "late_local_marker");
+ Map<String, String> props =
+ ImmutableMap.of(
+ PROPERTY_KEY1, "value1", PROPERTY_KEY2, "value2", PROPERTY_KEY5_PREFIX + "1", "value3");
+ try {
+ manager.createCatalog(ident, Catalog.Type.RELATIONAL, provider, "comment", props);
+ Mockito.doAnswer(
+ invocation -> {
+ Object result = invocation.callRealMethod();
+ // The transaction has completed but CatalogManager's mutation caller has not
+ // returned.
+ store
+ .listener
+ .get()
+ .onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L,
+ "metalake",
+ "CATALOG",
+ ident.toString(),
+ OperateType.ALTER,
+ 0L)));
+ return result;
+ })
+ .when(store)
+ .update(
+ Mockito.eq(ident),
+ Mockito.eq(CatalogEntity.class),
+ Mockito.eq(EntityType.CATALOG),
+ Mockito.any());
+ manager.alterCatalog(ident, CatalogChange.updateComment("changed"));
+ Assertions.assertNotNull(manager.loadCatalogAndWrap(ident));
+ Assertions.assertNotNull(manager.getCatalogCache().getIfPresent(ident));
+ store
+ .listener
+ .get()
+ .onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 2L, "metalake", "CATALOG", ident.toString(), OperateType.ALTER, 0L)));
+ Assertions.assertNull(
+ manager.getCatalogCache().getIfPresent(ident),
+ "A late local marker must not suppress the next remote mutation");
+ } finally {
+ manager.close();
+ }
+ }
+
+ @Test
+ void testCatalogChangeLogListenerInvalidatesLocalMutation() throws Exception {
NameIdentifier ident = NameIdentifier.of("metalake", "change_log_local");
Map<String, String> props =
ImmutableMap.of(
@@ -1019,21 +1075,15 @@ public class TestCatalogManager {
Assertions.assertNotNull(catalogManager.loadCatalogAndWrap(ident));
Assertions.assertNotNull(catalogManager.getCatalogCache().getIfPresent(ident));
- // Enable local-mutation tracking, which a CatalogManager backed by a change-log-aware store
- // would have turned on in its constructor. The in-memory store used here does not support a
- // change log, so set it explicitly.
- catalogManager.setTrackLocalMutations(true);
- catalogManager.markLocalMutation(ident);
-
CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
listener.onEntityChange(
List.of(
new EntityChangeRecord(
1L, "metalake", "CATALOG", "metalake.change_log_local", OperateType.ALTER, 0L)));
- Assertions.assertNotNull(
+ Assertions.assertNull(
catalogManager.getCatalogCache().getIfPresent(ident),
- "Cache should NOT be invalidated for local mutations");
+ "Local events must not suppress catalog invalidation");
}
@Test
@@ -1160,7 +1210,7 @@ public class TestCatalogManager {
}
@Test
- void testFailedCreateCatalogCleanupMarksLocalMutation() throws Exception {
+ void testFailedCreateCleanupAndSubsequentAlterInvalidateRecreatedCatalog() throws Exception {
ChangeLogAwareEntityStore store = new ChangeLogAwareEntityStore();
store.initialize(config);
store.put(metalakeEntity, true);
@@ -1195,13 +1245,8 @@ public class TestCatalogManager {
Assertions.assertNotNull(manager.loadCatalogAndWrap(ident));
Assertions.assertNotNull(manager.getCatalogCache().getIfPresent(ident));
- // Simulate a subsequent local mutation (e.g. disableCatalog) that writes an ALTER record.
- manager.markLocalMutation(ident);
-
- // The poller delivers both records in one batch: the DROP from the failed-create cleanup and
- // the ALTER from the local mutation. The cleanup DROP must carry its own local-mutation token
- // (the fix); otherwise it consumes the ALTER's token, the ALTER is treated as remote, and the
- // in-use cached wrapper is spuriously invalidated and asynchronously closed.
+ // Cleanup DROP and subsequent ALTER both invalidate the recreated entry. No local marker
+ // may suppress either record; active operations remain protected by CatalogLease.
store
.listener
.get()
@@ -1222,10 +1267,9 @@ public class TestCatalogManager {
OperateType.ALTER,
0L)));
- Assertions.assertNotNull(
+ Assertions.assertNull(
manager.getCatalogCache().getIfPresent(ident),
- "Cache should NOT be invalidated: the failed-create cleanup DROP must be tracked as a "
- + "local mutation so it does not steal the token meant for the later ALTER");
+ "Cleanup and alter records must conservatively invalidate a recreated catalog");
manager.close();
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogMutationMarkerRace.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogMutationMarkerRace.java
new file mode 100644
index 0000000000..6cfdfc0c89
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogMutationMarkerRace.java
@@ -0,0 +1,70 @@
+/*
+ * 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.catalog;
+
+import java.util.List;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.CatalogManager.CatalogWrapper;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+/** Regression probe for catalog mutation markers published after the change-log commit. */
+public class TestCatalogMutationMarkerRace {
+ @Test
+ void testLocalRemoteAndRepeatedEventsAlwaysInvalidateReloadedCatalog() {
+ CatalogManager manager = new CatalogManager(new Config() {}, null, null, null);
+ CatalogChangeLogListener listener = new CatalogChangeLogListener(manager);
+ NameIdentifier ident = NameIdentifier.of("lake", "catalog");
+ CatalogWrapper versionOne = Mockito.mock(CatalogWrapper.class);
+ CatalogWrapper versionTwo = Mockito.mock(CatalogWrapper.class);
+ try {
+ manager.getCatalogCache().put(ident, versionOne);
+ // Consumption may run before the local mutation caller has returned.
+ listener.onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L, "lake", "CATALOG", ident.toString(), OperateType.ALTER, 0L)));
+ Assertions.assertNull(manager.getCatalogCache().getIfPresent(ident));
+ // The writer reloads its new catalog after its event was consumed.
+ manager.getCatalogCache().put(ident, versionTwo);
+ // A different node now changes the same catalog. This is not a local mutation.
+ listener.onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 2L, "lake", "CATALOG", ident.toString(), OperateType.ALTER, 0L)));
+ Assertions.assertNull(
+ manager.getCatalogCache().getIfPresent(ident),
+ "A previously consumed local event must not mask a future remote event");
+ manager.getCatalogCache().put(ident, versionTwo);
+ listener.onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L, "lake", "CATALOG", ident.toString(), OperateType.ALTER, 0L)));
+ Assertions.assertNull(
+ manager.getCatalogCache().getIfPresent(ident),
+ "Replayed events must conservatively invalidate a reloaded catalog too");
+ } finally {
+ manager.close();
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java
index 5bdfc09d5b..a27c626497 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogWrapperLease.java
@@ -50,6 +50,7 @@ import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.memory.TestMemoryEntityStore;
import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;
+import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.utils.ClassLoaderPool;
@@ -132,7 +133,26 @@ public class TestCatalogWrapperLease {
CatalogWrapper wrapper = lease.wrapper();
Assertions.assertEquals(1, wrapper.activeOperations());
- catalogManager.getCatalogCache().invalidate(ident);
+ CatalogChangeLogListener listener = new CatalogChangeLogListener(catalogManager);
+ listener.onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L,
+ METALAKE,
+ "CATALOG",
+ EntityChangeLogNameIdentifierCodec.encode(ident),
+ OperateType.ALTER,
+ 0L)));
+ // Repeated delivery must be safe while the operation is still using the retired wrapper.
+ listener.onEntityChange(
+ List.of(
+ new EntityChangeRecord(
+ 1L,
+ METALAKE,
+ "CATALOG",
+ EntityChangeLogNameIdentifierCodec.encode(ident),
+ OperateType.ALTER,
+ 0L)));
// Caffeine runs the removal listener asynchronously, so wait for the retirement to land.
await().atMost(Duration.ofSeconds(10)).until(wrapper::isRetired);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
index c1622ab676..f8b4843656 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
@@ -20,10 +20,14 @@ package org.apache.gravitino.hook;
import static org.apache.gravitino.Configs.CATALOG_CACHE_EVICTION_INTERVAL_MS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -252,6 +256,10 @@ public class TestFilesetHookDispatcher extends TestOperationDispatcher {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
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 5b2f956a6c..8153929910 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -20,10 +20,14 @@
package org.apache.gravitino.policy;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -261,6 +265,10 @@ public class TestPolicyManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
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 c18104df6e..862effb935 100644
--- a/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
+++ b/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
@@ -20,10 +20,14 @@
package org.apache.gravitino.stats;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -122,6 +126,10 @@ public class TestStatisticManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
diff --git a/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java b/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
index f49c550f4e..b62d01b743 100644
--- a/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
+++ b/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
@@ -20,10 +20,14 @@
package org.apache.gravitino.storage;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -161,6 +165,10 @@ abstract class AbstractEntityStorageTest {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestCacheCommitOrdering.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestCacheCommitOrdering.java
new file mode 100644
index 0000000000..89832946e5
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestCacheCommitOrdering.java
@@ -0,0 +1,119 @@
+/*
+ * 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;
+
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.spy;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.cache.CaffeineEntityCache;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Regression probe for change-log identity allocation versus transaction commit order. */
+public class TestCacheCommitOrdering extends TestJDBCBackend {
+ @TestTemplate
+ void testLowerChangeIdCommittedLateMustReachPeerCache() throws Exception {
+ createParentEntities("lake", "order_catalog", "schema", AUDIT_INFO);
+ Namespace namespace = Namespace.of("lake", "order_catalog", "schema");
+ createAndInsertSchema("lake", "order_catalog", "fast_schema");
+ Namespace fastNamespace = Namespace.of("lake", "order_catalog", "fast_schema");
+ TableEntity slow =
+ createTableEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "slow", AUDIT_INFO);
+ TableEntity fast =
+ createTableEntity(RandomIdGenerator.INSTANCE.nextId(), fastNamespace, "fast", AUDIT_INFO);
+ backend.insert(slow, false);
+ backend.insert(fast, false);
+ CaffeineEntityCache peer = new CaffeineEntityCache(new Config() {});
+ peer.put(slow);
+ peer.put(fast);
+ // The hour-long poll interval also spaces replay sweeps an hour apart; skip ahead before the
+ // polls that must start a new sweep after the late commit.
+ AtomicLong clockOffset = new AtomicLong();
+ EntityChangeLogPoller poller = spy(new EntityChangeLogPoller(3600));
+ doAnswer(ignored -> System.nanoTime() + clockOffset.get()).when(poller).nanoTime();
+ poller.registerListener(new EntityCacheChangeLogListener(peer));
+ poller.start();
+ CountDownLatch insertedLowId = new CountDownLatch(1);
+ CountDownLatch commitSlow = new CountDownLatch(1);
+ ExecutorService writer = Executors.newSingleThreadExecutor();
+ try {
+ Future<?> transaction =
+ writer.submit(
+ () -> {
+ SessionUtils.beginTransaction();
+ boolean committed = false;
+ try {
+ backend.update(
+ slow.nameIdentifier(),
+ EntityType.TABLE,
+ entity ->
+ createTableEntity(slow.id(), namespace, "slow_renamed", AUDIT_INFO));
+ insertedLowId.countDown();
+ Assertions.assertTrue(commitSlow.await(15, TimeUnit.SECONDS));
+ SessionUtils.commitTransaction();
+ committed = true;
+ return null;
+ } finally {
+ if (!committed) {
+ SessionUtils.rollbackTransaction();
+ }
+ }
+ });
+ Assertions.assertTrue(insertedLowId.await(15, TimeUnit.SECONDS));
+ backend.update(
+ fast.nameIdentifier(),
+ EntityType.TABLE,
+ entity -> createTableEntity(fast.id(), fastNamespace, "fast_renamed", AUDIT_INFO));
+ poller.pollChanges();
+ Assertions.assertFalse(peer.contains(fast.nameIdentifier(), EntityType.TABLE));
+ Assertions.assertTrue(peer.contains(slow.nameIdentifier(), EntityType.TABLE));
+ commitSlow.countDown();
+ transaction.get(15, TimeUnit.SECONDS);
+ Assertions.assertFalse(backend.exists(slow.nameIdentifier(), EntityType.TABLE));
+ clockOffset.set(TimeUnit.HOURS.toNanos(2));
+ for (int i = 0; i < 3; i++) {
+ poller.pollChanges();
+ }
+ Assertions.assertFalse(
+ peer.contains(slow.nameIdentifier(), EntityType.TABLE),
+ "A committed low-ID invalidation must not be skipped after consuming a higher ID");
+ } finally {
+ commitSlow.countDown();
+ writer.shutdownNow();
+ try {
+ Assertions.assertTrue(writer.awaitTermination(15, TimeUnit.SECONDS));
+ } finally {
+ poller.close();
+ peer.clear();
+ }
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogPoller.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogPoller.java
index 2b086f2f61..9d6024b3a2 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogPoller.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestEntityChangeLogPoller.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.storage.relational;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
@@ -28,6 +29,7 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -35,6 +37,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -49,11 +52,18 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
+import org.apache.gravitino.Configs;
import org.apache.gravitino.metrics.source.EntityChangeLogMetricsSource;
import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -63,6 +73,574 @@ import org.mockito.MockedStatic;
public class TestEntityChangeLogPoller {
private static final int MAX_ROWS = 2000;
+ // max(pollIntervalSecs = 1, default replayWindowSecs = 60 / 4): the gap between sweep starts.
+ private static final long SWEEP_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(15);
+
+ @Test
+ void testDefaultPollingKeepsIncrementalEventWithinSixSecondsWithReplayWork()
+ throws InterruptedException {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
+ AtomicLong clockMillis = new AtomicLong();
+ AtomicLong committedAt = new AtomicLong(-1);
+ AtomicLong deliveredAt = new AtomicLong(-1);
+ AtomicReference<Runnable> nextPoll = new AtomicReference<>();
+ AtomicLong nextDelayMillis = new AtomicLong();
+ AtomicInteger incrementalQueries = new AtomicInteger();
+ when(mapper.selectMaxChangeId()).thenReturn(1L, 2L);
+ when(mapper.selectEntityChanges(anyLong(), anyInt()))
+ .thenAnswer(
+ invocation -> {
+ // Commit just after the previous query's snapshot: this poll cannot see the row.
+ boolean first = incrementalQueries.getAndIncrement() == 0;
+ if (first) {
+ committedAt.set(clockMillis.get());
+ }
+ clockMillis.addAndGet(900);
+ return first ? List.of() : changes(2, 2);
+ });
+ when(mapper.selectRecentEntityChanges(anyLong(), anyLong(), anyLong(), anyLong(), anyInt()))
+ .thenAnswer(
+ invocation -> {
+ clockMillis.addAndGet(900);
+ return changes(1, 1);
+ });
+ when(scheduler.awaitTermination(anyLong(), any())).thenReturn(true);
+ doAnswer(
+ invocation -> {
+ nextPoll.set(invocation.getArgument(0));
+ TimeUnit unit = invocation.getArgument(2);
+ nextDelayMillis.set(unit.toMillis(invocation.getArgument(1)));
+ return mock(ScheduledFuture.class);
+ })
+ .when(scheduler)
+ .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ // A 12s window makes the sweep interval equal the 3s poll interval, so every cycle replays:
+ // the worst case for incremental delivery under the default poll interval and batch size.
+ EntityChangeLogPoller poller =
+ spy(
+ new EntityChangeLogPoller(
+ Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS,
+ Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE,
+ 12,
+ Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES,
+ new EntityChangeLogMetricsSource()));
+ doReturn(scheduler).when(poller).createScheduler();
+ doAnswer(invocation -> TimeUnit.MILLISECONDS.toNanos(clockMillis.get()))
+ .when(poller)
+ .nanoTime();
+ poller.registerListener(
+ records -> {
+ if (records.stream().anyMatch(record -> record.getId() == 2)) {
+ deliveredAt.set(clockMillis.get());
+ }
+ });
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ try {
+ poller.start();
+ for (int cycle = 0; cycle < 2; cycle++) {
+ Assertions.assertEquals(3000, nextDelayMillis.get());
+ clockMillis.addAndGet(nextDelayMillis.get());
+ nextPoll.get().run();
+ }
+ // The original incremental pull and one added replay page each take less than a second.
+ // Assert delivery before the second replay page finishes, not just eventual delivery.
+ Assertions.assertEquals(5700, deliveredAt.get() - committedAt.get());
+ Assertions.assertTrue(deliveredAt.get() - committedAt.get() < 6000);
+ verify(mapper, times(2))
+ .selectRecentEntityChanges(anyLong(), anyLong(), anyLong(), anyLong(), anyInt());
+ } finally {
+ poller.close();
+ }
+ }
+ }
+
+ @Test
+ void testReplayRecoversLateLowerIdWithoutMovingCursorBackOrRedelivering() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ EntityChangeRecord late =
+ new EntityChangeRecord(1, "ml1", "TABLE", "ml1.cat.schema.late", OperateType.DROP, 100);
+ EntityChangeRecord fast =
+ new EntityChangeRecord(2, "ml1", "TABLE", "ml1.cat.schema.fast", OperateType.ALTER, 200);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(List.of(fast));
+ when(mapper.selectEntityChanges(2, 2)).thenReturn(List.of());
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2))
+ .thenReturn(List.of(fast), List.of(late, fast), List.of(late, fast));
+ when(mapper.selectRecentEntityChanges(200, 2, 2, 60000, 2)).thenReturn(List.of());
+ List<EntityChangeRecord> received = new ArrayList<>();
+ EntityChangeLogMetricsSource metrics = new EntityChangeLogMetricsSource();
+ AtomicLong clock = new AtomicLong();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller = spy(new EntityChangeLogPoller(1, 2, metrics));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ Assertions.assertFalse(poller.pollChanges());
+ clock.addAndGet(SWEEP_INTERVAL_NANOS);
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertFalse(poller.pollChanges());
+ clock.addAndGet(SWEEP_INTERVAL_NANOS);
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertEquals(List.of(2L, 1L), ids(received));
+ Assertions.assertEquals(
+ 2L, metrics.getMetricRegistry().getGauges().get("cursor-id").getValue());
+ Assertions.assertEquals(
+ 1L, metrics.getMetricRegistry().getCounters().get("replay-records-total").getCount());
+ }
+ }
+
+ @Test
+ void testReplayPagesEqualTimestampsAndRestartsForLaterVisibleRows() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(4, 4));
+ when(mapper.selectEntityChanges(4, 2)).thenReturn(List.of());
+ when(mapper.selectRecentEntityChanges(-1, 0, 4, 60000, 2))
+ .thenReturn(changes(2, 3), changes(1, 2));
+ when(mapper.selectRecentEntityChanges(0, 3, 4, 60000, 2)).thenReturn(changes(4, 4));
+ List<EntityChangeRecord> received = new ArrayList<>();
+ AtomicLong clock = new AtomicLong();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ Assertions.assertTrue(poller.pollChanges());
+ // The second page continues the sweep at once even though no sweep interval has passed.
+ Assertions.assertFalse(poller.pollChanges());
+ clock.addAndGet(SWEEP_INTERVAL_NANOS);
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertEquals(List.of(4L, 2L, 3L, 1L), ids(received));
+ verify(mapper).selectRecentEntityChanges(0, 3, 4, 60000, 2);
+ }
+ }
+
+ @Test
+ void testReplayFailureDoesNotBlockIncrementalDeliveryOrRetryNewRows() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 1));
+ when(mapper.selectEntityChanges(1, 2)).thenReturn(changes(2, 2));
+ when(mapper.selectRecentEntityChanges(-1, 0, 1, 60000, 2))
+ .thenThrow(new IllegalStateException("replay unavailable"))
+ .thenReturn(changes(1, 1));
+ List<EntityChangeRecord> received = new ArrayList<>();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ AtomicLong clock = new AtomicLong();
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ Assertions.assertFalse(poller.pollChanges());
+ clock.set(TimeUnit.SECONDS.toNanos(1));
+ Assertions.assertFalse(poller.pollChanges());
+ Assertions.assertEquals(List.of(1L, 2L), ids(received));
+ verify(mapper, times(2)).selectRecentEntityChanges(-1, 0, 1, 60000, 2);
+ }
+ }
+
+ @Test
+ void testReplayFailureIsRateLimitedWhileIncrementalBacklogDrains() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 2));
+ when(mapper.selectEntityChanges(2, 2)).thenReturn(changes(3, 4));
+ when(mapper.selectEntityChanges(4, 2)).thenReturn(List.of());
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2))
+ .thenThrow(new IllegalStateException("replay unavailable"));
+ AtomicLong clock = new AtomicLong();
+ List<EntityChangeRecord> received = new ArrayList<>();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertTrue(poller.pollChanges());
+ verify(mapper).selectRecentEntityChanges(-1, 0, 2, 60000, 2);
+ Assertions.assertEquals(List.of(1L, 2L, 3L, 4L), ids(received));
+ clock.set(TimeUnit.SECONDS.toNanos(1));
+ Assertions.assertFalse(poller.pollChanges());
+ verify(mapper, times(2)).selectRecentEntityChanges(-1, 0, 2, 60000, 2);
+ }
+ }
+
+ @Test
+ void testCapacityWarningsAreRateLimitedAndCountSuppressedEvictions() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 2));
+ when(mapper.selectEntityChanges(2, 2)).thenReturn(changes(3, 4));
+ when(mapper.selectEntityChanges(4, 2)).thenReturn(changes(5, 6));
+ AtomicLong clock = new AtomicLong();
+ List<LogEvent> logs =
+ captureReplayLogs(
+ () -> {
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, 60, 1, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.pollChanges();
+ poller.pollChanges();
+ clock.set(TimeUnit.SECONDS.toNanos(1));
+ poller.pollChanges();
+ }
+ });
+ List<String> warnings =
+ logs.stream()
+ .map(e -> e.getMessage().getFormattedMessage())
+ .filter(m -> m.contains("dedup capacity reached"))
+ .toList();
+ Assertions.assertEquals(2, warnings.size());
+ Assertions.assertTrue(warnings.get(0).contains("evictedIds=1"));
+ Assertions.assertTrue(warnings.get(1).contains("evictedIds=4"));
+ }
+
+ @Test
+ void testDisabledReplayDoesNotQueryRecentHistory() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 1));
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ new EntityChangeLogPoller(1, 2, 0, 1, new EntityChangeLogMetricsSource());
+ Assertions.assertFalse(poller.pollChanges());
+ verify(mapper, never())
+ .selectRecentEntityChanges(anyLong(), anyLong(), anyLong(), anyLong(), anyInt());
+ }
+ }
+
+ @Test
+ void testCapacityEvictionAllowsRedeliveryWithoutSkippingUnknownEvents() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 2));
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2)).thenReturn(changes(1, 1));
+ List<EntityChangeRecord> received = new ArrayList<>();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ new EntityChangeLogPoller(1, 2, 60, 1, new EntityChangeLogMetricsSource());
+ poller.registerListener(replayListener(received));
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertEquals(List.of(1L, 2L, 1L), ids(received));
+ }
+ }
+
+ @Test
+ void testDedupExpiresUsingMonotonicClock() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 1));
+ when(mapper.selectRecentEntityChanges(-1, 0, 1, 1000, 2)).thenReturn(changes(1, 1));
+ AtomicLong clock = new AtomicLong();
+ List<EntityChangeRecord> received = new ArrayList<>();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, 1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ poller.pollChanges();
+ clock.set(TimeUnit.SECONDS.toNanos(2));
+ poller.pollChanges();
+ Assertions.assertEquals(List.of(1L, 1L), ids(received));
+ }
+ }
+
+ @Test
+ void testReplayDiagnosticsExposeEventAndFailureContext() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(2, 2));
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2))
+ .thenReturn(changes(1, 1))
+ .thenThrow(new IllegalStateException("replay database unavailable"));
+ AtomicLong clock = new AtomicLong();
+ EntityChangeLogMetricsSource metrics = new EntityChangeLogMetricsSource();
+ List<LogEvent> logs =
+ captureReplayLogs(
+ () -> {
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller = spy(new EntityChangeLogPoller(1, 2, metrics));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.pollChanges();
+ clock.addAndGet(SWEEP_INTERVAL_NANOS);
+ poller.pollChanges();
+ }
+ });
+ Assertions.assertEquals(
+ 1L, metrics.getMetricRegistry().getCounters().get("replay-failures-total").getCount());
+ Assertions.assertEquals(
+ 0L, metrics.getMetricRegistry().getCounters().get("poll-failures-total").getCount());
+ String diagnostics =
+ logs.stream()
+ .map(e -> e.getMessage().getFormattedMessage())
+ .collect(Collectors.joining("\n"));
+ Assertions.assertTrue(diagnostics.contains("cursor=2"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("changeId=1"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("entityType=TABLE"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("fullName=ml1.cat1.schema1.table1"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("operation=ALTER"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("createdAt=0"), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("approximateAgeMs="), diagnostics);
+ Assertions.assertTrue(diagnostics.contains("windowMs=60000"), diagnostics);
+ Assertions.assertTrue(
+ diagnostics.contains("possible late commit, startup history, or dedup eviction"),
+ diagnostics);
+ Assertions.assertTrue(diagnostics.contains("replay failed cursor=2"), diagnostics);
+ Assertions.assertTrue(
+ logs.stream().anyMatch(e -> e.getThrown() instanceof IllegalStateException));
+ }
+
+ @Test
+ void testReplayStartupIncludesLowerIdsAndCapacityWarning() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectMaxChangeId()).thenReturn(3L);
+ when(mapper.selectRecentEntityChanges(-1, 0, 3, 60000, 2)).thenReturn(changes(1, 2));
+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
+ List<EntityChangeRecord> received = new ArrayList<>();
+ List<LogEvent> logs =
+ captureReplayLogs(
+ () -> {
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, 60, 1, new EntityChangeLogMetricsSource()));
+ doReturn(scheduler).when(poller).createScheduler();
+ poller.registerListener(replayListener(received));
+ try {
+ poller.start();
+ Assertions.assertTrue(poller.pollChanges());
+ Assertions.assertEquals(List.of(1L, 2L), ids(received));
+ } finally {
+ poller.close();
+ }
+ }
+ });
+ String diagnostics =
+ logs.stream()
+ .map(e -> e.getMessage().getFormattedMessage())
+ .collect(Collectors.joining("\n"));
+ Assertions.assertTrue(diagnostics.contains("startupCursor=3"), diagnostics);
+ Assertions.assertTrue(
+ diagnostics.contains("dedup capacity reached cursor=3 evictedIds=1 maxEntries=1"),
+ diagnostics);
+ // Startup history is expected after every restart, so it must not raise the late-commit WARN.
+ Assertions.assertTrue(
+ logs.stream()
+ .anyMatch(
+ e ->
+ Level.INFO.equals(e.getLevel())
+ && e.getMessage()
+ .getFormattedMessage()
+ .contains("startup replay delivered 2 recent record(s)")),
+ diagnostics);
+ Assertions.assertFalse(diagnostics.contains("replay found"), diagnostics);
+ }
+
+ @Test
+ void testFailedReplayPageResumesFromSavedPageCursor() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(5, 5));
+ when(mapper.selectRecentEntityChanges(-1, 0, 5, 60000, 2)).thenReturn(changes(1, 2));
+ when(mapper.selectRecentEntityChanges(0, 2, 5, 60000, 2))
+ .thenThrow(new IllegalStateException("replay database unavailable"))
+ .thenReturn(changes(3, 3));
+ AtomicLong clock = new AtomicLong();
+ List<EntityChangeRecord> received = new ArrayList<>();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.registerListener(replayListener(received));
+ // A full first page saves the (created_at, id) page cursor.
+ Assertions.assertTrue(poller.pollChanges());
+ // The second page fails; the saved cursor and sweep ceiling are kept.
+ Assertions.assertFalse(poller.pollChanges());
+ clock.addAndGet(TimeUnit.SECONDS.toNanos(1));
+ // After the poll interval the same page is retried instead of restarting the sweep.
+ Assertions.assertFalse(poller.pollChanges());
+ verify(mapper, times(1)).selectRecentEntityChanges(-1, 0, 5, 60000, 2);
+ verify(mapper, times(2)).selectRecentEntityChanges(0, 2, 5, 60000, 2);
+ Assertions.assertEquals(List.of(5L, 1L, 2L, 3L), ids(received));
+ }
+ }
+
+ @Test
+ void testUnseenRowAfterFirstSweepLogsLateCommitWarning() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(2, 2));
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2))
+ .thenReturn(List.of())
+ .thenReturn(changes(1, 1));
+ AtomicLong clock = new AtomicLong();
+ List<LogEvent> logs =
+ captureReplayLogs(
+ () -> {
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.pollChanges();
+ clock.addAndGet(SWEEP_INTERVAL_NANOS);
+ poller.pollChanges();
+ }
+ });
+ Assertions.assertTrue(
+ logs.stream()
+ .anyMatch(
+ e ->
+ Level.WARN.equals(e.getLevel())
+ && e.getMessage()
+ .getFormattedMessage()
+ .contains("replay found 1 previously unseen record(s)")),
+ logs.stream()
+ .map(e -> e.getMessage().getFormattedMessage())
+ .collect(Collectors.joining("\n")));
+ }
+
+ @Test
+ void testReplayOptInPreservesExistingListenersAndIsolatesCapabilityFailure() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ List<EntityChangeRecord> incremental = changes(2, 2);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(incremental);
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2)).thenReturn(changes(1, 1));
+ List<EntityChangeRecord> legacyReceived = new ArrayList<>();
+ List<EntityChangeRecord> replayReceived = new ArrayList<>();
+ EntityChangeLogListener broken = mock(EntityChangeLogListener.class);
+ when(broken.supportsReplay()).thenThrow(new AssertionError("capability unavailable"));
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource());
+ poller.registerListener(legacyReceived::addAll);
+ poller.registerListener(broken);
+ poller.registerListener(replayListener(replayReceived));
+ Assertions.assertFalse(poller.pollChanges());
+ Assertions.assertEquals(List.of(2L), ids(legacyReceived));
+ Assertions.assertEquals(List.of(2L, 1L), ids(replayReceived));
+ verify(broken).onEntityChange(incremental);
+ }
+ }
+
+ @Test
+ void testReplaySweepsStartAtMostOncePerSweepInterval() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 1));
+ when(mapper.selectEntityChanges(1, 2)).thenReturn(List.of());
+ when(mapper.selectRecentEntityChanges(-1, 0, 1, 60000, 2)).thenReturn(changes(1, 1));
+ AtomicLong clock = new AtomicLong();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(1, 2, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.pollChanges();
+ verify(mapper, times(1)).selectRecentEntityChanges(-1, 0, 1, 60000, 2);
+ // Polls inside the sweep interval read only the incremental stream.
+ clock.addAndGet(SWEEP_INTERVAL_NANOS - 1);
+ poller.pollChanges();
+ verify(mapper, times(1)).selectRecentEntityChanges(-1, 0, 1, 60000, 2);
+ clock.addAndGet(1);
+ poller.pollChanges();
+ verify(mapper, times(2)).selectRecentEntityChanges(-1, 0, 1, 60000, 2);
+ verify(mapper, times(3)).selectEntityChanges(anyLong(), anyInt());
+ }
+ }
+
+ @Test
+ void testReplaySweepIntervalIsAtLeastThePollInterval() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 1));
+ when(mapper.selectEntityChanges(1, 2)).thenReturn(List.of());
+ when(mapper.selectRecentEntityChanges(-1, 0, 1, 8000, 2)).thenReturn(List.of());
+ AtomicLong clock = new AtomicLong();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ // window / 4 = 2s is shorter than the 3s poll interval, so sweeps follow the poll interval.
+ EntityChangeLogPoller poller =
+ spy(new EntityChangeLogPoller(3, 2, 8, 10, new EntityChangeLogMetricsSource()));
+ doAnswer(ignored -> clock.get()).when(poller).nanoTime();
+ poller.pollChanges();
+ clock.addAndGet(TimeUnit.SECONDS.toNanos(2));
+ poller.pollChanges();
+ verify(mapper, times(1)).selectRecentEntityChanges(-1, 0, 1, 8000, 2);
+ clock.addAndGet(TimeUnit.SECONDS.toNanos(1));
+ poller.pollChanges();
+ verify(mapper, times(2)).selectRecentEntityChanges(-1, 0, 1, 8000, 2);
+ }
+ }
+
+ @Test
+ void testDedupEvictionsAreCounted() {
+ EntityChangeLogMapper mapper = mock(EntityChangeLogMapper.class);
+ when(mapper.selectEntityChanges(0, 2)).thenReturn(changes(1, 2));
+ when(mapper.selectRecentEntityChanges(-1, 0, 2, 60000, 2)).thenReturn(List.of());
+ EntityChangeLogMetricsSource metrics = new EntityChangeLogMetricsSource();
+ try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class)) {
+ mockSessionUtils(sessions, mapper);
+ EntityChangeLogPoller poller = new EntityChangeLogPoller(1, 2, 60, 1, metrics);
+ poller.pollChanges();
+ Assertions.assertEquals(
+ 1L, metrics.getMetricRegistry().getCounters().get("dedup-evictions-total").getCount());
+ Assertions.assertEquals(
+ 0L, metrics.getMetricRegistry().getCounters().get("replay-records-total").getCount());
+ }
+ }
+
+ private static EntityChangeLogListener replayListener(List<EntityChangeRecord> received) {
+ return new EntityChangeLogListener() {
+ /** {@inheritDoc} */
+ @Override
+ public void onEntityChange(List<EntityChangeRecord> changes) {
+ received.addAll(changes);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean supportsReplay() {
+ return true;
+ }
+ };
+ }
+
+ private static List<LogEvent> captureReplayLogs(Runnable action) {
+ LoggerContext context =
+ (LoggerContext) LogManager.getContext(EntityChangeLogPoller.class.getClassLoader(), false);
+ var logger = context.getLogger(EntityChangeLogPoller.class.getName());
+ ReplayLogCollector collector = new ReplayLogCollector();
+ collector.start();
+ // Attach to this logger without replacing its configuration or its existing appenders.
+ synchronized (logger) {
+ Level previous = logger.getLevel();
+ logger.addAppender(collector);
+ logger.setLevel(Level.DEBUG);
+ try {
+ action.run();
+ } finally {
+ logger.removeAppender(collector);
+ logger.setLevel(previous);
+ collector.stop();
+ }
+ }
+ return List.copyOf(collector.events);
+ }
+
+ private static class ReplayLogCollector extends AbstractAppender {
+ private final List<LogEvent> events = new CopyOnWriteArrayList<>();
+
+ private ReplayLogCollector() {
+ super("entityChangeReplayDiagnostics", null, PatternLayout.createDefaultLayout(), true, null);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void append(LogEvent event) {
+ events.add(event.toImmutable());
+ }
+ }
@Test
void testRejectsInvalidConfiguration() {
@@ -71,6 +649,12 @@ public class TestEntityChangeLogPoller {
EntityChangeLogMetricsSource metrics = new EntityChangeLogMetricsSource();
Assertions.assertThrows(
IllegalArgumentException.class, () -> new EntityChangeLogPoller(1, 0, metrics));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new EntityChangeLogPoller(1, 2, -1, 1, metrics));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new EntityChangeLogPoller(1, 2, 86401, 1, metrics));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> new EntityChangeLogPoller(1, 2, 60, 0, metrics));
}
@Test
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.java
index 35ad8fe0ec..b1cb6dde30 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
@@ -34,10 +34,12 @@ import org.apache.gravitino.RelationEdgeTarget;
import org.apache.gravitino.RelationQuery;
import org.apache.gravitino.RelationUpdate;
import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.cache.BaseEntityCache;
import org.apache.gravitino.cache.Coherence;
import org.apache.gravitino.cache.EntityCache;
import org.apache.gravitino.cache.NoOpsCache;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.TopicEntity;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -62,6 +64,23 @@ public class TestRelationalEntityStore {
FieldUtils.writeField(store, "cache", Mockito.spy(new NoOpsCache(config)), true);
}
+ @Test
+ void testUncachedInsertStillInvokesRelatedInvalidationAfterEpochChanges() throws Exception {
+ BaseEntityCache cache = Mockito.mock(BaseEntityCache.class);
+ FieldUtils.writeField(store, "cache", cache, true);
+ ModelEntity entity = Mockito.mock(ModelEntity.class);
+ Mockito.when(entity.type()).thenReturn(Entity.EntityType.MODEL);
+ Mockito.doAnswer(
+ invocation -> {
+ store.clearCache();
+ return null;
+ })
+ .when(backend)
+ .insert(entity, false);
+ store.put(entity, false);
+ Mockito.verify(cache).put(entity);
+ }
+
@Test
void testUpdateInvalidatesCacheAfterBackendUpdate()
throws IOException, NoSuchEntityException, EntityAlreadyExistsException,
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
index 00197d0c6d..11d66d3ca4 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
@@ -19,6 +19,11 @@
package org.apache.gravitino.storage.relational;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
+
import java.io.File;
import java.io.IOException;
import java.time.Instant;
@@ -207,6 +212,10 @@ public class TestRelationalEntityStoreHierarchicalCache {
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
index 2c745ea60e..152cfa9e44 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
@@ -447,6 +447,10 @@ public class TestRelationalEntityStoreLockWaitTimeout {
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(false);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java
index 5e34cd9696..b9d2fee40b 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java
@@ -104,6 +104,47 @@ public class TestEntityChangeLogMapper {
sharedSession.clearCache();
}
+ @Test
+ void testRecentReplayUsesWindowCeilingAndTimestampIdPagination() throws SQLException {
+ entityChangeLogMapper.insertEntityChange("ml", "TABLE", "expired", OperateType.ALTER);
+ forceCreatedAt("expired", 1000);
+ entityChangeLogMapper.insertEntityChange("ml", "TABLE", "recent-a", OperateType.ALTER);
+ entityChangeLogMapper.insertEntityChange("ml", "TABLE", "recent-b", OperateType.ALTER);
+ entityChangeLogMapper.insertEntityChange("ml", "TABLE", "above-ceiling", OperateType.ALTER);
+ List<EntityChangeRecord> all = entityChangeLogMapper.selectEntityChanges(0, 10);
+ long timestamp = all.get(1).getCreatedAt();
+ forceCreatedAt("recent-b", timestamp);
+ long ceiling = all.get(2).getId();
+ List<EntityChangeRecord> page =
+ entityChangeLogMapper.selectRecentEntityChanges(-1, 0, ceiling, 60000, 1);
+ Assertions.assertEquals(
+ List.of("recent-a"), page.stream().map(EntityChangeRecord::getFullName).toList());
+ EntityChangeRecord first = page.get(0);
+ List<EntityChangeRecord> second =
+ entityChangeLogMapper.selectRecentEntityChanges(
+ first.getCreatedAt(), first.getId(), ceiling, 60000, 10);
+ Assertions.assertEquals(
+ List.of("recent-b"), second.stream().map(EntityChangeRecord::getFullName).toList());
+ EntityChangeRecord last = second.get(0);
+ Assertions.assertTrue(
+ entityChangeLogMapper
+ .selectRecentEntityChanges(last.getCreatedAt(), last.getId(), ceiling, 60000, 10)
+ .isEmpty());
+ }
+
+ @Test
+ void testRecentReplayUsesBackendDatabaseClock() {
+ String mysql =
+ new EntityChangeLogBaseSQLProvider().selectRecentEntityChanges(-1, 0, 10, 60000, 2);
+ String postgres =
+ new EntityChangeLogPostgreSQLProvider().selectRecentEntityChanges(-1, 0, 10, 60000, 2);
+ Assertions.assertTrue(mysql.contains("UNIX_TIMESTAMP"));
+ Assertions.assertTrue(postgres.contains("EXTRACT(EPOCH FROM CURRENT_TIMESTAMP)"));
+ Assertions.assertFalse(postgres.contains("UNIX_TIMESTAMP"));
+ Assertions.assertTrue(mysql.contains("ORDER BY created_at, id LIMIT #{maxRows}"));
+ Assertions.assertTrue(postgres.contains("#{windowMs}"));
+ }
+
@Test
void testEntityChangeLogInsertAndSelect() {
long jvmBefore = System.currentTimeMillis();
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 13af7fb477..cd5921cdf6 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -19,10 +19,14 @@
package org.apache.gravitino.tag;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES;
+import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS;
import static org.apache.gravitino.Configs.ENTITY_CHANGE_LOG_RETENTION_SECS;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;
@@ -184,6 +188,10 @@ public class TestTagManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_WINDOW_SECS);
+ Mockito.when(config.get(ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES))
+ .thenReturn(DEFAULT_ENTITY_CHANGE_LOG_REPLAY_MAX_ENTRIES);
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
diff --git a/docs/gravitino-server-config.md b/docs/gravitino-server-config.md
index f4cf1fe400..a76e5fe596 100644
--- a/docs/gravitino-server-config.md
+++ b/docs/gravitino-server-config.md
@@ -142,9 +142,11 @@ it recognizes.
Servers behind a load balancer share the entity store but keep local caches. Each server polls the
entity change log and invalidates entries that another server has modified. The default poll
-interval is three seconds. The poller delivers each batch to every registered listener once and
-then advances its cursor; a listener that cannot invalidate a key must clear its local cache. The
-poller logs query and listener failures and continues polling. Monitor the
+interval is three seconds. The poller delivers each incremental batch to registered listeners
+and advances its cursor. Bounded recent-history replay is enabled by default and can repeat event
+IDs for listeners opting into replay, including the built-in cache listeners. A listener that
+cannot invalidate a key must clear its local cache. The poller logs query and listener failures
+and continues polling. Monitor the
[entity change log metrics](metrics.md#entity-change-log-metrics), especially record lag, time
since the last successful poll, listener failures, and fallback clears. Point the load balancer's
health check at `GET /health/ready` so a server that has lost its database stops receiving traffic.
@@ -327,24 +329,81 @@ Caches are local to each server, so a metalake modified on one server would othe
its neighbors. Every server writes its changes to an entity change log table and polls that table
to invalidate what other servers have touched. A separate cleaner trims old rows.
-Each poll reads at most `pollBatchSize` records. When a poll returns a full batch, the next poll
-starts immediately instead of waiting `pollIntervalSecs`, so a backlog is drained as fast as the
+Each poll reads at most `pollBatchSize` incremental records and, when a replay sweep is in
+progress or due, one additional recent-history page of at most `pollBatchSize` records. If either query returns a
+full page, the next poll starts immediately instead of waiting `pollIntervalSecs`, so a backlog is drained as fast as the
server can read and apply batches rather than at a fixed `pollBatchSize / pollIntervalSecs`
-records per second. Once a poll returns fewer records than the batch size, or fails, the server
-waits `pollIntervalSecs` again. A change written on one server therefore normally becomes visible
+records per second. Once both queries return fewer records than the batch size, or the cycle
+fails, the server waits `pollIntervalSecs` again. A change written on one server therefore normally becomes visible
on the others within about `pollIntervalSecs`, plus the time needed to drain any backlog ahead of
it. Continuous draining deliberately has no minimum delay between batches; a sustained backlog
can therefore keep the data query running at the rate the database and listeners support. The
observability-only database-tail query is sampled at most once per `pollIntervalSecs` during a
-full-batch drain; partial and empty polls still sample the tail. Each poll holds its whole batch
+full incremental-batch drain; partial and empty incremental queries still sample the tail,
+including each cycle of a replay-only drain. Each poll holds its whole batch
in memory, so raise `pollBatchSize` in moderate steps.
-| Configuration Item | Description | Default Value |
-|-------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|---------------------|
-| `gravitino.entityChangeLog.pollIntervalSecs` | Interval in seconds between polls once a server has caught up. Must be positive. | `3` |
-| `gravitino.entityChangeLog.pollBatchSize` | Maximum number of change log records read per poll. A full batch is followed by another poll right away. Must be positive. | `2000` |
-| `gravitino.entityChangeLog.retentionSecs` | How long in seconds change log rows are kept, measured by database time. `0` disables cleanup; otherwise use at least ten times `pollIntervalSecs`. | `2592000` (30 days) |
-| `gravitino.entityChangeLog.cleanupIntervalSecs` | Interval in seconds between cleaner runs. Must be positive. | `86400` (1 day) |
+| Configuration Item | Description | Default Value |
+|-------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------|
+| `gravitino.entityChangeLog.pollIntervalSecs` | Interval in seconds between polls once a server has caught up. Must be positive. | `3` |
+| `gravitino.entityChangeLog.pollBatchSize` | Maximum number of change log records read per poll. A full batch is followed by another poll right away. Must be positive. | `2000` |
+| `gravitino.entityChangeLog.replayWindowSecs` | Recent-history recorded-age window in seconds, using database time. Replay sweeps start at most once per `max(pollIntervalSecs, replayWindowSecs / 4)`. `0` disables replay; maximum `86400`. | `60` |
+| `gravitino.entityChangeLog.replayMaxEntries` | Maximum event IDs remembered locally for deduplication. Must be positive. Capacity eviction permits duplicate invalidations. | `100000` |
+| `gravitino.entityChangeLog.retentionSecs` | How long in seconds change log rows are kept, measured by database time. `0` disables cleanup; otherwise use at least ten times `pollIntervalSecs`. | `2592000` (30 days) |
+| `gravitino.entityChangeLog.cleanupIntervalSecs` | Interval in seconds between cleaner runs. Must be positive. | `86400` (1 day) |
+
+The built-in entity, catalog, and authorization listeners opt into replay. Third-party
+`EntityChangeLogListener` implementations keep incremental-only delivery by default. Override
+`supportsReplay()` to return `true` only when callbacks tolerate duplicate event IDs.
+
+All valid catalog events invalidate their cache entry, including locally originated events.
+Name-based local mutation markers are not used because polling can race marker registration and
+replay can repeat rows. This may add a local catalog reload; existing operation leases defer
+connection-pool/classloader cleanup until in-flight operations finish. Point reads and insert
+publications also check the entity-cache invalidation epoch so an ancestor invalidation cannot
+leave an old value cached after a concurrent load. An overlapping read can still return its
+original snapshot; this does not introduce linearizable reads.
+
+Auto-increment ID allocation order is not commit order. A transaction can commit a lower ID after
+another row has advanced the incremental cursor. Recent-history replay scans at or behind that
+cursor, ordered by `(created_at, id)` with a fixed ID ceiling per sweep. Each query uses the database
+clock, and the existing `created_at` index supports the time filter; repeated IDs are suppressed
+by a process-local bounded set.
+Full replay pages continue immediately, but every cycle delivers its incremental batch first.
+A new sweep starts at most once per `max(pollIntervalSecs, replayWindowSecs / 4)`, 15 seconds by
+default; the first sweep after startup runs at once. A row that becomes visible behind an already
+scanned replay page, or between sweeps, is considered on the next sweep. Late-commit recovery can
+therefore take up to one extra sweep interval, and a row is guaranteed to be replayed only if it
+becomes visible before its recorded age exceeds the window minus one sweep interval (45 seconds by
+default).
+
+The window measures age of the stored **`created_at`**, not time since commit. PostgreSQL's
+existing writer uses `CURRENT_TIMESTAMP`, which is the transaction start timestamp; a long
+transaction can therefore consume replay headroom even before inserting its log row. Transactions
+that commit outside it, records deleted by retention cleanup, and an overloaded replay sweep can still lose
+invalidations. Keep retention longer than the replay window and allow enough headroom for polling
+and backlog. This is bounded compensation, not a lossless delivery protocol. Replay does not change
+cache TTLs. Each sweep rereads every row in the window; deduplication avoids repeated listener work,
+not the SQL reads. With the sweep interval at a quarter of the window, each row is read by about
+four sweeps per server, so replay reads grow with write rate and server count but not with the
+poll interval. More recent rows than
+`replayMaxEntries` can cause repeated invalidations, including catalog reloads; increase capacity or reduce the window based on measured traffic and memory.
+
+At startup, INFO logs report the window and dedup capacity. A WARN containing
+`Entity change log replay found` reports previously unseen rows behind the cursor, with cursor,
+startup cursor, window, approximate oldest recorded age, and up to 20 event summaries
+(`id:type:operation:name`). DEBUG logs include every replayed row's timestamp and age, and page/sweep
+progress. This is evidence of a **possible** late commit: dedup eviction can also produce unseen
+IDs. The first sweep after startup replays recent history into an empty dedup set, so it logs
+`Entity change log startup replay delivered` at INFO instead. Ages compare JVM and database clocks and are not commit latency.
+`replay failed` logs include page cursors and the exception; incremental delivery is preserved,
+and replay retries are limited to one attempt per polling interval during a failure.
+`replay dedup capacity reached` reports accumulated eviction and possible repeated invalidations,
+at most once per polling interval. The `entity-change-log` metrics `replay-records-total`,
+`replay-failures-total`, and `dedup-evictions-total` count the same events for monitoring. An event never observed because it committed outside the window
+cannot be diagnosed from replay logs alone.
+The `record-lag` gauge compares maximum ID and cursor, so a value of zero does not rule out a
+late lower-ID commit; inspect the replay diagnostics as well.
#### Tree Lock
diff --git a/docs/metrics.md b/docs/metrics.md
index 5d54df52f5..7265278257 100644
--- a/docs/metrics.md
+++ b/docs/metrics.md
@@ -78,28 +78,40 @@ The `entity-change-log` source exposes each server's change-log processing state
`/prometheus/metrics`. For example, `entity-change-log.record-lag` in the metrics registry becomes
`entity_change_log_record_lag` in Prometheus. Gauges read only in-memory values; the poller samples
the database tail on partial and empty polls, and at most once per `pollIntervalSecs` during
-a full-batch drain (including failed sample attempts). If only the tail sample fails, delivery
-continues and the tail value remains at its last successful sample.
-
-| Metric suffix | Type and unit | Meaning |
-| ------------------------------------------------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `db-tail-id`, `cursor-id` | gauge, change ID | Latest sampled database ID and last delivered ID on this server. |
-| `record-lag` | gauge, records | Sampled tail minus cursor, clamped at zero. Interpret only while tail sampling succeeds. |
-| `seconds-since-last-successful-poll` | gauge, seconds | Time since a successful database poll, including an empty result; `-1` before the first poll. |
-| `seconds-since-last-successful-tail-sample` | gauge, seconds | Time since `db-tail-id` was last refreshed; `-1` before the first sample. Trust `db-tail-id` and `record-lag` only while this stays near the poll interval. |
-| `poll-failures-total` | counter, failures | Failed poll cycles. |
-| `tail-sample-failures-total` | counter, failures | Failed database-tail samples; fetched batches can still be delivered. |
-| `listener-failures-total`, `listener-failures.<class>-total` | counter, failures | Total failures and failures by registered listener class. |
-| `records-fetched-total`, `records-delivered-total` | counter, records | Rows fetched and rows delivered successfully to listeners; one row delivered to two listeners counts twice as delivered. |
-| `records-delivered.<class>-total` | counter, records | Successful deliveries by listener class. Lambda and anonymous listeners share the `anonymous` bucket. |
-| `records-applied-total` | counter, invalidations | Targeted entity-cache invalidations completed successfully; malformed rows and fallback clears do not count. |
-| `batch-size-records` | histogram, records | Number of rows fetched per successful poll, including empty polls. Polls at `pollBatchSize` mean the server is draining a backlog and polls again at once. |
-| `poll-duration` | timer, duration | End-to-end poll-cycle duration. |
-| `invalidation-failures-total`, `fallback-clears-total` | counter, failures/clears | Failed targeted entity-cache invalidations and successful full-cache recovery clears. |
-
-The poller delivers each batch once and has no pending or retry state. A failed listener must
-recover locally; its failure counter and log identify the affected listener. The debug logs use
-`entityChangeLog` fields to trace an append, poll, delivery, and invalidation. Append logs mean the
+a full incremental-batch drain (including failed sample attempts). A full replay page also
+schedules the next cycle immediately; when its incremental query is partial or empty, that
+cycle still samples the tail. Each such replay-only drain cycle therefore performs an incremental
+query, a tail query, and a replay query. If only the tail sample fails, delivery continues and
+the tail value remains at its last successful sample.
+
+| Metric suffix | Type and unit | Meaning |
+| ------------------------------------------------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `db-tail-id`, `cursor-id` | gauge, change ID | Latest sampled database ID and last incrementally delivered ID on this server; replay does not move the cursor. |
+| `record-lag` | gauge, records | Sampled tail minus cursor, clamped at zero. Interpret only while tail sampling succeeds. |
+| `seconds-since-last-successful-poll` | gauge, seconds | Time since a successful database poll, including an empty result; `-1` before the first poll. |
+| `seconds-since-last-successful-tail-sample` | gauge, seconds | Time since `db-tail-id` was last refreshed; `-1` before the first sample. Trust `db-tail-id` and `record-lag` only while this stays near the poll interval. |
+| `poll-failures-total` | counter, failures | Failed poll cycles. |
+| `tail-sample-failures-total` | counter, failures | Failed database-tail samples; fetched batches can still be delivered. |
+| `listener-failures-total`, `listener-failures.<class>-total` | counter, failures | Total callback failures, and failures by registered listener class. |
+| `records-fetched-total`, `records-delivered-total` | counter, records | Incremental rows fetched and rows delivered successfully to listeners, including replay; one row delivered to two listeners counts twice as delivered. |
+| `records-delivered.<class>-total` | counter, records | Successful deliveries by listener class. Lambda and anonymous listeners share the `anonymous` bucket. |
+| `records-applied-total` | counter, invalidations | Targeted entity-cache invalidations completed successfully; malformed rows and fallback clears do not count. |
+| `batch-size-records` | histogram, records | Incremental rows fetched per successful poll, including empty polls; replay rows are excluded. A full incremental or replay page schedules another cycle at once. |
+| `poll-duration` | timer, duration | End-to-end poll-cycle duration. |
+| `invalidation-failures-total`, `fallback-clears-total` | counter, failures/clears | Failed targeted entity-cache invalidations and successful full-cache recovery clears. |
+| `replay-records-total` | counter, records | Previously unseen rows found behind the cursor by recent-history replay: possible late commits, startup history, or rows whose dedup entry was evicted. |
+| `replay-failures-total` | counter, failures | Failed recent-history replay queries; incremental delivery continues and the query is retried after the poll interval. |
+| `dedup-evictions-total` | counter, IDs | Remembered event IDs evicted at `replayMaxEntries` capacity; each eviction may allow one duplicate invalidation. |
+
+The poller does not retry a failed listener callback; a failed listener must recover locally.
+Its failure counter and log identify the affected listener. Recent-history replay maintains
+a page cursor and bounded deduplication state and retries failed queries after the polling
+interval. It can redeliver previously delivered rows to listeners opting into `supportsReplay()`.
+Consequently, delivery and invalidation counters include replay work, while fetched-row and
+batch-size metrics describe only the incremental stream. Replay query failures increment
+`replay-failures-total`, not `poll-failures-total`, when incremental delivery succeeded.
+Replay capability-check failures are logged separately and skip replay for that listener without
+incrementing callback failure counters. The debug logs use `entityChangeLog` fields to trace an append, poll, delivery, and invalidation. Append logs mean the
row was added to the current transaction, not that the transaction committed.
For an incident, check `seconds-since-last-successful-tail-sample` before comparing `db-tail-id`
@@ -108,7 +120,9 @@ investigate slow or failed polling and tail sampling; `tail-sample-failures-tota
sample failures. Between samples, an advancing cursor can pass the retained tail, so `record-lag`
can read zero even while full batches remain. Use `batch-size-records` at `pollBatchSize` as the
backlog signal rather than treating zero sampled lag as proof that the poller has caught up. With a
-fresh tail sample, a growing `record-lag` together with an increasing poll age or
+fresh tail sample, zero lag cannot exclude a late-committing lower ID; watch
+`replay-records-total` and the `Entity change log replay found` logs as well. A rising
+`replay-failures-total` means late commits are not being recovered. A growing `record-lag` together with an increasing poll age or
`poll-failures-total` points to polling trouble.
If the cursor advances but data remains stale, inspect `listener-failures-total`, `records-delivered.<class>-total`,
`invalidation-failures-total`, and `fallback-clears-total`, then correlate the debug logs by
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
index d245f3a95c..a1e11e3f1d 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java
@@ -214,6 +214,12 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
ownerPollHighWaterUpdatedAtId = maxSeenUpdatedAtId[0];
}
+ /** {@inheritDoc} */
+ @Override
+ public boolean supportsReplay() {
+ return true;
+ }
+
/**
* Invalidates the affected {@code metadataIdCache} keys from an entity-change batch.
*
@@ -229,8 +235,8 @@ public class JcasbinChangeListener implements EntityChangeLogListener, AutoClose
* being thrown up. Such a row does not point at any cache key, so skipping it leaves nothing
* stale behind.
*
- * <p><b>Recovering from a failure:</b> the poller hands each batch over only once and never sends
- * it again, so a failed removal has to be handled here. Otherwise {@code metadataIdCache} would
+ * <p><b>Recovering from a failure:</b> the poller does not guarantee a retry after a failed
+ * callback, so a failed removal has to be handled here. Otherwise {@code metadataIdCache} would
* keep an out-of-date name&#8594;id entry and hand it to authorization checks until that entry's
* TTL runs out. So the whole {@code metadataIdCache} is cleared instead. That is safe: everything
* in it can be looked up again, and clearing it also covers the entry that failed plus the rest
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
index c8e815a926..fe3207203d 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinChangePoller.java
@@ -37,6 +37,20 @@ import org.junit.jupiter.api.Test;
/** Tests for {@link JcasbinChangeListener} static helpers. */
public class TestJcasbinChangePoller {
+ @Test
+ void testReplayOptInAcceptsRepeatedInvalidations() {
+ RecordingCache<String, Long> metadataIdCache = new RecordingCache<>();
+ RecordingCache<Long, Optional<OwnerInfo>> ownerRelCache = new RecordingCache<>();
+ JcasbinChangeListener listener = new JcasbinChangeListener(metadataIdCache, ownerRelCache, 1);
+ Assertions.assertTrue(listener.supportsReplay());
+ List<EntityChangeRecord> batch =
+ List.of(change(1L, MetadataObject.Type.TABLE, "ml1.cat1.sch1.tbl1"));
+ listener.onEntityChange(batch);
+ listener.onEntityChange(batch);
+ String tableKey = key("ml1", "CATALOG", "cat1", "SCHEMA", "sch1", "TABLE", "tbl1", "");
+ Assertions.assertEquals(List.of(tableKey, tableKey), metadataIdCache.invalidatedPrefixes);
+ }
+
@Test
void testRejectsNonPositivePollInterval() {
RecordingCache<String, Long> metadataIdCache = new RecordingCache<>();