yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766606176


##########
core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java:
##########
@@ -190,21 +211,47 @@ void testCatalogAndSchemaChangeLogOnRenameAndDrop() 
throws IOException {
         OperateType.DROP);
   }
 
+  @TestTemplate
+  void testEntityAndChangeLogRollbackTogether() throws IOException {
+    createAndInsertMakeLake(METALAKE_NAME);
+    CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, 
CATALOG_NAME);
+    long maxIdBeforeUpdate = maxEntityChangeId();
+
+    SessionUtils.beginTransaction();
+    try {
+      backend.update(
+          catalog.nameIdentifier(),
+          Entity.EntityType.CATALOG,
+          entity ->
+              createCatalog(
+                  catalog.id(), catalog.namespace(), CATALOG_NAME + 
"_rolled_back", AUDIT_INFO));
+    } finally {
+      SessionUtils.rollbackTransaction();
+    }
+
+    CatalogEntity persistedCatalog =
+        backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);
+    Assertions.assertEquals(CATALOG_NAME, persistedCatalog.name());
+    Assertions.assertEquals(maxIdBeforeUpdate, maxEntityChangeId());

Review Comment:
   Added `testEntityUpdateRollsBackWhenChangeLogInsertFails`.
   
   Your earlier point was right: `testEntityAndChangeLogRollbackTogether` only 
rolls back a transaction the test itself owns, so it never exercises a 
change-log insert failing after the entity write. The new test renames 
`entity_change_log` away for the duration of the call, so `updateEntity` 
succeeds and `insertEntityChange` then fails inside the same transaction, and 
asserts that neither the renamed catalog nor a change-log row survives.
   
   I verified the new test is actually sensitive to the rollback by temporarily 
disabling the `finally { rollback }` block in `JDBCBackend#update`:
   
   | test | with rollback removed |
   | --- | --- |
   | `testEntityAndChangeLogRollbackTogether` (existing) | still passes |
   | `testEntityUpdateRollsBackWhenChangeLogInsertFails` (new) | fails |
   
   Run locally against H2; the MySQL and PostgreSQL template invocations are 
left to CI.



##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -115,6 +120,14 @@ public void initialize(Config config) throws 
RuntimeException {
             
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_RETENTION_SECS)),
             
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)),
             
TimeUnit.SECONDS.toMillis(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)));
+
+    // The coherence gate: a LOCAL_PER_NODE cache keeps its own copy per node, 
so changes made on
+    // other nodes must be replayed here through the change log. SHARED and 
NONE caches have
+    // nothing per-node to invalidate, so no listener is registered.
+    if (cache.coherence() == Coherence.LOCAL_PER_NODE) {

Review Comment:
   Added tests for all three coherence modes in `TestRelationalEntityStore`:
   
   - `testLocalPerNodeCacheRegistersChangeLogListener` — the listener is 
created and registered with the poller.
   - `testSharedCacheDoesNotRegisterChangeLogListener` — a single cluster-wide 
copy has nothing per-node to invalidate, so no listener.
   - `testCacheDisabledDoesNotRegisterChangeLogListener` — same for `NONE`.
   
   `initialize()` needs a real backend, garbage collector and a started poller, 
so I extracted the gate into `registerCacheChangeLogListener()` and the tests 
drive that directly with an injected cache and a mock poller. `SHARED` has no 
implementation yet, so that case uses a mocked `EntityCache` reporting the mode.



##########
core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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 com.google.common.base.Preconditions;
+import java.util.List;
+import java.util.Locale;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.cache.EntityCache;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Keeps a per-node {@link EntityCache} coherent across a multi-node cluster 
by replaying {@code
+ * entity_change_log} rows written by other nodes.
+ *
+ * <p>Every ALTER/DROP row is replayed as a direct {@link 
EntityCache#invalidate(NameIdentifier,
+ * EntityType)} for exactly the changed entity key. Because the cache indexes 
its keys by identifier
+ * prefix, invalidating a container (for example a schema) cascades to its 
cached children on the
+ * local node through that forward prefix scan; no reverse index is involved.
+ *
+ * <p>This listener is registered only for a {@link
+ * org.apache.gravitino.cache.Coherence#LOCAL_PER_NODE} cache: a shared cache 
has a single
+ * cluster-wide copy and nothing per-node to invalidate. It is called 
<em>synchronously</em> on the
+ * poller thread, so it performs only fast, in-memory, idempotent 
invalidations.
+ */
+public class EntityCacheChangeLogListener implements EntityChangeLogListener {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(EntityCacheChangeLogListener.class);
+
+  private final EntityCache cache;
+
+  /**
+   * Creates a listener that invalidates the given entity store cache.
+   *
+   * @param cache the per-node entity store cache to keep coherent
+   */
+  public EntityCacheChangeLogListener(EntityCache cache) {
+    Preconditions.checkArgument(cache != null, "cache cannot be null");
+    this.cache = cache;
+  }
+
+  @Override
+  public void onEntityChange(List<EntityChangeRecord> changes) {
+    for (EntityChangeRecord change : changes) {
+      try {
+        EntityType type = entityType(change);
+        NameIdentifier ident = identifier(change);
+        if (type == null || ident == null) {
+          continue;
+        }
+
+        LOG.debug("Invalidating entity cache due to entity change log: {} 
({})", ident, type);
+        cache.invalidate(ident, type);
+      } catch (RuntimeException e) {

Review Comment:
   Fixed in e6d4d41 — details are in the reply on the original thread above.
   
   Short version: the block mixed two unrelated failures. `identifier()` calls 
`EntityChangeLogNameIdentifierCodec.decode()`, which throws 
`IllegalArgumentException` on a malformed encoding, and `cache.invalidate()` 
fails for entirely different reasons; the single broad catch treated both as 
"bad record, log and move on".
   
   Parsing now catches `IllegalArgumentException` where it happens and returns 
null, so a malformed row is logged and skipped and the rest of the batch still 
applies. A failed invalidation is handled separately: it would otherwise leave 
this node serving stale metadata, so the listener clears the whole cache — a 
safe superset of the invalidation that failed, which also covers the remaining 
records in the batch. If the clear itself fails the exception propagates to the 
poller.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to