You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "yuqi1129 (via GitHub)" <gi...@apache.org> on 2026/08/05 07:33:15 UTC

[PR] [#12151] fix(core): complete cached entity change-log coverage [gravitino]

yuqi1129 opened a new pull request, #12374:
URL: https://github.com/apache/gravitino/pull/12374

   Depends on #12111.
   
   ### What changes were proposed in this pull request?
   
   Centralize cache invalidation change-log emission at the `JDBCBackend` entity-store mutation boundary.
   
   - Emit `ALTER` for cacheable entity overwrite and update operations.
   - Emit `DROP` after a successful delete.
   - Keep only the old identifier for rename invalidation.
   - Do not emit an event for create because the entity cache has no negative entries and list operations bypass the cache.
   - Emit one root `DROP` for cascading deletion and let prefix invalidation clear cached descendants.
   - Commit the metadata mutation and its change-log row in the same transaction.
   - Remove duplicated change-log emission from type-specific MetaServices.
   - Update the multi-node cache design and mutation coverage tests.
   
   The covered cacheable types are metalake, catalog, schema, table, topic, view, fileset, tag, policy, and job.
   
   ### Why are the changes needed?
   
   Change-log emission was distributed across selected MetaService paths. This missed ordinary non-rename updates and mutation paths such as overwrite, status changes, enable/disable, import, and repair.
   
   Centralizing emission ensures that every invalidating mutation of a cacheable entity follows the same transaction and coverage policy.
   
   Fix: #12151
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. This PR does not change public APIs or configuration properties.
   
   ### How was this patch tested?
   
   - `./gradlew :core:spotlessApply -PskipDockerTests`
   - `./gradlew :core:test --tests "org.apache.gravitino.storage.relational.service.TestEntityChangeLogService" -PskipITs -PskipDockerTests`
   - `./gradlew :core:test --tests "org.apache.gravitino.storage.relational.service.TestTableMetaService" -PskipITs -PskipDockerTests`
   - `./gradlew :core:test --tests "org.apache.gravitino.storage.relational.TestEntityCacheCrossNodeInvalidation" -PskipITs -PskipDockerTests`
   - `./gradlew :core:test -PskipITs -PskipDockerTests`


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766609210


##########
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:
   Tests added



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766493280


##########
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:
   Split the two failure modes as you suggested.
   
   The block actually mixed two independent sources of exceptions: `identifier()` calls `EntityChangeLogNameIdentifierCodec.decode()`, which throws `IllegalArgumentException` on a malformed encoding, and `cache.invalidate()`, which fails for entirely different reasons. The single broad catch treated both as "bad record, log and move on".
   
   Now parsing catches `IllegalArgumentException` where it happens and returns null, so a malformed row is logged and skipped without affecting the rest of the batch. A failed invalidation is handled separately: it would otherwise leave this node serving stale metadata, so the listener clears the whole cache — the cache is derived state, so the clear is a safe superset of the invalidation that failed, and it also covers the remaining records in the batch. If the clear itself fails, the exception propagates and the poller applies its retry / failure-action policy.
   
   Added three tests for these paths.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3755108778


##########
server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java:
##########


Review Comment:
   Emitting rows for TAG/POLICY/JOB will crash every node.
   
    TAG/POLICY/JOB in a virtual namespace (`NamespaceUtil.java:93`), so a tag row is
   `ml1.system.tag.pii` — 4 levels. `valueOf("TAG")` succeeds, then `MetadataObjects.of`
   expects length 1 and throws. There's no per-record try/catch here, so the batch fails
   deterministically and the poller's default action after 10 retries is `EXIT`
   



##########
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:
   Catching RuntimeException here is too broad. Could we separate the invalidate logic from the entity log processing so that exceptions are handled independently?



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########


Review Comment:
   Cascade drop doesn't clear hierarchical-schema descendants on remote nodes.
   
   `childPrefix` joins with a dot, but hierarchical schemas nest with `:`
   (`Configs.java:609-625` forbids `.`), so dropping `ml1.cat1.raw:events` leaves
   `raw:events:2024` and its tables cached until TTL — while the single root DROP row is
   all this PR emits.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3756740048


##########
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:
   Changed.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] fix(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3719621220


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -115,6 +121,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. A SHARED cache (or a disabled
+    // NoOpsCache) has nothing per-node to invalidate, so no listener is registered.
+    if (cache.coherence() == Coherence.LOCAL_PER_NODE && !(cache instanceof NoOpsCache)) {
+      this.entityCacheChangeLogListener = new EntityCacheChangeLogListener(cache);
+      this.entityChangeLogPoller.registerListener(entityCacheChangeLogListener);
+    }

Review Comment:
   Fixed in 917df696fa. Added Coherence.NONE, made NoOpsCache return it, and removed the instanceof special case from listener registration. Tests now verify the cache coherence modes.



##########
core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java:
##########
@@ -64,20 +75,20 @@ private void assertEntityChange(
       Entity.EntityType entityType,
       String fullName,
       OperateType operateType) {
-    Assertions.assertTrue(
-        listEntityChanges(lastConsumedId).stream()
-            .anyMatch(
-                record ->
-                    record.getMetalakeName().equals(metalakeName)
-                        && record.getEntityType().equals(entityType.name())
-                        && record.getFullName().equals(fullName)
-                        && record.getOperateType() == operateType),
-        String.format("Missing %s %s changelog for %s", entityType, operateType, fullName));
+    List<EntityChangeRecord> entityChanges = listEntityChanges(lastConsumedId);
+    Assertions.assertEquals(1, entityChanges.size());
+    EntityChangeRecord entityChange = entityChanges.get(0);
+    Assertions.assertEquals(metalakeName, entityChange.getMetalakeName());
+    Assertions.assertEquals(entityType.name(), entityChange.getEntityType());
+    Assertions.assertEquals(fullName, entityChange.getFullName());
+    Assertions.assertEquals(operateType, entityChange.getOperateType());

Review Comment:
   Fixed in 917df696fa. The assertion now filters by metalake, entity type, full name, and operation, then requires exactly one matching row while tolerating unrelated rows.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -56,10 +54,9 @@
  * schemas and tables under it).
  *
  * <p>Relation query results are NOT cached by this implementation; relation and list operations
- * always fall back to the {@code EntityStore}. Entity types whose materialized form embeds
- * relation-derived data ({@code USER}, {@code GROUP}, {@code ROLE}) are excluded from caching
- * entirely by {@link BaseEntityCache#put}, because without relation tracking their entries could
- * not be invalidated when the referenced entities change.
+ * always fall back to the {@code EntityStore}. Only the self-contained metadata objects listed in
+ * {@link BaseEntityCache#isCacheable} are cached; every other type (user/group/role, model/model
+ * version, function, and operational entities) is read straight from the {@code EntityStore}.

Review Comment:
   Fixed in 917df696fa. The Javadoc now describes the actual allowlist behavior and explicitly lists the excluded types, without classifying all operational entities as uncached.



##########
core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java:
##########
@@ -178,95 +183,45 @@ public boolean exists(NameIdentifier ident, Entity.EntityType entityType) throws
   @Override
   public <E extends Entity & HasIdentifier> void insert(E e, boolean overwritten)
       throws EntityAlreadyExistsException, IOException {
-    if (e instanceof BaseMetalake) {
-      MetalakeMetaService.getInstance().insertMetalake((BaseMetalake) e, overwritten);
-    } else if (e instanceof CatalogEntity) {
-      CatalogMetaService.getInstance().insertCatalog((CatalogEntity) e, overwritten);
-    } else if (e instanceof SchemaEntity) {
-      SchemaMetaService.getInstance().insertSchema((SchemaEntity) e, overwritten);
-    } else if (e instanceof TableEntity) {
-      TableMetaService.getInstance().insertTable((TableEntity) e, overwritten);
-    } else if (e instanceof FilesetEntity) {
-      FilesetMetaService.getInstance().insertFileset((FilesetEntity) e, overwritten);
-    } else if (e instanceof TopicEntity) {
-      TopicMetaService.getInstance().insertTopic((TopicEntity) e, overwritten);
-    } else if (e instanceof UserEntity) {
-      UserMetaService.getInstance().insertUser((UserEntity) e, overwritten);
-    } else if (e instanceof RoleEntity) {
-      RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);
-    } else if (e instanceof GroupEntity) {
-      GroupMetaService.getInstance().insertGroup((GroupEntity) e, overwritten);
-    } else if (e instanceof TagEntity) {
-      TagMetaService.getInstance().insertTag((TagEntity) e, overwritten);
-    } else if (e instanceof ModelEntity) {
-      ModelMetaService.getInstance().insertModel((ModelEntity) e, overwritten);
-    } else if (e instanceof ModelVersionEntity) {
-      if (overwritten) {
-        LOG.warn(
-            "'overwritten' is not supported for model version meta, ignoring this flag and "
-                + "inserting the new model version.");
+    if (!overwritten || !BaseEntityCache.isCacheable(e.type())) {
+      insertEntity(e, overwritten);
+      return;
+    }
+
+    SessionUtils.beginTransaction();
+    boolean committed = false;
+    try {
+      insertEntity(e, true);
+      insertEntityChange(e.nameIdentifier(), e.type(), OperateType.ALTER);
+      SessionUtils.commitTransaction();
+      committed = true;
+    } finally {
+      if (!committed) {
+        SessionUtils.rollbackTransaction();
       }
-      ModelVersionMetaService.getInstance().insertModelVersion((ModelVersionEntity) e);
-    } else if (e instanceof FunctionEntity) {
-      FunctionMetaService.getInstance().insertFunction((FunctionEntity) e, overwritten);
-    } else if (e instanceof PolicyEntity) {
-      PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
-    } else if (e instanceof JobTemplateEntity) {
-      JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);
-    } else if (e instanceof JobEntity) {
-      JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);
-    } else if (e instanceof ViewEntity) {
-      ViewMetaService.getInstance().insertView((ViewEntity) e, overwritten);
-    } else if (e instanceof GenericEntity) {
-      GenericEntity genericEntity = (GenericEntity) e;
-      throw new UnsupportedEntityTypeException(
-          "Unsupported entity type: %s for insert operation", genericEntity.type());
-    } else {
-      throw new UnsupportedEntityTypeException(
-          "Unsupported entity type: %s for insert operation", e.getClass());
     }
   }
 
   @Override
   public <E extends Entity & HasIdentifier> E update(
       NameIdentifier ident, Entity.EntityType entityType, Function<E, E> updater)
       throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
-    switch (entityType) {
-      case METALAKE:
-        return (E) MetalakeMetaService.getInstance().updateMetalake(ident, updater);
-      case CATALOG:
-        return (E) CatalogMetaService.getInstance().updateCatalog(ident, updater);
-      case SCHEMA:
-        return (E) SchemaMetaService.getInstance().updateSchema(ident, updater);
-      case TABLE:
-        return (E) TableMetaService.getInstance().updateTable(ident, updater);
-      case FILESET:
-        return (E) FilesetMetaService.getInstance().updateFileset(ident, updater);
-      case TOPIC:
-        return (E) TopicMetaService.getInstance().updateTopic(ident, updater);
-      case USER:
-        return (E) UserMetaService.getInstance().updateUser(ident, updater);
-      case GROUP:
-        return (E) GroupMetaService.getInstance().updateGroup(ident, updater);
-      case ROLE:
-        return (E) RoleMetaService.getInstance().updateRole(ident, updater);
-      case TAG:
-        return (E) TagMetaService.getInstance().updateTag(ident, updater);
-      case MODEL:
-        return (E) ModelMetaService.getInstance().updateModel(ident, updater);
-      case MODEL_VERSION:
-        return (E) ModelVersionMetaService.getInstance().updateModelVersion(ident, updater);
-      case FUNCTION:
-        return (E) FunctionMetaService.getInstance().updateFunction(ident, updater);
-      case POLICY:
-        return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
-      case JOB_TEMPLATE:
-        return (E) JobTemplateMetaService.getInstance().updateJobTemplate(ident, updater);
-      case VIEW:
-        return (E) ViewMetaService.getInstance().updateView(ident, updater);
-      default:
-        throw new UnsupportedEntityTypeException(
-            "Unsupported entity type: %s for update operation", entityType);
+    if (!BaseEntityCache.isCacheable(entityType)) {
+      return updateEntity(ident, entityType, updater);
+    }
+
+    SessionUtils.beginTransaction();
+    boolean committed = false;
+    try {
+      E updatedEntity = updateEntity(ident, entityType, updater);
+      insertEntityChange(ident, entityType, OperateType.ALTER);
+      SessionUtils.commitTransaction();
+      committed = true;
+      return updatedEntity;
+    } finally {
+      if (!committed) {
+        SessionUtils.rollbackTransaction();
+      }
     }

Review Comment:
   Fixed in 917df696fa. JDBCBackend now checks SessionUtils.isInTransaction() and only begins, commits, or rolls back when it owns the transaction; otherwise it participates in the caller-managed transaction. Added session-state coverage and a service test that verifies the entity update and change-log row roll back together.



##########
core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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) {
+        LOG.warn(
+            "Failed to process entity change log record: fullName={}, entityType={}",
+            change.getFullName(),
+            change.getEntityType(),
+            e);
+      }
+    }
+  }
+
+  private EntityType entityType(EntityChangeRecord change) {
+    if (change.getEntityType() == null) {
+      LOG.warn("Invalid entity type in entity change log: null");
+      return null;
+    }
+    try {
+      return EntityType.valueOf(change.getEntityType().toUpperCase(Locale.ROOT));
+    } catch (IllegalArgumentException e) {
+      LOG.warn("Unknown entity type in entity change log: {}", change.getEntityType());
+      return null;
+    }
+  }
+
+  private NameIdentifier identifier(EntityChangeRecord change) {
+    String fullName = change.getFullName();
+    if (fullName == null || fullName.isEmpty()) {
+      LOG.warn("Invalid full name in entity change log: {}", fullName);
+      return null;
+    }
+    // The change log stores the entity's NameIdentifier#toString(), a dot-joined full name. Split
+    // it back into levels the same way the catalog cache listener does; this is exact as long as
+    // no name segment contains a dot.
+    return NameIdentifier.of(fullName.split("\\."));

Review Comment:
   Fixed in 917df696fa with a lossless, versioned length-prefixed codec for identifiers containing dots. Ordinary identifiers retain the legacy dot-joined form for rolling compatibility. The entity cache, catalog, and JCasbin consumers decode through the codec, with focused listener, codec, and H2 service tests.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3755142619


##########
server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java:
##########


Review Comment:
   
   The comments still names `SchemaMetaService` / `TableMetaService` as the
   writers, which this PR removed.



##########
core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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 java.util.Arrays;
+import org.apache.gravitino.NameIdentifier;
+
+/** Losslessly encodes entity identifiers in the change log while retaining legacy readability. */
+public final class EntityChangeLogNameIdentifierCodec {
+
+  private static final String ENCODED_PREFIX = "gravitino:v1:";
+
+  private EntityChangeLogNameIdentifierCodec() {}
+
+  /**
+   * Encodes an identifier for the {@code entity_full_name} change-log column.
+   *
+   * <p>Identifiers without ambiguous dots retain their historical dot-joined representation, so
+   * older nodes can continue consuming ordinary names during a rolling upgrade. Identifiers whose
+   * segments contain dots use a length-prefixed representation.
+   *
+   * @param ident identifier to encode
+   * @return encoded identifier
+   */
+  public static String encode(NameIdentifier ident) {
+    String legacyValue = ident.toString();
+    String[] levels = levels(ident);
+    boolean requiresEncoding =
+        legacyValue.startsWith(ENCODED_PREFIX)
+            || Arrays.stream(levels).anyMatch(level -> level.indexOf('.') >= 0);
+    if (!requiresEncoding) {
+      return legacyValue;
+    }
+
+    StringBuilder encoded = new StringBuilder(ENCODED_PREFIX).append(levels.length).append(':');
+    for (String level : levels) {
+      encoded.append(level.length()).append(':').append(level);
+    }
+    return encoded.toString();
+  }
+
+  /**
+   * Decodes an identifier read from the {@code entity_full_name} change-log column.
+   *
+   * @param encoded encoded identifier
+   * @return decoded identifier
+   * @throws IllegalArgumentException if the encoded value is malformed
+   */
+  public static NameIdentifier decode(String encoded) {
+    if (encoded == null || encoded.isEmpty()) {
+      throw new IllegalArgumentException("Cannot decode a null or empty entity identifier");
+    }
+    if (!encoded.startsWith(ENCODED_PREFIX)) {
+      return NameIdentifier.parse(encoded);
+    }
+
+    int offset = ENCODED_PREFIX.length();
+    int separator = encoded.indexOf(':', offset);
+    int levelCount = parseLength(encoded, offset, separator);
+    if (levelCount <= 0) {
+      throw new IllegalArgumentException("Entity identifier must contain at least one level");
+    }
+
+    String[] levels = new String[levelCount];
+    offset = separator + 1;
+    for (int index = 0; index < levelCount; index++) {
+      separator = encoded.indexOf(':', offset);
+      int levelLength = parseLength(encoded, offset, separator);
+      offset = separator + 1;
+      if (levelLength <= 0 || levelLength > encoded.length() - offset) {
+        throw new IllegalArgumentException("Invalid entity identifier level length");
+      }
+      levels[index] = encoded.substring(offset, offset + levelLength);
+      offset += levelLength;
+    }
+    if (offset != encoded.length()) {
+      throw new IllegalArgumentException("Unexpected trailing data in entity identifier");
+    }
+    return NameIdentifier.of(levels);
+  }

Review Comment:
   `ModelMetaService.java:189,393` still write raw names while all readers now `decode()` — a model
   under a schema named `a.b` silently decodes to the wrong identifier.



##########
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();

Review Comment:
    This only covers outer rollback, not a change-log insert failing
   after the entity write — deleting the new `finally { rollback }` blocks keeps the suite green.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3756725521


##########
core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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 java.util.Arrays;
+import org.apache.gravitino.NameIdentifier;
+
+/** Losslessly encodes entity identifiers in the change log while retaining legacy readability. */
+public final class EntityChangeLogNameIdentifierCodec {
+
+  private static final String ENCODED_PREFIX = "gravitino:v1:";
+
+  private EntityChangeLogNameIdentifierCodec() {}
+
+  /**
+   * Encodes an identifier for the {@code entity_full_name} change-log column.
+   *
+   * <p>Identifiers without ambiguous dots retain their historical dot-joined representation, so
+   * older nodes can continue consuming ordinary names during a rolling upgrade. Identifiers whose
+   * segments contain dots use a length-prefixed representation.
+   *
+   * @param ident identifier to encode
+   * @return encoded identifier
+   */
+  public static String encode(NameIdentifier ident) {
+    String legacyValue = ident.toString();
+    String[] levels = levels(ident);
+    boolean requiresEncoding =
+        legacyValue.startsWith(ENCODED_PREFIX)
+            || Arrays.stream(levels).anyMatch(level -> level.indexOf('.') >= 0);
+    if (!requiresEncoding) {
+      return legacyValue;
+    }
+
+    StringBuilder encoded = new StringBuilder(ENCODED_PREFIX).append(levels.length).append(':');
+    for (String level : levels) {
+      encoded.append(level.length()).append(':').append(level);
+    }
+    return encoded.toString();
+  }
+
+  /**
+   * Decodes an identifier read from the {@code entity_full_name} change-log column.
+   *
+   * @param encoded encoded identifier
+   * @return decoded identifier
+   * @throws IllegalArgumentException if the encoded value is malformed
+   */
+  public static NameIdentifier decode(String encoded) {
+    if (encoded == null || encoded.isEmpty()) {
+      throw new IllegalArgumentException("Cannot decode a null or empty entity identifier");
+    }
+    if (!encoded.startsWith(ENCODED_PREFIX)) {
+      return NameIdentifier.parse(encoded);
+    }
+
+    int offset = ENCODED_PREFIX.length();
+    int separator = encoded.indexOf(':', offset);
+    int levelCount = parseLength(encoded, offset, separator);
+    if (levelCount <= 0) {
+      throw new IllegalArgumentException("Entity identifier must contain at least one level");
+    }
+
+    String[] levels = new String[levelCount];
+    offset = separator + 1;
+    for (int index = 0; index < levelCount; index++) {
+      separator = encoded.indexOf(':', offset);
+      int levelLength = parseLength(encoded, offset, separator);
+      offset = separator + 1;
+      if (levelLength <= 0 || levelLength > encoded.length() - offset) {
+        throw new IllegalArgumentException("Invalid entity identifier level length");
+      }
+      levels[index] = encoded.substring(offset, offset + levelLength);
+      offset += levelLength;
+    }
+    if (offset != encoded.length()) {
+      throw new IllegalArgumentException("Unexpected trailing data in entity identifier");
+    }
+    return NameIdentifier.of(levels);
+  }

Review Comment:
   Use another PR #12416 to track it.



##########
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();

Review Comment:
   done



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766241068


##########
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:
   Add a test of update log failed → rollback testers



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#issuecomment-5267197369

   All fixed, just wait for the CI to pass


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] fix(core): complete cached entity change-log coverage [gravitino]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#issuecomment-5199804455

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.34% **`+0.35%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|84.71%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|1.72%|:red_circle:|
   |api|49.37%|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |aws|42.04%|:green_circle:|
   |azure|2.47%|:red_circle:|
   |catalog-common|9.92%|:red_circle:|
   |catalog-fileset|79.74%|:green_circle:|
   |catalog-glue|68.95%|:green_circle:|
   |catalog-hive|79.4%|:green_circle:|
   |catalog-jdbc-common|45.7%|:green_circle:|
   |catalog-jdbc-doris|81.8%|:green_circle:|
   |catalog-jdbc-mysql|79.33%|:green_circle:|
   |catalog-jdbc-postgresql|83.39%|:green_circle:|
   |catalog-jdbc-starrocks|79.16%|:green_circle:|
   |catalog-kafka|77.01%|:green_circle:|
   |catalog-lakehouse-generic|59.18%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.86%|:green_circle:|
   |catalog-lakehouse-paimon|84.23%|:green_circle:|
   |catalog-model|77.72%|:green_circle:|
   |cli|44.48%|:green_circle:|
   |client-java|78.27%|:green_circle:|
   |common|52.11%|:green_circle:|
   |core|83.45% **`+0.23%`**|:green_circle:|
   |filesystem-hadoop3|77.28%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|48.68%|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|14.12%|:red_circle:|
   |hadoop-auth|68.0%|:green_circle:|
   |hadoop-common|12.7%|:red_circle:|
   |hive-metastore-common|53.4%|:green_circle:|
   |iceberg-common|64.75%|:green_circle:|
   |iceberg-rest-server|75.1%|:green_circle:|
   |idp-basic|86.02%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|62.92%|:green_circle:|
   |lance-common|31.75%|:red_circle:|
   |lance-rest-server|63.47%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.24%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|85.76%|:green_circle:|
   |server-common|76.46% **`-1.07%`**|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|45.89%|:green_circle:|
   |tencent|69.84%|:green_circle:|
   |trino-connector|40.29%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |core|[Coherence.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/Coherence.java)|100.0%|:green_circle:|
   ||[EntityCacheChangeLogListener.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java)|100.0%|:green_circle:|
   ||[MetalakeMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java)|100.0%|:green_circle:|
   ||[TableMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java)|100.0%|:green_circle:|
   ||[ViewMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java)|100.0%|:green_circle:|
   ||[SessionUtils.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/utils/SessionUtils.java)|100.0%|:green_circle:|
   ||[CatalogMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java)|98.65%|:green_circle:|
   ||[SchemaMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java)|98.62%|:green_circle:|
   ||[FilesetMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java)|96.43%|:green_circle:|
   ||[BaseEntityCache.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java)|92.31%|:green_circle:|
   ||[EntityChangeLogNameIdentifierCodec.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/EntityChangeLogNameIdentifierCodec.java)|90.48%|:green_circle:|
   ||[CatalogChangeLogListener.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/catalog/CatalogChangeLogListener.java)|88.37%|:green_circle:|
   ||[SqlSessions.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessions.java)|87.8%|:green_circle:|
   ||[JDBCBackend.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java)|81.4%|:green_circle:|
   ||[TopicMetaService.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java)|78.64%|:green_circle:|
   ||[RelationalEntityStore.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java)|74.27%|:green_circle:|
   ||[CaffeineEntityCache.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java)|70.41%|:green_circle:|
   ||[NoOpsCache.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/NoOpsCache.java)|60.0%|:green_circle:|
   ||[EntityCache.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/EntityCache.java)|0.0%|:red_circle:|
   ||[SupportsEntityStoreCache.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/core/src/main/java/org/apache/gravitino/cache/SupportsEntityStoreCache.java)|0.0%|:red_circle:|
   |server-common|[JcasbinChangeListener.java](https://github.com/yuqi1129/gravitino/blob/5548367c8f6c56b2a60b80e1f8bc856e2169ba2e/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java)|52.94%|:red_circle:|
   
   </details>


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3756070732


##########
server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java:
##########


Review Comment:
   Yeah, that's indeed a problem, and I have trouble-shoting & modifed it. 



##########
server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinChangeListener.java:
##########


Review Comment:
   OK



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766040943


##########
core/src/test/java/org/apache/gravitino/storage/TestEntityStorageChangeLog.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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;
+
+import java.time.Instant;
+import java.util.List;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.EntityStoreFactory;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+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.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mockito;
+
+/** Tests entity change logs through the relational {@link EntityStore}. */
+@Tag("gravitino-docker-test")

Review Comment:
   Does this need to be tested in Docker?



##########
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:
   How did you fix this here?



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766211111


##########
core/src/test/java/org/apache/gravitino/storage/TestEntityStorageChangeLog.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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;
+
+import java.time.Instant;
+import java.util.List;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.EntityStoreFactory;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+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.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mockito;
+
+/** Tests entity change logs through the relational {@link EntityStore}. */
+@Tag("gravitino-docker-test")

Review Comment:
   Yeah, it will start MySQL/PG to verify the SQL sentence.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3766249306


##########
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:
   Add testers for enable Coherence 



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] fix(core): complete cached entity change-log coverage [gravitino]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3719029460


##########
core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java:
##########
@@ -178,95 +183,45 @@ public boolean exists(NameIdentifier ident, Entity.EntityType entityType) throws
   @Override
   public <E extends Entity & HasIdentifier> void insert(E e, boolean overwritten)
       throws EntityAlreadyExistsException, IOException {
-    if (e instanceof BaseMetalake) {
-      MetalakeMetaService.getInstance().insertMetalake((BaseMetalake) e, overwritten);
-    } else if (e instanceof CatalogEntity) {
-      CatalogMetaService.getInstance().insertCatalog((CatalogEntity) e, overwritten);
-    } else if (e instanceof SchemaEntity) {
-      SchemaMetaService.getInstance().insertSchema((SchemaEntity) e, overwritten);
-    } else if (e instanceof TableEntity) {
-      TableMetaService.getInstance().insertTable((TableEntity) e, overwritten);
-    } else if (e instanceof FilesetEntity) {
-      FilesetMetaService.getInstance().insertFileset((FilesetEntity) e, overwritten);
-    } else if (e instanceof TopicEntity) {
-      TopicMetaService.getInstance().insertTopic((TopicEntity) e, overwritten);
-    } else if (e instanceof UserEntity) {
-      UserMetaService.getInstance().insertUser((UserEntity) e, overwritten);
-    } else if (e instanceof RoleEntity) {
-      RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);
-    } else if (e instanceof GroupEntity) {
-      GroupMetaService.getInstance().insertGroup((GroupEntity) e, overwritten);
-    } else if (e instanceof TagEntity) {
-      TagMetaService.getInstance().insertTag((TagEntity) e, overwritten);
-    } else if (e instanceof ModelEntity) {
-      ModelMetaService.getInstance().insertModel((ModelEntity) e, overwritten);
-    } else if (e instanceof ModelVersionEntity) {
-      if (overwritten) {
-        LOG.warn(
-            "'overwritten' is not supported for model version meta, ignoring this flag and "
-                + "inserting the new model version.");
+    if (!overwritten || !BaseEntityCache.isCacheable(e.type())) {
+      insertEntity(e, overwritten);
+      return;
+    }
+
+    SessionUtils.beginTransaction();
+    boolean committed = false;
+    try {
+      insertEntity(e, true);
+      insertEntityChange(e.nameIdentifier(), e.type(), OperateType.ALTER);
+      SessionUtils.commitTransaction();
+      committed = true;
+    } finally {
+      if (!committed) {
+        SessionUtils.rollbackTransaction();
       }
-      ModelVersionMetaService.getInstance().insertModelVersion((ModelVersionEntity) e);
-    } else if (e instanceof FunctionEntity) {
-      FunctionMetaService.getInstance().insertFunction((FunctionEntity) e, overwritten);
-    } else if (e instanceof PolicyEntity) {
-      PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
-    } else if (e instanceof JobTemplateEntity) {
-      JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);
-    } else if (e instanceof JobEntity) {
-      JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);
-    } else if (e instanceof ViewEntity) {
-      ViewMetaService.getInstance().insertView((ViewEntity) e, overwritten);
-    } else if (e instanceof GenericEntity) {
-      GenericEntity genericEntity = (GenericEntity) e;
-      throw new UnsupportedEntityTypeException(
-          "Unsupported entity type: %s for insert operation", genericEntity.type());
-    } else {
-      throw new UnsupportedEntityTypeException(
-          "Unsupported entity type: %s for insert operation", e.getClass());
     }
   }
 
   @Override
   public <E extends Entity & HasIdentifier> E update(
       NameIdentifier ident, Entity.EntityType entityType, Function<E, E> updater)
       throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
-    switch (entityType) {
-      case METALAKE:
-        return (E) MetalakeMetaService.getInstance().updateMetalake(ident, updater);
-      case CATALOG:
-        return (E) CatalogMetaService.getInstance().updateCatalog(ident, updater);
-      case SCHEMA:
-        return (E) SchemaMetaService.getInstance().updateSchema(ident, updater);
-      case TABLE:
-        return (E) TableMetaService.getInstance().updateTable(ident, updater);
-      case FILESET:
-        return (E) FilesetMetaService.getInstance().updateFileset(ident, updater);
-      case TOPIC:
-        return (E) TopicMetaService.getInstance().updateTopic(ident, updater);
-      case USER:
-        return (E) UserMetaService.getInstance().updateUser(ident, updater);
-      case GROUP:
-        return (E) GroupMetaService.getInstance().updateGroup(ident, updater);
-      case ROLE:
-        return (E) RoleMetaService.getInstance().updateRole(ident, updater);
-      case TAG:
-        return (E) TagMetaService.getInstance().updateTag(ident, updater);
-      case MODEL:
-        return (E) ModelMetaService.getInstance().updateModel(ident, updater);
-      case MODEL_VERSION:
-        return (E) ModelVersionMetaService.getInstance().updateModelVersion(ident, updater);
-      case FUNCTION:
-        return (E) FunctionMetaService.getInstance().updateFunction(ident, updater);
-      case POLICY:
-        return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
-      case JOB_TEMPLATE:
-        return (E) JobTemplateMetaService.getInstance().updateJobTemplate(ident, updater);
-      case VIEW:
-        return (E) ViewMetaService.getInstance().updateView(ident, updater);
-      default:
-        throw new UnsupportedEntityTypeException(
-            "Unsupported entity type: %s for update operation", entityType);
+    if (!BaseEntityCache.isCacheable(entityType)) {
+      return updateEntity(ident, entityType, updater);
+    }
+
+    SessionUtils.beginTransaction();
+    boolean committed = false;
+    try {
+      E updatedEntity = updateEntity(ident, entityType, updater);
+      insertEntityChange(ident, entityType, OperateType.ALTER);
+      SessionUtils.commitTransaction();
+      committed = true;
+      return updatedEntity;
+    } finally {
+      if (!committed) {
+        SessionUtils.rollbackTransaction();
+      }
     }

Review Comment:
   The backend now unconditionally starts/commits/rolls back a transaction for cacheable updates. This breaks caller-managed transaction semantics unless `SessionUtils` explicitly supports nested transactions with correct ownership (e.g., savepoints or reference counting). In this PR, tests also begin a transaction and then call `backend.update()`, which implies nesting is expected. Recommendation (mandatory): make transaction ownership explicit by only beginning/committing/rolling back when there is no existing transaction (e.g., via a `SessionUtils.isInTransaction()`/`inTransaction()` check), and otherwise participate in the caller’s transaction without committing it.



##########
core/src/main/java/org/apache/gravitino/storage/relational/EntityCacheChangeLogListener.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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) {
+        LOG.warn(
+            "Failed to process entity change log record: fullName={}, entityType={}",
+            change.getFullName(),
+            change.getEntityType(),
+            e);
+      }
+    }
+  }
+
+  private EntityType entityType(EntityChangeRecord change) {
+    if (change.getEntityType() == null) {
+      LOG.warn("Invalid entity type in entity change log: null");
+      return null;
+    }
+    try {
+      return EntityType.valueOf(change.getEntityType().toUpperCase(Locale.ROOT));
+    } catch (IllegalArgumentException e) {
+      LOG.warn("Unknown entity type in entity change log: {}", change.getEntityType());
+      return null;
+    }
+  }
+
+  private NameIdentifier identifier(EntityChangeRecord change) {
+    String fullName = change.getFullName();
+    if (fullName == null || fullName.isEmpty()) {
+      LOG.warn("Invalid full name in entity change log: {}", fullName);
+      return null;
+    }
+    // The change log stores the entity's NameIdentifier#toString(), a dot-joined full name. Split
+    // it back into levels the same way the catalog cache listener does; this is exact as long as
+    // no name segment contains a dot.
+    return NameIdentifier.of(fullName.split("\\."));

Review Comment:
   Reconstructing `NameIdentifier` by splitting on '.' is only correct if name segments are guaranteed not to contain dots. If dots are allowed in any segment, this will invalidate the wrong key(s) and can leave stale cache entries. Recommendation (mandatory): either enforce 'no dots in names' at validation time (and reference that invariant here), or change the change-log encoding/parsing to a lossless format (e.g., store structured name levels or an escaped/encoded representation).



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -56,10 +54,9 @@
  * schemas and tables under it).
  *
  * <p>Relation query results are NOT cached by this implementation; relation and list operations
- * always fall back to the {@code EntityStore}. Entity types whose materialized form embeds
- * relation-derived data ({@code USER}, {@code GROUP}, {@code ROLE}) are excluded from caching
- * entirely by {@link BaseEntityCache#put}, because without relation tracking their entries could
- * not be invalidated when the referenced entities change.
+ * always fall back to the {@code EntityStore}. Only the self-contained metadata objects listed in
+ * {@link BaseEntityCache#isCacheable} are cached; every other type (user/group/role, model/model
+ * version, function, and operational entities) is read straight from the {@code EntityStore}.

Review Comment:
   The Javadoc claims 'operational entities' are read straight from the store, but `BaseEntityCache` now explicitly includes `EntityType.JOB` in the cacheable allowlist. Recommendation (mandatory): update this Javadoc to match actual behavior (e.g., remove 'operational entities' or spell out which operational types are excluded while noting that jobs are cacheable).



##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -115,6 +121,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. A SHARED cache (or a disabled
+    // NoOpsCache) has nothing per-node to invalidate, so no listener is registered.
+    if (cache.coherence() == Coherence.LOCAL_PER_NODE && !(cache instanceof NoOpsCache)) {
+      this.entityCacheChangeLogListener = new EntityCacheChangeLogListener(cache);
+      this.entityChangeLogPoller.registerListener(entityCacheChangeLogListener);
+    }

Review Comment:
   Needing `!(cache instanceof NoOpsCache)` alongside `coherence() == LOCAL_PER_NODE` suggests the `Coherence` model can’t fully express 'no caching'. Recommendation (optional): have `NoOpsCache` override `coherence()` to a value that naturally skips listener registration (e.g., introduce a `NONE` coherence or define `NoOpsCache` as `SHARED`/non-propagating), so the registration condition doesn’t require type checks.



##########
core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java:
##########
@@ -64,20 +75,20 @@ private void assertEntityChange(
       Entity.EntityType entityType,
       String fullName,
       OperateType operateType) {
-    Assertions.assertTrue(
-        listEntityChanges(lastConsumedId).stream()
-            .anyMatch(
-                record ->
-                    record.getMetalakeName().equals(metalakeName)
-                        && record.getEntityType().equals(entityType.name())
-                        && record.getFullName().equals(fullName)
-                        && record.getOperateType() == operateType),
-        String.format("Missing %s %s changelog for %s", entityType, operateType, fullName));
+    List<EntityChangeRecord> entityChanges = listEntityChanges(lastConsumedId);
+    Assertions.assertEquals(1, entityChanges.size());
+    EntityChangeRecord entityChange = entityChanges.get(0);
+    Assertions.assertEquals(metalakeName, entityChange.getMetalakeName());
+    Assertions.assertEquals(entityType.name(), entityChange.getEntityType());
+    Assertions.assertEquals(fullName, entityChange.getFullName());
+    Assertions.assertEquals(operateType, entityChange.getOperateType());

Review Comment:
   Asserting `entityChanges.size() == 1` makes the tests sensitive to any additional change-log rows written after `lastConsumedId` (e.g., if tests ever run concurrently against a shared DB, or if background activity writes to the log). Recommendation (optional but strongly suggested): assert that the expected record exists (filter/match on metalake/type/fullName/operateType) rather than requiring the list to contain exactly one element.



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12374:
URL: https://github.com/apache/gravitino/pull/12374#discussion_r3756732502


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########


Review Comment:
   Fixed in #12416



-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [#12151] improvement(core): complete cached entity change-log coverage [gravitino]

Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 merged PR #12374:
URL: https://github.com/apache/gravitino/pull/12374


-- 
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: commits-unsubscribe@gravitino.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org