You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "xunliu (via GitHub)" <gi...@apache.org> on 2025/08/27 02:35:56 UTC

[PR] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   
   ### What changes were proposed in this pull request?
   
   (Please outline the changes and how this PR fixes the issue.)
   
   ### Why are the changes needed?
   
   (Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, describe the bug.)
   
   Fix: #7804, #7797, #8155, #8181, #8182
   
   ### Does this PR introduce _any_ user-facing change?
   
   (Please list the user-facing changes introduced by your change, including
     1. Change in user-facing APIs.
     2. Addition or removal of property keys.)
   
   ### How was this patch tested?
   
   (Please test your changes, and provide instructions on how to test it:
     1. If you add a feature or fix a bug, add a test to cover your changes.
     2. If you fix a flaky test, repeat it for many times to prove it works.)
   


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,66 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    EntityCacheKey valueForExactKey;
+    if (relTypeOpt.isEmpty()) {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(EntityCacheKey.of(identifier, type).toString());
+    } else {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(
+              EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+    }

Review Comment:
   Fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +86,16 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {
+                  EntityCache cache = (EntityCache) store;
+                  roles.forEach(
+                          roleName -> {
+                            Namespace namespaceRole = NamespaceUtil.ofRole(metalake);
+                            NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+                            cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+                          });

Review Comment:
   I think we should wrap this with the cache lock to keep the consistency.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -194,6 +207,7 @@ public void clear() {
     withLock(
         () -> {
           cacheData.invalidateAll();
+          reverseIndex = new ReverseIndexCache();
           cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   I'm a little confused why do we use `new xxx` to clear the memory?



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // first invalidate this entity
+    EntityCacheKey currentKey = cacheIndex.getValueForExactKey(identifier.toString());
+    if (currentKey != null) {
+      // already removed
+      cacheData.invalidate(currentKey);
+      cacheIndex.remove(currentKey.toString());
+    }
+
+    // Remove child entities
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = ((HasIdentifier) entity).nameIdentifier();
+                if (!child.equals(identifier)) {
+                  invalidateEntitiesOld(child);

Review Comment:
   Why do we need a recursive call here?



##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheKey.java:
##########
@@ -23,26 +23,11 @@
 import java.util.Objects;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.SupportsRelationOperations;
 
 /** Key for Entity cache. */
 public class EntityCacheKey {

Review Comment:
   Do we still need this class? Seems not so useful.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // first invalidate this entity
+    EntityCacheKey currentKey = cacheIndex.getValueForExactKey(identifier.toString());
+    if (currentKey != null) {
+      // already removed
+      cacheData.invalidate(currentKey);
+      cacheIndex.remove(currentKey.toString());
+    }
+
+    // Remove child entities
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = ((HasIdentifier) entity).nameIdentifier();
+                if (!child.equals(identifier)) {
+                  invalidateEntitiesOld(child);
+                }
+              });
+        });

Review Comment:
   My feeling is that the complexity of the logic is quite high, this part may requires lots of time to execute, is there's a way to optimize this code?



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {

Review Comment:
   What is the meaning of `Old`?



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.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.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeys.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());

Review Comment:
   Directly calling `nameIdentifiter` should be enough.



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.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.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =

Review Comment:
   What's the meaning of `No`?



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,
               userEntity -> {
                 List<RoleEntity> roleEntities = Lists.newArrayList();

Review Comment:
   Fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,
               userEntity -> {
                 List<RoleEntity> roleEntities = Lists.newArrayList();

Review Comment:
   I revert this part code, we didn't need to modify here.
   https://github.com/apache/gravitino/commit/649e7efc380eefcc64c7f29db1c2f042c8c1400c



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());

Review Comment:
   fixed



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,62 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
+
+    EntityCacheKey valueForExactKey =
+        cacheIndex.getValueForExactKey(
+            relTypeOpt.isEmpty()
+                ? EntityCacheKey.of(identifier, type).toString()
+                : EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+
+    if (valueForExactKey == null) {
+      // No key to remove
+      return false;
+    }
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    queue.offer(valueForExactKey);
+
+    while (!queue.isEmpty()) {
+      EntityCacheKey currentKeyToRemove = queue.poll();
+
+      cacheData.invalidate(currentKeyToRemove);
+      cacheIndex.remove(currentKeyToRemove.toString());
+
+      // Remove related entity keys
+      List<EntityCacheKey> relatedEntityKeysToRemove =
+          Lists.newArrayList(
+              cacheIndex.getValuesForKeysStartingWith(currentKeyToRemove.identifier().toString()));
+      queue.addAll(relatedEntityKeysToRemove);
+
+      // Look up from reverse index to go to next depth
+      List<EntityCacheKey> reverseKeysToRemove =
+          Lists.newArrayList(
+              reverseIndex.getValuesForKeysStartingWith(
+                  currentKeyToRemove.identifier().toString()));
+      reverseKeysToRemove.forEach(
+          key -> {
+            // Remove from reverse index
+            // Convert EntityCacheRelationKey to EntityCacheKey
+            reverseIndex
+                .getKeysStartingWith(key.toString())
+                .forEach(
+                    reverseIndexKey -> {
+                      reverseIndex.remove(reverseIndexKey.toString());
+                    });
+          });
+
+      reverseKeysToRemove.forEach(queue::offer);

Review Comment:
   fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   Fixed.
   Base offline discussion, use all fields to cache.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   you should also uncomment the IT codes and make it pass:
   https://github.com/apache/gravitino/blob/c347a08d6c80ee271ffed4e6446bd63a527e5c9a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java#L468-L475


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCache.java:
##########
@@ -120,7 +122,116 @@ void testEnableStats() {
     config.set(Configs.CACHE_STATS_ENABLED, true);
     EntityCache cache = new CaffeineEntityCache(config);
 
-    Assertions.assertDoesNotThrow(() -> cache.put(entity1));
+    Assertions.assertDoesNotThrow(() -> cache.put(entity_m1c1s1));
+  }
+
+  @Test
+  /**
+   * SCENE[0] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * ACTIVE: INVALIDATE Role1, then need to remove RECORD1 and RECORD2 <br>
+   */
+  void testRemoveCacheRelation0() {
+    EntityCache cache = getNormalCache();
+
+    UserEntity testUserEntity = TestUtil.getTestUserEntity();
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_USER_REL,
+        ImmutableList.of(testUserEntity));
+
+    cache.invalidate(testRoleEntity.nameIdentifier(), Entity.EntityType.ROLE);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[1] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * CACHE2 = catalog1 -> [tab1, tab2] <br>
+   * ACTIVE: INVALIDATE Role1, then need to remove RECORD1 and RECORD2 <br>
+   */
+  void testRemoveCacheRelation1() {
+    EntityCache cache = getNormalCache();
+
+    UserEntity testUserEntity = TestUtil.getTestUserEntity();
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(testGroupEntity);
+    cache.put(testUserEntity);
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_USER_REL,
+        ImmutableList.of(testUserEntity));
+
+    cache.invalidate(testRoleEntity.nameIdentifier(), Entity.EntityType.ROLE);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[2] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * CACHE2 = catalog1 -> [tab1, tab2] <br>
+   * ACTIVE: INVALIDATE catalog1, then need to remove RECORD1 and RECORD2
+   */
+  void testRemoveCacheRelation2() {
+    EntityCache cache = getNormalCache();
+
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(testGroupEntity);
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+
+    cache.invalidate(testGroupEntity.nameIdentifier(), Entity.EntityType.GROUP);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[3]<br>
+   * CACHE1 = Metadata1 -> []<br>
+   * CACHE2 = Metadata1.Catalog1.tab1 -> []<br>
+   * ACTIVE: INVALIDATE Metadata1, then need to remove RECORD1 and RECORD2<br>
+   */
+  void testRemoveCacheRelation3() {
+    EntityCache cache = getNormalCache();
+
+    BaseMetalake testMetalake = TestUtil.getTestMetalake();
+    TableEntity testTableEntity = TestUtil.getTestTableEntity();
+
+    cache.put(testMetalake);
+    cache.put(testTableEntity);
+
+    cache.invalidate(testMetalake.nameIdentifier(), Entity.EntityType.CATALOG);

Review Comment:
   The test is invalidating a metalake entity but using `Entity.EntityType.CATALOG` instead of `Entity.EntityType.METALAKE`.
   ```suggestion
       cache.invalidate(testMetalake.nameIdentifier(), Entity.EntityType.METALAKE);
   ```



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -272,6 +286,7 @@ public <E, T extends Exception> E withCacheLock(ThrowingSupplier<E, T> action) t
   protected void invalidateExpiredItem(EntityCacheKey key) {
     withLock(
         () -> {
+          reverseIndex.remove(key);
           cacheIndex.remove(key.toString());
         });
   }

Review Comment:
   The method parameter is `EntityCacheKey` but should be `EntityCacheRelationKey` to match the cache structure and reverseIndex expectations.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -339,6 +364,55 @@ private boolean invalidateEntities(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // SCENE[1]
+    // RECORD1 = Role1 -> [catalog1, catalog2]
+    // RECORD2 = catalog1 -> [tab1, tab2]
+    // INVALIDATE Role1, then need to remove RECORD1 and RECORD2
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = getNameIdentifier(entity);
+                if (!child.equals(identifier)) {
+                  invalidateEntities(child);

Review Comment:
   hi @unknowntpo Thank you for your report this issue, I will fix it.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -78,11 +79,21 @@ public class CaffeineEntityCache extends BaseEntityCache {
   private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());
   private final ReentrantLock opLock = new ReentrantLock();
 
-  /** Cache part */
-  private final Cache<EntityCacheKey, List<Entity>> cacheData;
+  /** Cache data structure. cacheData[0] = Role1-KEY -> [catalog1, catalog2] */
+  private final Cache<EntityCacheRelationKey, List<Entity>> cacheData;
 
-  /** Index part */
-  private RadixTree<EntityCacheKey> cacheIndex;
+  /**
+   * Cache reverse index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] =
+   * catalog1 -> [tab1, tab2] reverseIndex[0] = catalog1-KEY -> Role1 reverseIndex[1] = catalog2-KEY
+   * -> Role1 reverseIndex[3] = tab1-KEY -> catalog1 reverseIndex[4] = tab2-KEY -> catalog1
+   */
+  private ReverseIndexCache reverseIndex;
+
+  /**
+   * Cache Index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] = catalog1 ->
+   * [tab1, tab2] cacheIndex[0] = Role1-KEY -> Role1 cacheIndex[1] = Role1-KEY -> Role1

Review Comment:
   Removed invalid comments



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java:
##########
@@ -466,17 +466,16 @@ public void testAssociatePoliciesToCatalog() {
     Assertions.assertTrue(policies7[0].enabled());
 
     // Test disable the policy then list again
-    // todo: uncomment after the bug is fixed
-    // https://github.com/apache/gravitino/issues/7787#issue-3255540700
-    //    Assertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));
-    //    Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();
-    //    Assertions.assertEquals(1, policies8.length);
-    //    Assertions.assertEquals(policy1.name(), policies8[0].name());
-    //    Assertions.assertFalse(policies8[0].enabled());
+    Assertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));
+    Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();
+    Assertions.assertEquals(1, policies8.length);
+    Assertions.assertEquals(policy1.name(), policies8[0].name());
+    Assertions.assertFalse(policies8[0].enabled());
+    Assertions.assertDoesNotThrow(() -> metalake.enablePolicy(policy1.name()));
 
     // Test get associated policy for catalog
     Policy policy = relationalCatalog.supportsPolicies().getPolicy(policy1.name());
-    Assertions.assertEquals(policy1, policy);
+    Assertions.assertEquals(policy1.enabled(), policy.enabled());

Review Comment:
   hi @mchades 
   Because the policy modifies some information, So I changed assert conditions.
   
   <img width="1458" height="295" alt="image" src="https://github.com/user-attachments/assets/f9a58800-ff5a-4dd2-974a-7b48a22792b1" />
   



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   Fixed.
   Base offline discussion with @mchades , use all fields to cache.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public void clean() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   ditto



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public void clean() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public int size() {
+    return reverseIndex.size();
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeySerialNumber =
+        String.format("%s-%d", strEntityCacheKey, entityKeys.size());
+    reverseIndex.put(strEntityCacheKeySerialNumber, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent = ((HasIdentifier) entity).nameIdentifier();
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  public void registerReverseRule(Class<? extends Entity> entityClass, ReverseIndexRule rule) {
+    reverseIndexRules.put(entityClass, rule);
+  }
+
+  /** Processes an entity and updates the reverse index accordingly. */
+  public void indexEntity(Entity entity, EntityCacheRelationKey key) {
+    ReverseIndexRule rule = reverseIndexRules.get(entity.getClass());
+    if (rule != null) {
+      rule.indexEntity(entity, key, this);
+    }
+  }
+
+  /** Functional interface for processing reverse index rules. */
+  @FunctionalInterface
+  public interface ReverseIndexRule {

Review Comment:
   It can be package access level.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -194,6 +207,7 @@ public void clear() {
     withLock(
         () -> {
           cacheData.invalidateAll();
+          reverseIndex = new ReverseIndexCache();
           cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   It seems that we will only clear the cache if the Gravitino server is going to shut down, perhaps there is no need to create a new instance here. 



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());

Review Comment:
   ReverseIndexRules.class.getName() -> ReverseIndexRules.class



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} -
+ * UserEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} - RoleEntity
+ * role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} - {serial-number}: Because
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;
+                      default:

Review Comment:
   I see



##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheRelationKey.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.cache;
+
+import java.util.Objects;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.SupportsRelationOperations;
+
+/** Key for Entity cache. */
+public class EntityCacheRelationKey extends EntityCacheKey {
+  private final SupportsRelationOperations.Type relationType;
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation, it can be null.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(
+      NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relationType) {
+    return new EntityCacheRelationKey(ident, type, relationType);
+  }
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(NameIdentifier ident, Entity.EntityType type) {
+    return new EntityCacheRelationKey(ident, type, null);
+  }
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given parameters.
+   *
+   * @param identifier The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation.
+   */
+  private EntityCacheRelationKey(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      SupportsRelationOperations.Type relationType) {
+    super(identifier, type);
+    this.relationType = relationType;
+  }
+
+  /**
+   * Returns the type of the relation.
+   *
+   * @return The type of the relation.
+   */
+  public SupportsRelationOperations.Type relationType() {
+    return relationType;
+  }
+
+  /**
+   * Compares two instances of {@link EntityCacheRelationKey} for equality. The comparison is done
+   * by comparing the identifier, type, and relationType of the instances.
+   *
+   * @param obj The object to compare to.
+   * @return {@code true} if the objects are equal, {@code false} otherwise.
+   */
+  @Override
+  public boolean equals(Object obj) {
+    if (obj == this) return true;
+    if (!(obj instanceof EntityCacheRelationKey)) return false;
+    EntityCacheRelationKey other = (EntityCacheRelationKey) obj;
+
+    return Objects.equals(super.identifier(), other.identifier())

Review Comment:
       return super.equals(obj) && Objects.equals(relationType, other.relationType);
   



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,62 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
+
+    EntityCacheKey valueForExactKey =
+        cacheIndex.getValueForExactKey(
+            relTypeOpt.isEmpty()
+                ? EntityCacheKey.of(identifier, type).toString()
+                : EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+
+    if (valueForExactKey == null) {
+      // No key to remove
+      return false;
+    }
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    queue.offer(valueForExactKey);
+
+    while (!queue.isEmpty()) {
+      EntityCacheKey currentKeyToRemove = queue.poll();
+
+      cacheData.invalidate(currentKeyToRemove);
+      cacheIndex.remove(currentKeyToRemove.toString());
+
+      // Remove related entity keys
+      List<EntityCacheKey> relatedEntityKeysToRemove =
+          Lists.newArrayList(
+              cacheIndex.getValuesForKeysStartingWith(currentKeyToRemove.identifier().toString()));
+      queue.addAll(relatedEntityKeysToRemove);
+
+      // Look up from reverse index to go to next depth
+      List<EntityCacheKey> reverseKeysToRemove =
+          Lists.newArrayList(
+              reverseIndex.getValuesForKeysStartingWith(
+                  currentKeyToRemove.identifier().toString()));
+      reverseKeysToRemove.forEach(
+          key -> {
+            // Remove from reverse index
+            // Convert EntityCacheRelationKey to EntityCacheKey
+            reverseIndex
+                .getKeysStartingWith(key.toString())
+                .forEach(
+                    reverseIndexKey -> {
+                      reverseIndex.remove(reverseIndexKey.toString());
+                    });
+          });
+
+      reverseKeysToRemove.forEach(queue::offer);

Review Comment:
   This line can also be optimized as L382



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeysToRemove.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  /** Registers a processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();

Review Comment:
   fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,66 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    EntityCacheKey valueForExactKey;
+    if (relTypeOpt.isEmpty()) {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(EntityCacheKey.of(identifier, type).toString());
+    } else {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(
+              EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+    }
+
+    if (valueForExactKey == null) {
+      // No key to remove
+      return false;
+    }
+
+    queue.offer(valueForExactKey);
+
+    while (!queue.isEmpty()) {
+      EntityCacheKey currentKeyToRemove = queue.poll();
+
+      cacheData.invalidate(currentKeyToRemove);
+      cacheIndex.remove(currentKeyToRemove.toString());
+
+      // Remove related entity keys
+      List<EntityCacheKey> relatedEntityKeysToRemove =
+          Lists.newArrayList(
+              cacheIndex.getValuesForKeysStartingWith(currentKeyToRemove.identifier().toString()));
+      relatedEntityKeysToRemove.forEach(queue::offer);

Review Comment:
   Fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   Yes, this PR fixed `allFields` and `cache inconsistency`, these problems.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -194,6 +207,7 @@ public void clear() {
     withLock(
         () -> {
           cacheData.invalidateAll();
+          reverseIndex = new ReverseIndexCache();
           cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   Fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   @jerqi @yuqi1129 
   Support these types in https://github.com/apache/gravitino/pull/8297/commits/e1eb0fa37831cc129898f6e99fc55e6bfefc5f91



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -194,6 +207,7 @@ public void clear() {
     withLock(
         () -> {
           cacheData.invalidateAll();
+          reverseIndex = new ReverseIndexCache();
           cacheIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   ```
   // Reinitialization: O(1) time complexity
   reverseIndex = new ConcurrentRadixTree<EntityCacheKey>(new DefaultCharSequenceNodeFactory());
   
   // Iterative deletion: O(n) time complexity, requires traversing all nodes
   for (CharSequence key : reverseIndex.getKeysStartingWith("")) {
        reverseIndex.remove(key); // Each removal operation has overhead
   }
   ```



-- 
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] [#7804][#7797][#8155][#8181][#8182][#7787] fix(cache): Fix metadata cache data consistency error [gravitino]

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


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   > I have no further comments.
   
   +1


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   > What do you mean by I'm not sure the grammar is ok? I can't get i
   
   I'm okay with the current changes.


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -564,9 +569,9 @@ subprojects {
       exclude("test/**")
     }
   }
-  tasks.named("compileJava").configure {
-    dependsOn("spotlessCheck")
-  }
+//  tasks.named("compileJava").configure {

Review Comment:
   Fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -116,7 +116,6 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
     cache.put(e);
   }
 
-  @Override

Review Comment:
   Why do we remove the annotation here? Is it by design?



##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   What do you mean by `I'm not sure the grammar is ok`? I can't get it.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case SCHEMA:
+                        entityType = Entity.EntityType.SCHEMA;
+                        Namespace nsSchema = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofSchema(
+                                roleEntity.namespace().level(0), nsSchema.level(0));
+                        break;
+                      case TABLE:
+                        entityType = Entity.EntityType.TABLE;
+                        Namespace nsTable = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofTable(
+                                roleEntity.namespace().level(0),
+                                nsTable.level(0),
+                                nsTable.level(1));
+                        break;
+                      case TOPIC:
+                        entityType = Entity.EntityType.TOPIC;
+                        Namespace nsTopic = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofTopic(
+                                roleEntity.namespace().level(0),
+                                nsTopic.level(0),
+                                nsTopic.level(1));
+                        break;
+                      case MODEL:
+                        entityType = Entity.EntityType.MODEL;
+                        Namespace nsModel = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofModel(
+                                roleEntity.namespace().level(0),
+                                nsModel.level(0),
+                                nsModel.level(1));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsFileset = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsFileset.level(0),
+                                nsFileset.level(1));
+                        break;
+                      default:
+                        LOG.info("Unprocessed securable object type: " + securableObject.type());

Review Comment:
   I'm afraid that we may need to throw an exception here, or it will go to L40 and continue to run the rest of the code.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheKey.java:
##########
@@ -23,26 +23,11 @@
 import java.util.Objects;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.NameIdentifier;
-import org.apache.gravitino.SupportsRelationOperations;
 
 /** Key for Entity cache. */
 public class EntityCacheKey {

Review Comment:
   The EntityCacheRelationKey extends EntityCacheKey



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.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.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeys.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());

Review Comment:
   fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =

Review Comment:
   Fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -330,6 +349,12 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
     return (Caffeine<KEY, VALUE>) builder;
   }
 
+  private NameIdentifier getNameIdentifier(Entity entity) {
+    NameIdentifier nameIdent =
+        NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());

Review Comment:
   Fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   Yes, these are invalid codes. I removed them.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +86,15 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache relationalStore) {
+                  roles.forEach(
+                          roleName -> {
+                            Namespace namespaceRole = NamespaceUtil.ofRole(metalake);
+                            NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+                            relationalStore.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);

Review Comment:
   I revert this part code, we didn't need to modify here.
   https://github.com/apache/gravitino/commit/649e7efc380eefcc64c7f29db1c2f042c8c1400c



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   I'm not sure the grammar is ok. The store may be the wrapper class instead of EntityCache.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   Currently, Authz only has MATEDATA, CATALOG, and FILESET integration tests, so I only added these.
   BTW, we can use the `ReverseIndexRule` to extend TABLE MODEL MODEL VERSION SCHEMA.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -78,11 +79,21 @@ public class CaffeineEntityCache extends BaseEntityCache {
   private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());
   private final ReentrantLock opLock = new ReentrantLock();
 
-  /** Cache part */
-  private final Cache<EntityCacheKey, List<Entity>> cacheData;
+  /** Cache data structure. cacheData[0] = Role1-KEY -> [catalog1, catalog2] */
+  private final Cache<EntityCacheRelationKey, List<Entity>> cacheData;
 
-  /** Index part */
-  private RadixTree<EntityCacheKey> cacheIndex;
+  /**
+   * Cache reverse index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] =
+   * catalog1 -> [tab1, tab2] reverseIndex[0] = catalog1-KEY -> Role1 reverseIndex[1] = catalog2-KEY
+   * -> Role1 reverseIndex[3] = tab1-KEY -> catalog1 reverseIndex[4] = tab2-KEY -> catalog1
+   */

Review Comment:
   I implement these function in the [core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java](https://github.com/apache/gravitino/pull/8297/files/d0ffbcd742189f376e8b82e9bab1b9f5841300e1#diff-c154fd9a0c98634802b70e022b1268e7a77c3260c29908307b9266e968ccf98a)



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,

Review Comment:
   Why do we need this?



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,
               userEntity -> {
                 List<RoleEntity> roleEntities = Lists.newArrayList();

Review Comment:
   Another point, this will execute cache operation multiple times. It's not  an atomic operation.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


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


Review Comment:
   > Is "ROLE" the only case in which one entity includes others? I guess USER/GROUP may have the same issues. Do you fix them all?
   
   hi  @jerryshao  I fixed these issues in 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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   @xunliu , please check it.



##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   After checking the code,  it is indeed that `store` will never be an instance of `EntityCache`.



##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   Another point is that since `RelationalEntityStore` already performed invalidation operations, it seems that there is no need to do the same thing again here. 
   
   https://github.com/apache/gravitino/blob/a9a43808cc18bad12d7fb76930a7ea6470b96180/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java#L120-L124



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   The problem is mentioned here: https://github.com/apache/gravitino/issues/7787#issuecomment-3157777461



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   hi @jerryshao 
   This PR fixed these cache inconsistency problem, https://github.com/apache/gravitino/issues/7804, https://github.com/apache/gravitino/issues/7797, https://github.com/apache/gravitino/issues/8155, https://github.com/apache/gravitino/issues/8181, https://github.com/apache/gravitino/issues/8182, https://github.com/apache/gravitino/issues/7787



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   How about TABLE MODEL MODEL VERSION SCHEMA.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/EntityStore.java:
##########
@@ -149,6 +149,14 @@ <E extends Entity & HasIdentifier> E update(
       NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
       throws IOException, NoSuchEntityException, EntityAlreadyExistsException;
 
+  <E extends Entity & HasIdentifier> E update(

Review Comment:
   I implement these function in the [core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java](https://github.com/apache/gravitino/pull/8297/files/d0ffbcd742189f376e8b82e9bab1b9f5841300e1#diff-c154fd9a0c98634802b70e022b1268e7a77c3260c29908307b9266e968ccf98a)



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/MetadataObjectRoleAuthorizationIT.java:
##########
@@ -82,8 +84,6 @@ public void testCatalogRole() {
         ImmutableList.of(
             SecurableObjects.ofCatalog(
                 CATALOG, ImmutableList.of(Privileges.CreateSchema.allow()))));
-    roleNames = catalogLoadByNormalUser.supportsRoles().listBindingRoleNames();
-    assertArrayEquals(new String[] {role1}, roleNames);

Review Comment:
   Why do we remove this code?



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case SCHEMA:
+                        entityType = Entity.EntityType.SCHEMA;
+                        Namespace nsSchema = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofSchema(
+                                roleEntity.namespace().level(0), nsSchema.level(0));
+                        break;
+                      case TABLE:
+                        entityType = Entity.EntityType.TABLE;
+                        Namespace nsTable = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofTable(
+                                roleEntity.namespace().level(0),
+                                nsTable.level(0),
+                                nsTable.level(1));
+                        break;
+                      case TOPIC:
+                        entityType = Entity.EntityType.TOPIC;
+                        Namespace nsTopic = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofTopic(
+                                roleEntity.namespace().level(0),
+                                nsTopic.level(0),
+                                nsTopic.level(1));
+                        break;
+                      case MODEL:
+                        entityType = Entity.EntityType.MODEL;
+                        Namespace nsModel = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofModel(
+                                roleEntity.namespace().level(0),
+                                nsModel.level(0),
+                                nsModel.level(1));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsFileset = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsFileset.level(0),
+                                nsFileset.level(1));
+                        break;
+                      default:
+                        throw new UnsupportedOperationException(
+                            "Don't support securable object type: " + securableObject.type());
+                    }
+                    Namespace so_namespace = Namespace.of(namespace.levels());

Review Comment:
   Can you please change to use camel style for this variable name.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -339,6 +364,55 @@ private boolean invalidateEntities(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // SCENE[1]
+    // RECORD1 = Role1 -> [catalog1, catalog2]
+    // RECORD2 = catalog1 -> [tab1, tab2]
+    // INVALIDATE Role1, then need to remove RECORD1 and RECORD2
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = getNameIdentifier(entity);
+                if (!child.equals(identifier)) {
+                  invalidateEntities(child);

Review Comment:
   Suppose cache contains:
   
   ```
   testMetalake.system.role.role1:ROLE -> RoleEntity
   testMetalake.system.role.role1:ROLE_OWNER_REL -> contains UserEntity of tester
   testMetalake.system.user.tester:USER -> UserEntity
   testMetalake.system.user.tester2:USER:ROLE_USER_REL -> contains RoleEntity of role1
   ```
   
   When we call `deleteRole` on `role1`, 
   the invalidation chain will be:
   
   `testMetalake.system.role.role1:ROLE` -> 
   `testMetalake.system.role.role1:ROLE_OWNER_REL` -> 
   `testMetalake.system.user.tester:USER` ->
   `testMetalake.system.user.tester2:USER:ROLE_USER_REL` -> 
   `testMetalake.system.role.role1:ROLE`,
   which cause infinite loop, and cause `StackOverflowError`



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -204,6 +204,11 @@ allprojects {
             "[-PtestMode=embedded] or [-PtestMode=deploy]."
         )
       }
+
+      // enable entity cache or not
+      val enableEntityCache = project.properties["enableEntityCache"] as? String ?: "false"
+      param.systemProperty("enableEntityCache", enableEntityCache)

Review Comment:
   Why do we need a configuration for test?



##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   ```
     @Override
     public <E extends Entity & HasIdentifier> List<E> listEntitiesByRelation(
         Type relType, NameIdentifier nameIdentifier, Entity.EntityType identType, boolean allFields)
         throws IOException {
       return cache.withCacheLock(
           () -> {
             Optional<List<E>> entities = cache.getIfPresent(relType, nameIdentifier, identType);
             if (entities.isPresent()) {
               return entities.get();
             }
             List<E> backendEntities =
                 backend.listEntitiesByRelation(relType, nameIdentifier, identType, allFields);
             cache.put(nameIdentifier, identType, relType, backendEntities);
   ```
   
   This code still have two issues, one is mentioned by @mchades about `allFields` problem, another is mentioned by me about cache inconsistency problem. Did you fix this problem also?



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -330,6 +349,12 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
     return (Caffeine<KEY, VALUE>) builder;
   }
 
+  private NameIdentifier getNameIdentifier(Entity entity) {
+    NameIdentifier nameIdent =
+        NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());

Review Comment:
   `HasIdentifier` has a method to get `NameIdentifier`; you don't have to create it manually.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -78,11 +79,21 @@ public class CaffeineEntityCache extends BaseEntityCache {
   private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());
   private final ReentrantLock opLock = new ReentrantLock();
 
-  /** Cache part */
-  private final Cache<EntityCacheKey, List<Entity>> cacheData;
+  /** Cache data structure. cacheData[0] = Role1-KEY -> [catalog1, catalog2] */
+  private final Cache<EntityCacheRelationKey, List<Entity>> cacheData;
 
-  /** Index part */
-  private RadixTree<EntityCacheKey> cacheIndex;
+  /**
+   * Cache reverse index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] =
+   * catalog1 -> [tab1, tab2] reverseIndex[0] = catalog1-KEY -> Role1 reverseIndex[1] = catalog2-KEY
+   * -> Role1 reverseIndex[3] = tab1-KEY -> catalog1 reverseIndex[4] = tab2-KEY -> catalog1
+   */
+  private ReverseIndexCache reverseIndex;
+
+  /**
+   * Cache Index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] = catalog1 ->
+   * [tab1, tab2] cacheIndex[0] = Role1-KEY -> Role1 cacheIndex[1] = Role1-KEY -> Role1

Review Comment:
   I don't quite understand the comment here, what is the meaning of "cacheIndex[0] = Role1-KEY -> Role1 cacheIndex[1] = Role1-KEY -> Role1"?



##########
core/src/main/java/org/apache/gravitino/EntityStore.java:
##########
@@ -149,6 +149,14 @@ <E extends Entity & HasIdentifier> E update(
       NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
       throws IOException, NoSuchEntityException, EntityAlreadyExistsException;
 
+  <E extends Entity & HasIdentifier> E update(

Review Comment:
   Yes, we'd better make it more general.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -78,11 +79,21 @@ public class CaffeineEntityCache extends BaseEntityCache {
   private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());
   private final ReentrantLock opLock = new ReentrantLock();
 
-  /** Cache part */
-  private final Cache<EntityCacheKey, List<Entity>> cacheData;
+  /** Cache data structure. cacheData[0] = Role1-KEY -> [catalog1, catalog2] */
+  private final Cache<EntityCacheRelationKey, List<Entity>> cacheData;
 
-  /** Index part */
-  private RadixTree<EntityCacheKey> cacheIndex;
+  /**
+   * Cache reverse index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] =
+   * catalog1 -> [tab1, tab2] reverseIndex[0] = catalog1-KEY -> Role1 reverseIndex[1] = catalog2-KEY
+   * -> Role1 reverseIndex[3] = tab1-KEY -> catalog1 reverseIndex[4] = tab2-KEY -> catalog1
+   */

Review Comment:
   Is "ROLE" the only case in which one entity includes others? I guess `USER/GROUP` may have the same issues. Do you fix them all?



##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheRelationKey.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.cache;
+
+import java.util.Objects;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.SupportsRelationOperations;
+
+/** Key for Entity cache. */
+public class EntityCacheRelationKey extends EntityCacheKey {
+  private final SupportsRelationOperations.Type relationType;
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation, it can be null.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(
+      NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relationType) {
+    return new EntityCacheRelationKey(ident, type, relationType);
+  }

Review Comment:
   Do we need to add the `allFields` to the key to solve the problem mentioned by @mchades ?



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -339,6 +364,55 @@ private boolean invalidateEntities(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // SCENE[1]
+    // RECORD1 = Role1 -> [catalog1, catalog2]
+    // RECORD2 = catalog1 -> [tab1, tab2]
+    // INVALIDATE Role1, then need to remove RECORD1 and RECORD2
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = getNameIdentifier(entity);
+                if (!child.equals(identifier)) {
+                  invalidateEntities(child);

Review Comment:
   Failed test: https://github.com/apache/gravitino/actions/runs/17262756741/job/48987812078?pr=8297#step:9:3663



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeysToRemove.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  /** Registers a processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public void registerReverseRule(Class<? extends Entity> entityClass, ReverseIndexRule rule) {
+    reverseIndexRules.put(entityClass, rule);
+  }
+
+  /** Processes an entity and updates the reverse index accordingly. */
+  public void indexEntity(Entity entity, EntityCacheRelationKey key) {
+    ReverseIndexRule rule = reverseIndexRules.get(entity.getClass());
+    if (rule != null) {
+      rule.indexEntity(entity, key, this);
+    }

Review Comment:
   Why was it necessary to store a reversed index if there was no rule?



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} -
+ * UserEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} - RoleEntity
+ * role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} - {serial-number}: Because
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;
+                      default:

Review Comment:
   Do we only support `metalake`, `catalog` and `fileset` here?  What about type `table`,`schema`?



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/EntityStore.java:
##########
@@ -149,6 +149,14 @@ <E extends Entity & HasIdentifier> E update(
       NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
       throws IOException, NoSuchEntityException, EntityAlreadyExistsException;
 
+  <E extends Entity & HasIdentifier> E update(

Review Comment:
   Is this method specialized for `role` related operations? It's so, I believe we need to make it more general.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/test/java/org/apache/gravitino/cache/TestCaffeineEntityCache.java:
##########
@@ -120,7 +122,116 @@ void testEnableStats() {
     config.set(Configs.CACHE_STATS_ENABLED, true);
     EntityCache cache = new CaffeineEntityCache(config);
 
-    Assertions.assertDoesNotThrow(() -> cache.put(entity1));
+    Assertions.assertDoesNotThrow(() -> cache.put(entity_m1c1s1));
+  }
+
+  @Test
+  /**
+   * SCENE[0] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * ACTIVE: INVALIDATE Role1, then need to remove RECORD1 and RECORD2 <br>
+   */
+  void testRemoveCacheRelation0() {
+    EntityCache cache = getNormalCache();
+
+    UserEntity testUserEntity = TestUtil.getTestUserEntity();
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_USER_REL,
+        ImmutableList.of(testUserEntity));
+
+    cache.invalidate(testRoleEntity.nameIdentifier(), Entity.EntityType.ROLE);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[1] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * CACHE2 = catalog1 -> [tab1, tab2] <br>
+   * ACTIVE: INVALIDATE Role1, then need to remove RECORD1 and RECORD2 <br>
+   */
+  void testRemoveCacheRelation1() {
+    EntityCache cache = getNormalCache();
+
+    UserEntity testUserEntity = TestUtil.getTestUserEntity();
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(testGroupEntity);
+    cache.put(testUserEntity);
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_USER_REL,
+        ImmutableList.of(testUserEntity));
+
+    cache.invalidate(testRoleEntity.nameIdentifier(), Entity.EntityType.ROLE);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[2] <br>
+   * CACHE1 = Role1 -> [catalog1, catalog2] <br>
+   * CACHE2 = catalog1 -> [tab1, tab2] <br>
+   * ACTIVE: INVALIDATE catalog1, then need to remove RECORD1 and RECORD2
+   */
+  void testRemoveCacheRelation2() {
+    EntityCache cache = getNormalCache();
+
+    GroupEntity testGroupEntity = TestUtil.getTestGroupEntity();
+    RoleEntity testRoleEntity = TestUtil.getTestRoleEntity();
+
+    cache.put(testGroupEntity);
+
+    cache.put(
+        testRoleEntity.nameIdentifier(),
+        Entity.EntityType.ROLE,
+        SupportsRelationOperations.Type.ROLE_GROUP_REL,
+        ImmutableList.of(testGroupEntity));
+
+    cache.invalidate(testGroupEntity.nameIdentifier(), Entity.EntityType.GROUP);
+
+    Assertions.assertEquals(0, cache.size());
+  }
+
+  @Test
+  /**
+   * SCENE[3]<br>
+   * CACHE1 = Metadata1 -> []<br>
+   * CACHE2 = Metadata1.Catalog1.tab1 -> []<br>
+   * ACTIVE: INVALIDATE Metadata1, then need to remove RECORD1 and RECORD2<br>
+   */
+  void testRemoveCacheRelation3() {
+    EntityCache cache = getNormalCache();
+
+    BaseMetalake testMetalake = TestUtil.getTestMetalake();
+    TableEntity testTableEntity = TestUtil.getTestTableEntity();
+
+    cache.put(testMetalake);
+    cache.put(testTableEntity);
+
+    cache.invalidate(testMetalake.nameIdentifier(), Entity.EntityType.CATALOG);

Review Comment:
   fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,
               userEntity -> {
                 List<RoleEntity> roleEntities = Lists.newArrayList();

Review Comment:
   We can move logic to here.
   ```  
    roles.forEach(
           roleName -> {
             Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
             NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
             cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
           });
   ```



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public void clean() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());

Review Comment:
   fixed



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public void clean() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public int size() {
+    return reverseIndex.size();
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeySerialNumber =
+        String.format("%s-%d", strEntityCacheKey, entityKeys.size());
+    reverseIndex.put(strEntityCacheKeySerialNumber, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent = ((HasIdentifier) entity).nameIdentifier();
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  public void registerReverseRule(Class<? extends Entity> entityClass, ReverseIndexRule rule) {
+    reverseIndexRules.put(entityClass, rule);
+  }
+
+  /** Processes an entity and updates the reverse index accordingly. */
+  public void indexEntity(Entity entity, EntityCacheRelationKey key) {
+    ReverseIndexRule rule = reverseIndexRules.get(entity.getClass());
+    if (rule != null) {
+      rule.indexEntity(entity, key, this);
+    }
+  }
+
+  /** Functional interface for processing reverse index rules. */
+  @FunctionalInterface
+  public interface ReverseIndexRule {

Review Comment:
   fixed



##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheRelationKey.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.cache;
+
+import java.util.Objects;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.SupportsRelationOperations;
+
+/** Key for Entity cache. */
+public class EntityCacheRelationKey extends EntityCacheKey {
+  private final SupportsRelationOperations.Type relationType;
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation, it can be null.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(
+      NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relationType) {
+    return new EntityCacheRelationKey(ident, type, relationType);
+  }
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(NameIdentifier ident, Entity.EntityType type) {
+    return new EntityCacheRelationKey(ident, type, null);
+  }
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given parameters.
+   *
+   * @param identifier The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation.
+   */
+  private EntityCacheRelationKey(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      SupportsRelationOperations.Type relationType) {
+    super(identifier, type);
+    this.relationType = relationType;
+  }
+
+  /**
+   * Returns the type of the relation.
+   *
+   * @return The type of the relation.
+   */
+  public SupportsRelationOperations.Type relationType() {
+    return relationType;
+  }
+
+  /**
+   * Compares two instances of {@link EntityCacheRelationKey} for equality. The comparison is done
+   * by comparing the identifier, type, and relationType of the instances.
+   *
+   * @param obj The object to compare to.
+   * @return {@code true} if the objects are equal, {@code false} otherwise.
+   */
+  @Override
+  public boolean equals(Object obj) {
+    if (obj == this) return true;
+    if (!(obj instanceof EntityCacheRelationKey)) return false;
+    EntityCacheRelationKey other = (EntityCacheRelationKey) obj;
+
+    return Objects.equals(super.identifier(), other.identifier())

Review Comment:
   fixed



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +86,16 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {
+                  EntityCache cache = (EntityCache) store;
+                  roles.forEach(
+                          roleName -> {
+                            Namespace namespaceRole = NamespaceUtil.ofRole(metalake);
+                            NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+                            cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+                          });

Review Comment:
   I revert this part code, we didn't need to modify here.
   https://github.com/apache/gravitino/pull/8297/commits/649e7efc380eefcc64c7f29db1c2f042c8c1400c



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,

Review Comment:
   I revert this part code, we didn't need to modify here.
   https://github.com/apache/gravitino/commit/649e7efc380eefcc64c7f29db1c2f042c8c1400c



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   I don't have further comments, @yuqi1129 @mchades @jerqi can you please also take a review? Hopes that this can be merged today.


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.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.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+  /** Registers a reverse index processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeys =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =

Review Comment:
   fixed.
   It's strEntityCacheKey Serial Number



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // first invalidate this entity
+    EntityCacheKey currentKey = cacheIndex.getValueForExactKey(identifier.toString());
+    if (currentKey != null) {
+      // already removed
+      cacheData.invalidate(currentKey);
+      cacheIndex.remove(currentKey.toString());
+    }
+
+    // Remove child entities
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = ((HasIdentifier) entity).nameIdentifier();
+                if (!child.equals(identifier)) {
+                  invalidateEntitiesOld(child);

Review Comment:
   Removed this test function.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // first invalidate this entity
+    EntityCacheKey currentKey = cacheIndex.getValueForExactKey(identifier.toString());
+    if (currentKey != null) {
+      // already removed
+      cacheData.invalidate(currentKey);
+      cacheIndex.remove(currentKey.toString());
+    }
+
+    // Remove child entities
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = ((HasIdentifier) entity).nameIdentifier();
+                if (!child.equals(identifier)) {
+                  invalidateEntitiesOld(child);
+                }
+              });
+        });

Review Comment:
   Removed this test function.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   I'm not sure the grammar is 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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -204,6 +204,11 @@ allprojects {
             "[-PtestMode=embedded] or [-PtestMode=deploy]."
         )
       }
+
+      // enable entity cache or not
+      val enableEntityCache = project.properties["enableEntityCache"] as? String ?: "false"
+      param.systemProperty("enableEntityCache", enableEntityCache)

Review Comment:
   I can remove it when I complete this PR.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/MetadataObjectRoleAuthorizationIT.java:
##########
@@ -82,8 +84,6 @@ public void testCatalogRole() {
         ImmutableList.of(
             SecurableObjects.ofCatalog(
                 CATALOG, ImmutableList.of(Privileges.CreateSchema.allow()))));
-    roleNames = catalogLoadByNormalUser.supportsRoles().listBindingRoleNames();
-    assertArrayEquals(new String[] {role1}, roleNames);

Review Comment:
   It seems that he forgot to restore the code 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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   I have no further comments.


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   I revert this commit https://github.com/apache/gravitino/pull/8297/commits/649e7efc380eefcc64c7f29db1c2f042c8c1400c



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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

   https://github.com/apache/gravitino/pull/8297#discussion_r2318329799
   > What do you mean by I'm not sure the grammar is ok? I can't get it.
   
   I revert this commit, https://github.com/apache/gravitino/pull/8297/commits/649e7efc380eefcc64c7f29db1c2f042c8c1400c


-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -564,9 +569,9 @@ subprojects {
       exclude("test/**")
     }
   }
-  tasks.named("compileJava").configure {
-    dependsOn("spotlessCheck")
-  }
+//  tasks.named("compileJava").configure {

Review Comment:
   Please remove it if it's unused.



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,66 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    EntityCacheKey valueForExactKey;
+    if (relTypeOpt.isEmpty()) {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(EntityCacheKey.of(identifier, type).toString());
+    } else {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(
+              EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+    }
+
+    if (valueForExactKey == null) {
+      // No key to remove
+      return false;
+    }
+
+    queue.offer(valueForExactKey);
+
+    while (!queue.isEmpty()) {
+      EntityCacheKey currentKeyToRemove = queue.poll();
+
+      cacheData.invalidate(currentKeyToRemove);
+      cacheIndex.remove(currentKeyToRemove.toString());
+
+      // Remove related entity keys
+      List<EntityCacheKey> relatedEntityKeysToRemove =
+          Lists.newArrayList(
+              cacheIndex.getValuesForKeysStartingWith(currentKeyToRemove.identifier().toString()));
+      relatedEntityKeysToRemove.forEach(queue::offer);

Review Comment:
   queue.addAll



##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -331,18 +346,66 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
   }
 
   /**
-   * Invalidates the entities by the given cache key.
+   * Invalidate entities with iterative BFS algorithm.
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
-    List<EntityCacheKey> entityKeysToRemove =
-        Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
+  private boolean invalidateEntities(
+      NameIdentifier identifier,
+      Entity.EntityType type,
+      Optional<SupportsRelationOperations.Type> relTypeOpt) {
+    Queue<EntityCacheKey> queue = new ArrayDeque<>();
 
-    cacheData.invalidateAll(entityKeysToRemove);
-    entityKeysToRemove.forEach(key -> cacheIndex.remove(key.toString()));
+    EntityCacheKey valueForExactKey;
+    if (relTypeOpt.isEmpty()) {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(EntityCacheKey.of(identifier, type).toString());
+    } else {
+      valueForExactKey =
+          cacheIndex.getValueForExactKey(
+              EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString());
+    }

Review Comment:
   ```
   String entityCacheKeyString = relTypeOpt.isEmpty() ? EntityCacheKey.of(identifier, type).toString() : EntityCacheRelationKey.of(identifier, type, relTypeOpt.get()).toString();
   
   valueForExactKey = cacheIndex.getValueForExactKey
   ```



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} -
+ * UserEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} - RoleEntity
+ * role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} - {serial-number}: Because
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;
+                      default:

Review Comment:
   cc @xunliu 



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   Did you fix the problem I mentioned in that issue also?



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -204,6 +204,11 @@ allprojects {
             "[-PtestMode=embedded] or [-PtestMode=deploy]."
         )
       }
+
+      // enable entity cache or not
+      val enableEntityCache = project.properties["enableEntityCache"] as? String ?: "false"
+      param.systemProperty("enableEntityCache", enableEntityCache)

Review Comment:
   It's better to remove it when you finish all the codes.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   Currently, Authz only has MATEDATA, CATALOG, and FILESET integration tests, so I only added these.
   BTW, we can use the ReverseIndexRule to extend the easy TABLE MODEL MODEL VERSION SCHEMA.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} -
+ * UserEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} - RoleEntity
+ * role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} - {serial-number}: Because
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class.getName());
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;
+                      default:

Review Comment:
   The currently supported types already cover all existing test cases, so I believe we should only add support for other types when the need arises.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/EntityCacheRelationKey.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.cache;
+
+import java.util.Objects;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.SupportsRelationOperations;
+
+/** Key for Entity cache. */
+public class EntityCacheRelationKey extends EntityCacheKey {
+  private final SupportsRelationOperations.Type relationType;
+
+  /**
+   * Creates a new instance of {@link EntityCacheRelationKey} with the given arguments.
+   *
+   * @param ident The identifier of the entity.
+   * @param type The type of the entity.
+   * @param relationType The type of the relation, it can be null.
+   * @return A new instance of {@link EntityCacheRelationKey}.
+   */
+  public static EntityCacheRelationKey of(
+      NameIdentifier ident, Entity.EntityType type, SupportsRelationOperations.Type relationType) {
+    return new EntityCacheRelationKey(ident, type, relationType);
+  }

Review Comment:
   Fixed here.
   https://github.com/apache/gravitino/pull/8297#discussion_r2313997092



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -339,6 +364,55 @@ private boolean invalidateEntities(NameIdentifier identifier) {
     List<EntityCacheKey> entityKeysToRemove =
         Lists.newArrayList(cacheIndex.getValuesForKeysStartingWith(identifier.toString()));
 
+    Map<EntityCacheRelationKey, List<Entity>> relationEnitiesMap =
+        cacheData.getAllPresent(entityKeysToRemove);
+
+    // SCENE[1]
+    // RECORD1 = Role1 -> [catalog1, catalog2]
+    // RECORD2 = catalog1 -> [tab1, tab2]
+    // INVALIDATE Role1, then need to remove RECORD1 and RECORD2
+    relationEnitiesMap.forEach(
+        (key, entities) -> {
+          if (key.relationType() == null) {
+            // If the relation type is null, it means it's a single entity, we can skip it.
+            return;
+          }
+          entities.forEach(
+              entity -> {
+                NameIdentifier child = getNameIdentifier(entity);
+                if (!child.equals(identifier)) {
+                  invalidateEntities(child);

Review Comment:
   Failed test: [RoleAuthorizationIT.deleteRole](https://github.com/apache/gravitino/actions/runs/17262756741/job/48987812078?pr=8297#step:9:3663)



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +86,15 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache relationalStore) {
+                  roles.forEach(
+                          roleName -> {
+                            Namespace namespaceRole = NamespaceUtil.ofRole(metalake);
+                            NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+                            relationalStore.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);

Review Comment:
   Maybe we need an interface to invalidate user and all the roles.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeysToRemove.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  /** Registers a processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();
+
+  public void registerReverseRule(Class<? extends Entity> entityClass, ReverseIndexRule rule) {
+    reverseIndexRules.put(entityClass, rule);
+  }
+
+  /** Processes an entity and updates the reverse index accordingly. */
+  public void indexEntity(Entity entity, EntityCacheRelationKey key) {
+    ReverseIndexRule rule = reverseIndexRules.get(entity.getClass());
+    if (rule != null) {
+      rule.indexEntity(entity, key, this);
+    }

Review Comment:
   Emmmm... Good point!
   Fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -78,11 +79,21 @@ public class CaffeineEntityCache extends BaseEntityCache {
   private static final Logger LOG = LoggerFactory.getLogger(CaffeineEntityCache.class.getName());
   private final ReentrantLock opLock = new ReentrantLock();
 
-  /** Cache part */
-  private final Cache<EntityCacheKey, List<Entity>> cacheData;
+  /** Cache data structure. cacheData[0] = Role1-KEY -> [catalog1, catalog2] */
+  private final Cache<EntityCacheRelationKey, List<Entity>> cacheData;
 
-  /** Index part */
-  private RadixTree<EntityCacheKey> cacheIndex;
+  /**
+   * Cache reverse index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] =
+   * catalog1 -> [tab1, tab2] reverseIndex[0] = catalog1-KEY -> Role1 reverseIndex[1] = catalog2-KEY
+   * -> Role1 reverseIndex[3] = tab1-KEY -> catalog1 reverseIndex[4] = tab2-KEY -> catalog1
+   */
+  private ReverseIndexCache reverseIndex;
+
+  /**
+   * Cache Index structure. cacheData[0] = Role1 -> [catalog1, catalog2] cacheData[1] = catalog1 ->
+   * [tab1, tab2] cacheIndex[0] = Role1-KEY -> Role1 cacheIndex[1] = Role1-KEY -> Role1

Review Comment:
   Remove invalid comments



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -80,6 +80,7 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               AuthorizationUtils.ofUser(metalake, user),
               UserEntity.class,
               Entity.EntityType.USER,
+              roles,

Review Comment:
   Because when we call `grant role to user`, the `user` and `roles` have changed,
   We need to notice the cache sync.
   Currently, we only have a `user` event, so we need to add `roles`.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =
+        Lists.newArrayList(reverseIndex.getValuesForKeysStartingWith(strEntityCacheKey));
+    String strEntityCacheKeyNo =
+        String.format("%s-%d", strEntityCacheKey, entityKeysToRemove.size());
+    reverseIndex.put(strEntityCacheKeyNo, key);
+  }
+
+  public void put(Entity entity, EntityCacheRelationKey key) {
+    Preconditions.checkArgument(entity != null, "EntityCacheRelationKey cannot be null");
+
+    if (entity instanceof HasIdentifier) {
+      NameIdentifier nameIdent =
+          NameIdentifier.of(((HasIdentifier) entity).namespace(), ((HasIdentifier) entity).name());
+      put(nameIdent, entity.type(), key);
+    }
+  }
+
+  /** Registers a processor for a specific entity class. */
+  private final Map<Class<? extends Entity>, ReverseIndexRule> reverseIndexRules = new HashMap<>();

Review Comment:
   Please move this line to the top of this class.



##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexCache.java:
##########
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
+import com.googlecode.concurrenttrees.radix.RadixTree;
+import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+
+/**
+ * Reverse index cache for managing entity relationships. This cache uses a radix tree to
+ * efficiently store and retrieve relationships between entities based on their keys.
+ */
+public class ReverseIndexCache {
+  private final RadixTree<EntityCacheKey> reverseIndex;
+
+  public ReverseIndexCache() {
+    this.reverseIndex = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory());
+
+    registerReverseRule(UserEntity.class, ReverseIndexRules.USER_REVERSE_RULE);
+    registerReverseRule(GroupEntity.class, ReverseIndexRules.GROUP_REVERSE_RULE);
+    registerReverseRule(RoleEntity.class, ReverseIndexRules.ROLE_REVERSE_RULE);
+  }
+
+  public boolean remove(EntityCacheKey key) {
+    return reverseIndex.remove(key.toString());
+  }
+
+  public Iterable<EntityCacheKey> getValuesForKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getValuesForKeysStartingWith(keyPrefix);
+  }
+
+  public Iterable<CharSequence> getKeysStartingWith(String keyPrefix) {
+    return reverseIndex.getKeysStartingWith(keyPrefix);
+  }
+
+  public boolean remove(String key) {
+    return reverseIndex.remove(key);
+  }
+
+  public void put(
+      NameIdentifier nameIdentifier, Entity.EntityType type, EntityCacheRelationKey key) {
+    EntityCacheKey entityCacheKey = EntityCacheKey.of(nameIdentifier, type);
+    String strEntityCacheKey = entityCacheKey.toString();
+    List<EntityCacheKey> entityKeysToRemove =

Review Comment:
   Can you explain why you named it `entityKeysToRemove` since I notice no drop operation 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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/PolicyIT.java:
##########
@@ -466,17 +466,16 @@ public void testAssociatePoliciesToCatalog() {
     Assertions.assertTrue(policies7[0].enabled());
 
     // Test disable the policy then list again
-    // todo: uncomment after the bug is fixed
-    // https://github.com/apache/gravitino/issues/7787#issue-3255540700
-    //    Assertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));
-    //    Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();
-    //    Assertions.assertEquals(1, policies8.length);
-    //    Assertions.assertEquals(policy1.name(), policies8[0].name());
-    //    Assertions.assertFalse(policies8[0].enabled());
+    Assertions.assertDoesNotThrow(() -> metalake.disablePolicy(policy1.name()));
+    Policy[] policies8 = relationalCatalog.supportsPolicies().listPolicyInfos();
+    Assertions.assertEquals(1, policies8.length);
+    Assertions.assertEquals(policy1.name(), policies8[0].name());
+    Assertions.assertFalse(policies8[0].enabled());
+    Assertions.assertDoesNotThrow(() -> metalake.enablePolicy(policy1.name()));
 
     // Test get associated policy for catalog
     Policy policy = relationalCatalog.supportsPolicies().getPolicy(policy1.name());
-    Assertions.assertEquals(policy1, policy);
+    Assertions.assertEquals(policy1.enabled(), policy.enabled());

Review Comment:
   It's okay



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/CaffeineEntityCache.java:
##########
@@ -335,16 +355,125 @@ private <KEY, VALUE> Caffeine<KEY, VALUE> newBaseBuilder(Config cacheConfig) {
    *
    * @param identifier The identifier of the entity to invalidate
    */
-  private boolean invalidateEntities(NameIdentifier identifier) {
+  private boolean invalidateEntitiesOld(NameIdentifier identifier) {

Review Comment:
   Removed this test function.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -204,6 +204,11 @@ allprojects {
             "[-PtestMode=embedded] or [-PtestMode=deploy]."
         )
       }
+
+      // enable entity cache or not
+      val enableEntityCache = project.properties["enableEntityCache"] as? String ?: "false"
+      param.systemProperty("enableEntityCache", enableEntityCache)

Review Comment:
   Let's make it easier to conduct comparative testing.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -117,6 +118,23 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
   }
 
   @Override
+  public <E extends Entity & HasIdentifier> E update(
+      NameIdentifier ident,
+      Class<E> type,
+      Entity.EntityType entityType,
+      List<String> roles,
+      Function<E, E> updater)
+      throws IOException, NoSuchEntityException, EntityAlreadyExistsException {
+    roles.forEach(
+        roleName -> {
+          Namespace namespaceRole = NamespaceUtil.ofRole(ident.namespace().level(0));
+          NameIdentifier nameIdentifierRole = NameIdentifier.of(namespaceRole, roleName);
+          cache.invalidate(nameIdentifierRole, Entity.EntityType.ROLE);
+        });
+
+    return update(ident, type, entityType, updater);
+  }
+

Review Comment:
   @xunliu 



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   Currently, Authz only has MATEDATA, CATALOG, and FILESET integration tests, so I only added these.
   BTW, we can use the ReverseIndexRule to extend TABLE MODEL MODEL VERSION SCHEMA.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/authorization/PermissionManager.java:
##########
@@ -81,6 +85,17 @@ User grantRolesToUser(String metalake, List<String> roles, String user) {
               UserEntity.class,
               Entity.EntityType.USER,
               userEntity -> {
+                if (store instanceof EntityCache) {

Review Comment:
   The store never will be the EntityCache in my understanding.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
build.gradle.kts:
##########
@@ -204,6 +204,11 @@ allprojects {
             "[-PtestMode=embedded] or [-PtestMode=deploy]."
         )
       }
+
+      // enable entity cache or not
+      val enableEntityCache = project.properties["enableEntityCache"] as? String ?: "false"
+      param.systemProperty("enableEntityCache", enableEntityCache)

Review Comment:
   Revert this commit.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java:
##########
@@ -116,7 +116,6 @@ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
     cache.put(e);
   }
 
-  @Override

Review Comment:
   Oh, this mistake, fixed.



-- 
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] [#7804] fix(cache): Fix metadata cache data consistency error [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/cache/ReverseIndexRules.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.cache;
+
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reverse index rules for different entity types. This class defines how to process reverse
+ * indexing for UserEntity, GroupEntity, and RoleEntity. <br>
+ * For example: <br>
+ * - UserEntity role is {metalake-name}.system.user.{user-name}:USER-{serial-number} <br>
+ * - GroupEntity role is {metalake-name}.system.group.{group-name}:GROUP-{serial-number} <br>
+ * - RoleEntity role is {metalake-name}.system.role.{role-name}:ROLE-{serial-number} <br>
+ */
+public class ReverseIndexRules {
+  private static final Logger LOG = LoggerFactory.getLogger(ReverseIndexRules.class);
+
+  /** UserEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule USER_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        UserEntity userEntity = (UserEntity) entity;
+        if (userEntity.roleNames() != null) {
+          userEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(userEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** GroupEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule GROUP_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        GroupEntity groupEntity = (GroupEntity) entity;
+        if (groupEntity.roleNames() != null) {
+          groupEntity
+              .roleNames()
+              .forEach(
+                  role -> {
+                    Namespace ns = NamespaceUtil.ofRole(groupEntity.namespace().level(0));
+                    NameIdentifier nameIdentifier = NameIdentifier.of(ns, role);
+                    reverseIndexCache.put(nameIdentifier, Entity.EntityType.ROLE, key);
+                  });
+        }
+      };
+
+  /** * RoleEntity reverse index processor */
+  public static final ReverseIndexCache.ReverseIndexRule ROLE_REVERSE_RULE =
+      (entity, key, reverseIndexCache) -> {
+        RoleEntity roleEntity = (RoleEntity) entity;
+        if (roleEntity.securableObjects() != null) {
+          roleEntity
+              .securableObjects()
+              .forEach(
+                  securableObject -> {
+                    Namespace namespace = Namespace.empty();
+                    Entity.EntityType entityType = Entity.EntityType.METALAKE;
+                    switch (securableObject.type()) {
+                      case METALAKE:
+                        entityType = Entity.EntityType.METALAKE;
+                        namespace = NamespaceUtil.ofMetalake();
+                        break;
+                      case CATALOG:
+                        entityType = Entity.EntityType.CATALOG;
+                        namespace = NamespaceUtil.ofCatalog(roleEntity.namespace().level(0));
+                        break;
+                      case FILESET:
+                        entityType = Entity.EntityType.FILESET;
+                        Namespace nsParent = Namespace.fromString(securableObject.parent());
+                        namespace =
+                            NamespaceUtil.ofFileset(
+                                roleEntity.namespace().level(0),
+                                nsParent.level(0),
+                                nsParent.level(1));
+                        break;

Review Comment:
   @jerqi @yuqi1129 
   Support all types in https://github.com/apache/gravitino/pull/8297/commits/e1eb0fa37831cc129898f6e99fc55e6bfefc5f91



-- 
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