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

[PR] [#12176] feat(core): resolve policies from tag associations [gravitino]

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

   ### What changes were proposed in this pull request?
   
   Implement the core runtime for policy-on-tag:
   
   1. Resolve effective tags with child assignments overriding inherited assignments.
   2. Deserialize persisted policy association selectors, including legacy relations without selector JSON.
   3. Resolve, filter, and deduplicate enabled policies from effective tags.
   4. Add policy-to-tag operations to the policy and tag managers.
   5. Add focused resolver, selector, and manager tests.
   
   REST APIs, clients, authorization, listener events, and documentation are intentionally excluded from this PR.
   
   ### Why are the changes needed?
   
   The policy-on-tag API and relational storage have already been merged. This PR adds the runtime behavior required to resolve object policies from effective tag assignments.
   
   Part of #12176.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. Object policy lookup now derives enabled policies from effective tags and matching policy association selectors.
   
   ### How was this patch tested?
   
   - `./gradlew :core:spotlessApply :core:compileJava :core:compileTestJava`
   - `./gradlew :core:test --tests org.apache.gravitino.policy.TestPolicyAssociationSelectorSerde --tests org.apache.gravitino.policy.TestObjectPolicyResolver --tests org.apache.gravitino.tag.TestEffectiveTagResolver --tests org.apache.gravitino.tag.TestTagManager -PskipDockerTests=false`
   - `git diff --check`


-- 
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] [#12176] feat(core): add policy-on-tag core support [gravitino]

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

   > Please update the PR title and description before merging, as they no longer match the current implementation.
   
   Updated.


-- 
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] [#12176] feat(core): resolve policies from tag associations [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);
           } catch (IOException e) {
-            LOG.error("Failed to list policies for metadata object {}", metadataObject, e);
+            LOG.error(
+                "Failed to list tag associations for policy {} under metalake {}",
+                policyName,
+                metalake,
+                e);
             throw new RuntimeException(e);
           }
         });
   }
 
+  @Override
+  public PolicyEntity[] listPolicyInfosForMetadataObject(
+      String metalake, MetadataObject metadataObject) {
+    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
+    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
+    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+
+    Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();
+    Arrays.stream(listDirectPoliciesForMetadataObject(entityIdent, entityType, metadataObject))
+        .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));
+    Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))

Review Comment:
   Fixed in 9123233bc. The ObjectPolicyResolver integration is deferred to the follow-up REST PR. PolicyManager now returns direct policies only, preserving the existing REST parent traversal and avoiding duplicate effective-tag resolution and incorrect inherited flags. The resolver and its unit coverage remain in 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] [#12176] feat(core): add policy-on-tag core support [gravitino]

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


-- 
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] [#12176] feat(core): resolve policies from tag associations [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);
           } catch (IOException e) {
-            LOG.error("Failed to list policies for metadata object {}", metadataObject, e);
+            LOG.error(
+                "Failed to list tag associations for policy {} under metalake {}",
+                policyName,
+                metalake,
+                e);
             throw new RuntimeException(e);
           }
         });
   }
 
+  @Override
+  public PolicyEntity[] listPolicyInfosForMetadataObject(
+      String metalake, MetadataObject metadataObject) {
+    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
+    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
+    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+
+    Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();
+    Arrays.stream(listDirectPoliciesForMetadataObject(entityIdent, entityType, metadataObject))
+        .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));
+    Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))

Review Comment:
   This PR already changes the existing user-facing list/get behavior by invoking `ObjectPolicyResolver` from `PolicyManager`. Those requests currently flow through `MetadataObjectPolicyOperations`, so merging this PR before the follow-up exposes the duplicate parent traversal immediately. Please either update the REST traversal and add override/inherited regression coverage here, or defer the `PolicyManager` resolver integration to the follow-up 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] [#12176] feat(core): resolve policies from tag associations [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -117,6 +119,56 @@ default Tag createTag(
    */
   MetadataObject[] listMetadataObjectsForTag(String metalake, String name);
 
+  /**
+   * List policy names directly associated with the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The directly associated policy names.
+   */
+  default String[] listPoliciesForTag(String metalake, String name) {
+    return Arrays.stream(listPolicyAssociationsForTag(metalake, name))
+        .map(association -> association.targetEntity().name())
+        .toArray(String[]::new);
+  }

Review Comment:
   Thanks. This duplicates the other import comment. java.util.Arrays is already imported in the current head, so no change is needed here.



##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -117,6 +119,56 @@ default Tag createTag(
    */
   MetadataObject[] listMetadataObjectsForTag(String metalake, String name);
 
+  /**
+   * List policy names directly associated with the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The directly associated policy names.
+   */
+  default String[] listPoliciesForTag(String metalake, String name) {
+    return Arrays.stream(listPolicyAssociationsForTag(metalake, name))
+        .map(association -> association.targetEntity().name())
+        .toArray(String[]::new);
+  }
+
+  /**
+   * List policy associations, including selectors, for the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The policy-to-tag associations.
+   */
+  default RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {

Review Comment:
   Thanks. The REST entry points and the corresponding Tag/Policy Event and Hook dispatcher delegation will be added together in the follow-up REST integration PR. This core runtime PR intentionally does not expose these operations through the composed production chain yet.



##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -22,8 +22,10 @@
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.RelationalEntity;
 import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.policy.PolicyAssociationSelector;

Review Comment:
   Thanks. java.util.Arrays is already imported at line 21 in the current head, and the build passes, so no change is needed here.



##########
core/src/main/java/org/apache/gravitino/tag/TagManager.java:
##########
@@ -227,6 +231,109 @@ public MetadataObject[] listMetadataObjectsForTag(String metalake, String name)
     return listMetadataObjectsForTag(metalake, name, null);
   }
 
+  @Override
+  public RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, name);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    return TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.READ,
+        () -> {
+          try {
+            return entityStore
+                .relationOperations()
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(tagIdentifier),
+                    Entity.EntityType.TAG)
+                .toArray(new RelationalEntity<?>[0]);
+          } catch (IOException e) {
+            LOG.error(
+                "Failed to list policy associations for tag {} under metalake {}",
+                name,
+                metalake,
+                e);
+            throw new RuntimeException(e);
+          }
+        });
+  }
+
+  @Override
+  public void addPolicyForTag(
+      String metalake, String tagName, String policyName, PolicyAssociationSelector selector) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, tagName);
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.WRITE,
+        () -> {
+          RelationUpdate update =
+              RelationUpdate.of(
+                  SupportsRelationOperations.Type.POLICY_TAG_REL,
+                  tagIdentifier,
+                  Entity.EntityType.TAG,
+                  new RelationEdgeTarget[] {
+                    RelationEdgeTarget.of(
+                        policyIdentifier,
+                        Entity.EntityType.POLICY,
+                        PolicyAssociationSelectorSerde.serialize(selector))

Review Comment:
   Thanks. Policy-tag association create, update, and delete operations enter through REST, so selector validation against TagValueConstraint will be implemented in the follow-up REST PR. TagValueConstraint is immutable after tag creation, and this keeps semantic request validation in the REST layer instead of duplicating it in core.



##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);
           } catch (IOException e) {
-            LOG.error("Failed to list policies for metadata object {}", metadataObject, e);
+            LOG.error(
+                "Failed to list tag associations for policy {} under metalake {}",
+                policyName,
+                metalake,
+                e);
             throw new RuntimeException(e);
           }
         });
   }
 
+  @Override
+  public PolicyEntity[] listPolicyInfosForMetadataObject(
+      String metalake, MetadataObject metadataObject) {
+    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
+    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
+    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+
+    Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();
+    Arrays.stream(listDirectPoliciesForMetadataObject(entityIdent, entityType, metadataObject))
+        .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));
+    Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))

Review Comment:
   Thanks. We agree this must be addressed together with the planned object-policy semantic change in the follow-up REST PR. That change will separate direct-policy compatibility traversal from effective tag-derived resolution and define inherited flags there. We are intentionally not changing the existing REST traversal in this core runtime PR.



##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);

Review Comment:
   Thanks. batchListEntitiesByRelation supports either endpoint for POLICY_TAG_REL. With a POLICY anchor, PolicyTagRelService.listRelations calls listByPolicyNames and then tagTargets, so the returned target entities are tags. The current implementation is correct and no change is needed here.



##########
core/src/main/java/org/apache/gravitino/tag/TagManager.java:
##########
@@ -227,6 +231,109 @@ public MetadataObject[] listMetadataObjectsForTag(String metalake, String name)
     return listMetadataObjectsForTag(metalake, name, null);
   }
 
+  @Override
+  public RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, name);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    return TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.READ,
+        () -> {
+          try {
+            return entityStore
+                .relationOperations()
+                .batchListEntitiesByRelation(

Review Comment:
   Fixed in e533d2de3. listPolicyAssociationsForTag now loads the anchor tag under the read lock before querying relations, and the regression test verifies that a missing tag raises NoSuchTagException.



##########
common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.json;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import java.io.IOException;
+import org.apache.gravitino.policy.AllValuesSelector;
+import org.apache.gravitino.policy.PolicyAssociationSelector;
+import org.apache.gravitino.policy.TagValueSelector;
+
+/** JSON serializer and deserializer for policy-to-tag selectors. */
+public final class PolicyAssociationSelectorSerde {
+
+  private static final String TYPE = "type";
+  private static final String VALUE = "value";
+
+  private static final ObjectMapper MAPPER =
+      JsonUtils.anyFieldMapper()
+          .copy()
+          .registerModule(
+              new SimpleModule()
+                  .addSerializer(PolicyAssociationSelector.class, new Serializer())
+                  .addDeserializer(PolicyAssociationSelector.class, new Deserializer()));
+
+  private PolicyAssociationSelectorSerde() {}
+
+  /**
+   * Serializes a selector.
+   *
+   * @param selector The selector to serialize.
+   * @return The selector JSON.
+   */
+  public static String serialize(PolicyAssociationSelector selector) {
+    try {
+      return MAPPER.writerFor(PolicyAssociationSelector.class).writeValueAsString(selector);
+    } catch (JsonProcessingException e) {
+      throw new IllegalArgumentException("Failed to serialize policy association selector", e);
+    }
+  }
+
+  /**
+   * Deserializes a selector.
+   *
+   * @param json The selector JSON.
+   * @return The selector.
+   */
+  public static PolicyAssociationSelector deserialize(String json) {
+    try {
+      return MAPPER.readValue(json, PolicyAssociationSelector.class);
+    } catch (JsonProcessingException e) {
+      throw new IllegalArgumentException("Failed to deserialize policy association selector", e);
+    }
+  }
+
+  /** Serializes a policy association selector. */
+  public static final class Serializer extends JsonSerializer<PolicyAssociationSelector> {
+
+    @Override
+    public void serialize(
+        PolicyAssociationSelector selector,
+        JsonGenerator generator,
+        SerializerProvider serializerProvider)
+        throws IOException {
+      if (!(selector instanceof AllValuesSelector) && !(selector instanceof TagValueSelector)) {
+        throw JsonMappingException.from(
+            generator, "Unsupported policy association selector: " + selector);
+      }
+
+      generator.writeStartObject();
+      generator.writeStringField(TYPE, selector.type());
+      if (selector instanceof TagValueSelector) {
+        generator.writeStringField(VALUE, ((TagValueSelector) selector).value());
+      }
+      generator.writeEndObject();
+    }
+  }
+
+  /** Deserializes a policy association selector. */
+  public static final class Deserializer extends JsonDeserializer<PolicyAssociationSelector> {
+
+    @Override
+    public PolicyAssociationSelector deserialize(
+        JsonParser parser, DeserializationContext deserializationContext) throws IOException {
+      JsonNode node = parser.getCodec().readTree(parser);
+      String type = node.get(TYPE).asText();
+      if (AllValuesSelector.TYPE.equals(type)) {
+        return AllValuesSelector.get();
+      }
+      if (TagValueSelector.TYPE.equals(type)) {
+        return TagValueSelector.of(node.get(VALUE).asText());
+      }
+      throw JsonMappingException.from(
+          parser, "Unsupported policy association selector type: " + type);
+    }

Review Comment:
   Fixed in e533d2de3. The deserializer now validates the required textual type and value fields and reports a clear JsonMappingException through the public deserialize helper. Tests cover missing and null fields.



##########
core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.policy;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationalEntity;
+import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.tag.EffectiveTagResolver;
+import org.apache.gravitino.tag.TagAssignment;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Resolves policies for a metadata object from its effective tag assignments.
+ *
+ * <p>The resolver evaluates relation selectors, rejects mixed match results for the same policy,
+ * filters disabled policies, and deduplicates repeated matches by policy entity ID.
+ */
+public class ObjectPolicyResolver {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ObjectPolicyResolver.class);
+
+  private final EntityStore entityStore;
+  private final EffectiveTagResolver effectiveTagResolver;
+
+  /**
+   * Creates an object policy resolver.
+   *
+   * @param entityStore The entity store used to read policy-to-tag relations.
+   */
+  public ObjectPolicyResolver(EntityStore entityStore) {
+    this(entityStore, new EffectiveTagResolver(entityStore));
+  }
+
+  ObjectPolicyResolver(EntityStore entityStore, EffectiveTagResolver effectiveTagResolver) {
+    this.entityStore = entityStore;
+    this.effectiveTagResolver = effectiveTagResolver;
+  }
+
+  /**
+   * Resolves enabled policies for a metadata object.
+   *
+   * @param metalake The metalake name.
+   * @param metadataObject The metadata object.
+   * @return Enabled policies selected by the object's effective tags.
+   */
+  public PolicyEntity[] resolve(String metalake, MetadataObject metadataObject) {
+    TagEntity[] effectiveTags = effectiveTagResolver.resolve(metalake, metadataObject);
+    if (effectiveTags.length == 0) {
+      return new PolicyEntity[0];
+    }
+
+    Map<String, TagEntity> tagsByName =
+        Arrays.stream(effectiveTags)
+            .collect(
+                Collectors.toMap(
+                    TagEntity::name, tag -> tag, (left, right) -> left, LinkedHashMap::new));
+    List<NameIdentifier> tagIdentifiers =
+        tagsByName.keySet().stream()
+            .map(tagName -> NameIdentifierUtil.ofTag(metalake, tagName))
+            .collect(Collectors.toList());
+
+    List<RelationalEntity<?>> relations;
+    try {
+      relations =
+          entityStore
+              .relationOperations()
+              .batchListEntitiesByRelation(
+                  SupportsRelationOperations.Type.POLICY_TAG_REL,
+                  tagIdentifiers,
+                  Entity.EntityType.TAG);
+    } catch (IOException e) {
+      LOG.error("Failed to resolve policies for metadata object {}", metadataObject, e);
+      throw new RuntimeException(e);
+    }
+
+    Map<Long, MatchState> matchStates = new LinkedHashMap<>();
+    for (RelationalEntity<?> relation : relations) {
+      TagEntity tag = tagsByName.get(relation.source().name());
+      if (tag == null) {
+        continue;
+      }
+      PolicyEntity policy = (PolicyEntity) relation.targetEntity();
+      PolicyAssociationSelector selector =
+          PolicyAssociationSelectorSerde.deserialize(relation.relationValue().orElseThrow());
+      TagAssignment assignment = tag.assignment().orElseGet(TagAssignment::noValue);
+      boolean matches = matches(selector, assignment);

Review Comment:
   Fixed in e533d2de3. A missing relation payload is now treated as AllValuesSelector, preserving the tag-presence compatibility behavior, and a regression test was added.



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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

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


Re: [PR] [#12176] feat(core): resolve policies from tag associations [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -22,8 +22,10 @@
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.RelationalEntity;
 import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.policy.PolicyAssociationSelector;

Review Comment:
   `listPoliciesForTag` uses `Arrays.stream(...)` but `java.util.Arrays` is not imported in this file, which should fail compilation. Add the missing import (or avoid `Arrays.stream` by iterating directly).



##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -117,6 +119,56 @@ default Tag createTag(
    */
   MetadataObject[] listMetadataObjectsForTag(String metalake, String name);
 
+  /**
+   * List policy names directly associated with the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The directly associated policy names.
+   */
+  default String[] listPoliciesForTag(String metalake, String name) {
+    return Arrays.stream(listPolicyAssociationsForTag(metalake, name))
+        .map(association -> association.targetEntity().name())
+        .toArray(String[]::new);
+  }

Review Comment:
   `listPoliciesForTag` uses `Arrays.stream(...)` but `java.util.Arrays` is not imported in this file, which should fail compilation. Add the missing import (or avoid `Arrays.stream` by iterating directly).



##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);

Review Comment:
   The POLICY_TAG relation is created as (source=TAG, target=POLICY) in `TagManager.addPolicyForTag`, but this method queries it as if (source=POLICY). That likely returns no results (or incorrect ones), so `listTagsForPolicy` / `listTagAssociationsForPolicy` will be broken. A concrete fix is to query POLICY_TAG relations by *target policy* (e.g., via a relation query API that filters by target), or store a reverse edge (POLICY→TAG) at association time; then ensure the returned associations actually contain tags (not policies) for callers.



##########
core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.policy;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.RelationalEntity;
+import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.tag.EffectiveTagResolver;
+import org.apache.gravitino.tag.TagAssignment;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Resolves policies for a metadata object from its effective tag assignments.
+ *
+ * <p>The resolver evaluates relation selectors, rejects mixed match results for the same policy,
+ * filters disabled policies, and deduplicates repeated matches by policy entity ID.
+ */
+public class ObjectPolicyResolver {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ObjectPolicyResolver.class);
+
+  private final EntityStore entityStore;
+  private final EffectiveTagResolver effectiveTagResolver;
+
+  /**
+   * Creates an object policy resolver.
+   *
+   * @param entityStore The entity store used to read policy-to-tag relations.
+   */
+  public ObjectPolicyResolver(EntityStore entityStore) {
+    this(entityStore, new EffectiveTagResolver(entityStore));
+  }
+
+  ObjectPolicyResolver(EntityStore entityStore, EffectiveTagResolver effectiveTagResolver) {
+    this.entityStore = entityStore;
+    this.effectiveTagResolver = effectiveTagResolver;
+  }
+
+  /**
+   * Resolves enabled policies for a metadata object.
+   *
+   * @param metalake The metalake name.
+   * @param metadataObject The metadata object.
+   * @return Enabled policies selected by the object's effective tags.
+   */
+  public PolicyEntity[] resolve(String metalake, MetadataObject metadataObject) {
+    TagEntity[] effectiveTags = effectiveTagResolver.resolve(metalake, metadataObject);
+    if (effectiveTags.length == 0) {
+      return new PolicyEntity[0];
+    }
+
+    Map<String, TagEntity> tagsByName =
+        Arrays.stream(effectiveTags)
+            .collect(
+                Collectors.toMap(
+                    TagEntity::name, tag -> tag, (left, right) -> left, LinkedHashMap::new));
+    List<NameIdentifier> tagIdentifiers =
+        tagsByName.keySet().stream()
+            .map(tagName -> NameIdentifierUtil.ofTag(metalake, tagName))
+            .collect(Collectors.toList());
+
+    List<RelationalEntity<?>> relations;
+    try {
+      relations =
+          entityStore
+              .relationOperations()
+              .batchListEntitiesByRelation(
+                  SupportsRelationOperations.Type.POLICY_TAG_REL,
+                  tagIdentifiers,
+                  Entity.EntityType.TAG);
+    } catch (IOException e) {
+      LOG.error("Failed to resolve policies for metadata object {}", metadataObject, e);
+      throw new RuntimeException(e);
+    }
+
+    Map<Long, MatchState> matchStates = new LinkedHashMap<>();
+    for (RelationalEntity<?> relation : relations) {
+      TagEntity tag = tagsByName.get(relation.source().name());
+      if (tag == null) {
+        continue;
+      }
+      PolicyEntity policy = (PolicyEntity) relation.targetEntity();
+      PolicyAssociationSelector selector =
+          PolicyAssociationSelectorSerde.deserialize(relation.relationValue().orElseThrow());
+      TagAssignment assignment = tag.assignment().orElseGet(TagAssignment::noValue);
+      boolean matches = matches(selector, assignment);

Review Comment:
   `relation.relationValue().orElseThrow()` will throw if a POLICY_TAG relation exists without a selector payload (e.g., older persisted associations or partially-migrated data). To keep policy-on-tag usable during transition, treat a missing relation value as a safe default (typically `AllValuesSelector.get()`), or fail with a domain-specific error that clearly indicates the association is invalid and needs migration.



##########
common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.json;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import java.io.IOException;
+import org.apache.gravitino.policy.AllValuesSelector;
+import org.apache.gravitino.policy.PolicyAssociationSelector;
+import org.apache.gravitino.policy.TagValueSelector;
+
+/** JSON serializer and deserializer for policy-to-tag selectors. */
+public final class PolicyAssociationSelectorSerde {
+
+  private static final String TYPE = "type";
+  private static final String VALUE = "value";
+
+  private static final ObjectMapper MAPPER =
+      JsonUtils.anyFieldMapper()
+          .copy()
+          .registerModule(
+              new SimpleModule()
+                  .addSerializer(PolicyAssociationSelector.class, new Serializer())
+                  .addDeserializer(PolicyAssociationSelector.class, new Deserializer()));
+
+  private PolicyAssociationSelectorSerde() {}
+
+  /**
+   * Serializes a selector.
+   *
+   * @param selector The selector to serialize.
+   * @return The selector JSON.
+   */
+  public static String serialize(PolicyAssociationSelector selector) {
+    try {
+      return MAPPER.writerFor(PolicyAssociationSelector.class).writeValueAsString(selector);
+    } catch (JsonProcessingException e) {
+      throw new IllegalArgumentException("Failed to serialize policy association selector", e);
+    }
+  }
+
+  /**
+   * Deserializes a selector.
+   *
+   * @param json The selector JSON.
+   * @return The selector.
+   */
+  public static PolicyAssociationSelector deserialize(String json) {
+    try {
+      return MAPPER.readValue(json, PolicyAssociationSelector.class);
+    } catch (JsonProcessingException e) {
+      throw new IllegalArgumentException("Failed to deserialize policy association selector", e);
+    }
+  }
+
+  /** Serializes a policy association selector. */
+  public static final class Serializer extends JsonSerializer<PolicyAssociationSelector> {
+
+    @Override
+    public void serialize(
+        PolicyAssociationSelector selector,
+        JsonGenerator generator,
+        SerializerProvider serializerProvider)
+        throws IOException {
+      if (!(selector instanceof AllValuesSelector) && !(selector instanceof TagValueSelector)) {
+        throw JsonMappingException.from(
+            generator, "Unsupported policy association selector: " + selector);
+      }
+
+      generator.writeStartObject();
+      generator.writeStringField(TYPE, selector.type());
+      if (selector instanceof TagValueSelector) {
+        generator.writeStringField(VALUE, ((TagValueSelector) selector).value());
+      }
+      generator.writeEndObject();
+    }
+  }
+
+  /** Deserializes a policy association selector. */
+  public static final class Deserializer extends JsonDeserializer<PolicyAssociationSelector> {
+
+    @Override
+    public PolicyAssociationSelector deserialize(
+        JsonParser parser, DeserializationContext deserializationContext) throws IOException {
+      JsonNode node = parser.getCodec().readTree(parser);
+      String type = node.get(TYPE).asText();
+      if (AllValuesSelector.TYPE.equals(type)) {
+        return AllValuesSelector.get();
+      }
+      if (TagValueSelector.TYPE.equals(type)) {
+        return TagValueSelector.of(node.get(VALUE).asText());
+      }
+      throw JsonMappingException.from(
+          parser, "Unsupported policy association selector type: " + type);
+    }

Review Comment:
   This deserializer will NPE if `type` is missing/null (or if `value` is missing for TAG_VALUE). Please validate required fields and throw a `JsonMappingException` with a clear message (e.g., missing `type`, missing `value` for TAG_VALUE) instead of relying on `node.get(...).asText()`.



-- 
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] [#12176] feat(core): resolve policies from tag associations [gravitino]

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

   <!-- coverage-report -->
   ### Code Coverage Report
   |Overall Project|68.6% **`+0.16%`**|:green_circle:|
   |:-|:-|:-:|
   |Files changed|74.0%|:green_circle:|
   <br>
   
   |Module|Coverage||
   |:-|:-|:-:|
   |aliyun|19.74%|:red_circle:|
   |api|51.74%|:green_circle:|
   |authorization-common|85.96%|:green_circle:|
   |authorization-ranger|4.38%|:red_circle:|
   |aws|53.54%|:green_circle:|
   |azure|32.1%|:red_circle:|
   |catalog-common|19.1%|:red_circle:|
   |catalog-fileset|80.3%|:green_circle:|
   |catalog-glue|69.24%|:green_circle:|
   |catalog-hive|82.96%|:green_circle:|
   |catalog-jdbc-common|45.69%|:green_circle:|
   |catalog-jdbc-doris|82.44%|:green_circle:|
   |catalog-jdbc-mysql|79.33%|:green_circle:|
   |catalog-jdbc-postgresql|83.39%|:green_circle:|
   |catalog-jdbc-starrocks|79.16%|:green_circle:|
   |catalog-kafka|76.99%|:green_circle:|
   |catalog-lakehouse-generic|60.55%|:green_circle:|
   |catalog-lakehouse-hudi|79.1%|:green_circle:|
   |catalog-lakehouse-iceberg|85.86%|:green_circle:|
   |catalog-lakehouse-paimon|84.26%|:green_circle:|
   |catalog-model|77.99%|:green_circle:|
   |cli|44.48%|:green_circle:|
   |client-java|77.44%|:green_circle:|
   |common|55.68% **`+0.17%`**|:green_circle:|
   |core|83.57% **`+0.15%`**|:green_circle:|
   |filesystem-hadoop3|76.45%|:green_circle:|
   |flink|0.0%|:red_circle:|
   |flink-common|50.29% **`-9.3%`**|:green_circle:|
   |flink-runtime|0.0%|:red_circle:|
   |gcp|32.2%|:red_circle:|
   |hadoop-auth|68.0%|:green_circle:|
   |hadoop-common|17.84%|:red_circle:|
   |hive-metastore-common|53.4%|:green_circle:|
   |iceberg-aliyun-bundle|0.0%|:red_circle:|
   |iceberg-common|64.75%|:green_circle:|
   |iceberg-rest-server|75.89%|:green_circle:|
   |idp-basic|85.98%|:green_circle:|
   |integration-test-common|0.0%|:red_circle:|
   |jobs|62.92%|:green_circle:|
   |lance-common|32.63%|:red_circle:|
   |lance-rest-server|65.46%|:green_circle:|
   |lineage|53.02%|:green_circle:|
   |optimizer|83.24%|:green_circle:|
   |optimizer-api|21.95%|:red_circle:|
   |server|88.11%|:green_circle:|
   |server-common|80.5%|:green_circle:|
   |spark|28.57%|:red_circle:|
   |spark-common|48.92%|:green_circle:|
   |tencent|81.78%|:green_circle:|
   |trino-connector|47.44%|:green_circle:|
   
   <details>
   <summary>Files</summary>
   
   |Module|File|Coverage||
   |:-|:-|:-|:-:|
   |common|[PolicyAssociationSelectorSerde.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/common/src/main/java/org/apache/gravitino/json/PolicyAssociationSelectorSerde.java)|100.0%|:green_circle:|
   |core|[ModelVersionAliasRelBaseSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionAliasRelBaseSQLProvider.java)|100.0%|:green_circle:|
   ||[ModelVersionMetaBaseSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelVersionMetaBaseSQLProvider.java)|100.0%|:green_circle:|
   ||[ModelVersionAliasRelH2SQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionAliasRelH2SQLProvider.java)|100.0%|:green_circle:|
   ||[ModelVersionMetaH2Provider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/h2/ModelVersionMetaH2Provider.java)|100.0%|:green_circle:|
   ||[ModelMetaPostgreSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java)|100.0%|:green_circle:|
   ||[ModelVersionAliasRelPostgreSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java)|100.0%|:green_circle:|
   ||[ModelVersionMetaPostgreSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java)|100.0%|:green_circle:|
   ||[ModelPO.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/po/ModelPO.java)|97.83%|:green_circle:|
   ||[ModelVersionMetaSQLProviderFactory.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaSQLProviderFactory.java)|95.65%|:green_circle:|
   ||[ModelVersionAliasSQLProviderFactory.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasSQLProviderFactory.java)|95.45%|:green_circle:|
   ||[ModelVersionMetaService.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelVersionMetaService.java)|93.64%|:green_circle:|
   ||[ObjectPolicyResolver.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/policy/ObjectPolicyResolver.java)|90.77%|:green_circle:|
   ||[POConverters.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java)|88.32%|:green_circle:|
   ||[EffectiveTagResolver.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/tag/EffectiveTagResolver.java)|87.5%|:green_circle:|
   ||[TagManager.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/tag/TagManager.java)|85.47%|:green_circle:|
   ||[ModelMetaSQLProviderFactory.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaSQLProviderFactory.java)|83.33%|:green_circle:|
   ||[ModelMetaService.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java)|76.72%|:green_circle:|
   ||[ModelMetaBaseSQLProvider.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ModelMetaBaseSQLProvider.java)|75.0%|:green_circle:|
   ||[PolicyManager.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/policy/PolicyManager.java)|74.21%|:green_circle:|
   ||[PolicyDispatcher.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/policy/PolicyDispatcher.java)|42.86%|:red_circle:|
   ||[ModelMetaMapper.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelMetaMapper.java)|0.0%|:red_circle:|
   ||[ModelVersionAliasRelMapper.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionAliasRelMapper.java)|0.0%|:red_circle:|
   ||[ModelVersionMetaMapper.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ModelVersionMetaMapper.java)|0.0%|:red_circle:|
   ||[TagDispatcher.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java)|0.0%|:red_circle:|
   |flink-common|[BaseCatalog.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/catalog/BaseCatalog.java)|41.49%|:red_circle:|
   ||[GravitinoHiveCatalog.java](https://github.com/qqqttt123/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/hive/GravitinoHiveCatalog.java)|6.67%|:red_circle:|
   
   </details>


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

To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org

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


Re: [PR] [#12176] feat(core): resolve policies from tag associations [gravitino]

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


##########
core/src/main/java/org/apache/gravitino/policy/PolicyManager.java:
##########
@@ -261,41 +267,49 @@ public MetadataObject[] listMetadataObjectsForPolicy(String metalake, String pol
   }
 
   @Override
-  public PolicyEntity[] listPolicyInfosForMetadataObject(
-      String metalake, MetadataObject metadataObject) {
-    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
-    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
-
-    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+  public RelationalEntity<?>[] listTagAssociationsForPolicy(String metalake, String policyName) {
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
     checkMetalake(NameIdentifier.of(metalake), entityStore);
-
     return TreeLockUtils.doWithTreeLock(
-        entityIdent,
+        policyIdentifier,
         LockType.READ,
         () -> {
+          getPolicyWithoutLock(metalake, policyName);
           try {
             return entityStore
                 .relationOperations()
-                .listEntitiesByRelation(
-                    SupportsRelationOperations.Type.POLICY_METADATA_OBJECT_REL,
-                    entityIdent,
-                    entityType,
-                    true /* allFields */)
-                .stream()
-                .map(entity -> (PolicyEntity) entity)
-                .toArray(PolicyEntity[]::new);
-          } catch (NoSuchEntityException e) {
-            throw new NoSuchMetadataObjectException(
-                e,
-                "Failed to list policies for metadata object %s due to not found",
-                metadataObject);
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(policyIdentifier),
+                    Entity.EntityType.POLICY)
+                .toArray(new RelationalEntity<?>[0]);
           } catch (IOException e) {
-            LOG.error("Failed to list policies for metadata object {}", metadataObject, e);
+            LOG.error(
+                "Failed to list tag associations for policy {} under metalake {}",
+                policyName,
+                metalake,
+                e);
             throw new RuntimeException(e);
           }
         });
   }
 
+  @Override
+  public PolicyEntity[] listPolicyInfosForMetadataObject(
+      String metalake, MetadataObject metadataObject) {
+    NameIdentifier entityIdent = MetadataObjectUtil.toEntityIdent(metalake, metadataObject);
+    Entity.EntityType entityType = MetadataObjectUtil.toEntityType(metadataObject);
+    MetadataObjectUtil.checkMetadataObject(metalake, metadataObject);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+
+    Map<Long, PolicyEntity> policiesById = new LinkedHashMap<>();
+    Arrays.stream(listDirectPoliciesForMetadataObject(entityIdent, entityType, metadataObject))
+        .forEach(policy -> policiesById.putIfAbsent(policy.id(), policy));
+    Arrays.stream(objectPolicyResolver.resolve(metalake, metadataObject))

Review Comment:
   `ObjectPolicyResolver.resolve` already walks the requested object and all parents through `EffectiveTagResolver`, while [`MetadataObjectPolicyOperations`](https://github.com/apache/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectPolicyOperations.java#L182-L211) still calls this method once for the object and again for each parent. A child override such as `data_domain=risk` over a parent `data_domain=finance` is therefore evaluated correctly here, but the later parent call adds a `TAG_VALUE("finance")` policy back. Policies selected from inherited tags are also returned in the first call and marked `inherited=false` by the REST layer. Please resolve tag-derived policies exactly once for the requested object, keep any direct-policy compatibility traversal separate, and add an end-to-end override regression test.



##########
core/src/main/java/org/apache/gravitino/tag/TagManager.java:
##########
@@ -227,6 +231,109 @@ public MetadataObject[] listMetadataObjectsForTag(String metalake, String name)
     return listMetadataObjectsForTag(metalake, name, null);
   }
 
+  @Override
+  public RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, name);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    return TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.READ,
+        () -> {
+          try {
+            return entityStore
+                .relationOperations()
+                .batchListEntitiesByRelation(
+                    SupportsRelationOperations.Type.POLICY_TAG_REL,
+                    Collections.singletonList(tagIdentifier),
+                    Entity.EntityType.TAG)
+                .toArray(new RelationalEntity<?>[0]);
+          } catch (IOException e) {
+            LOG.error(
+                "Failed to list policy associations for tag {} under metalake {}",
+                name,
+                metalake,
+                e);
+            throw new RuntimeException(e);
+          }
+        });
+  }
+
+  @Override
+  public void addPolicyForTag(
+      String metalake, String tagName, String policyName, PolicyAssociationSelector selector) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, tagName);
+    NameIdentifier policyIdentifier = NameIdentifierUtil.ofPolicy(metalake, policyName);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.WRITE,
+        () -> {
+          RelationUpdate update =
+              RelationUpdate.of(
+                  SupportsRelationOperations.Type.POLICY_TAG_REL,
+                  tagIdentifier,
+                  Entity.EntityType.TAG,
+                  new RelationEdgeTarget[] {
+                    RelationEdgeTarget.of(
+                        policyIdentifier,
+                        Entity.EntityType.POLICY,
+                        PolicyAssociationSelectorSerde.serialize(selector))

Review Comment:
   This method persists the selector without validating it against the tag's `TagValueConstraint`. It accepts `TAG_VALUE("engineering")` for an `ALLOWED_VALUES("finance", "risk")` tag, or any `TAG_VALUE` for a `NO_VALUE` tag, creating an association that can never match. Please load the tag under the lock, validate the selector against its constraint, and add negative tests for unsupported values and constraint types.



##########
core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java:
##########
@@ -117,6 +119,56 @@ default Tag createTag(
    */
   MetadataObject[] listMetadataObjectsForTag(String metalake, String name);
 
+  /**
+   * List policy names directly associated with the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The directly associated policy names.
+   */
+  default String[] listPoliciesForTag(String metalake, String name) {
+    return Arrays.stream(listPolicyAssociationsForTag(metalake, name))
+        .map(association -> association.targetEntity().name())
+        .toArray(String[]::new);
+  }
+
+  /**
+   * List policy associations, including selectors, for the specified tag.
+   *
+   * @param metalake The name of the metalake.
+   * @param name The name of the tag.
+   * @return The policy-to-tag associations.
+   */
+  default RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {

Review Comment:
   [`GravitinoEnv`](https://github.com/apache/gravitino/blob/18ca5608f4a57ebad241fbcde5a881ae8072d167/core/src/main/java/org/apache/gravitino/GravitinoEnv.java#L930-L937) exposes `TagHookDispatcher(TagEventDispatcher(TagManager))`, but neither wrapper overrides these new default methods, so calls through the production dispatcher stop at this `UnsupportedOperationException` instead of reaching `TagManager`. `PolicyHookDispatcher`/`PolicyEventDispatcher` have the same gap for `listTagAssociationsForPolicy`. Please delegate the new operations through both wrapper layers and test the composed runtime chain.



##########
core/src/main/java/org/apache/gravitino/tag/TagManager.java:
##########
@@ -227,6 +231,109 @@ public MetadataObject[] listMetadataObjectsForTag(String metalake, String name)
     return listMetadataObjectsForTag(metalake, name, null);
   }
 
+  @Override
+  public RelationalEntity<?>[] listPolicyAssociationsForTag(String metalake, String name) {
+    NameIdentifier tagIdentifier = NameIdentifierUtil.ofTag(metalake, name);
+    checkMetalake(NameIdentifier.of(metalake), entityStore);
+    return TreeLockUtils.doWithTreeLock(
+        tagIdentifier,
+        LockType.READ,
+        () -> {
+          try {
+            return entityStore
+                .relationOperations()
+                .batchListEntitiesByRelation(

Review Comment:
   `batchListEntitiesByRelation` returns an empty list when no matching relation exists and does not prove that the anchor tag exists. Because this method never loads the tag, a nonexistent tag is indistinguishable from an existing tag with no policies, so the planned GET endpoint cannot honor its 404 contract. Please check the tag under the read lock before querying and add a missing-tag test.



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