This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new f38f3de65a [#14749][#14424] fix: Support experimental scans and 
validate tag selectors (#14779)
f38f3de65a is described below

commit f38f3de65a538e0b73ef398a399eeefb076c7c7b
Author: roryqi <[email protected]>
AuthorDate: Tue Nov 10 14:09:37 2026 +0800

    [#14749][#14424] fix: Support experimental scans and validate tag selectors 
(#14779)
    
    ### What changes were proposed in this pull request?
    
    - Resolve scan response partition-spec methods lazily through cached
    public/protected lookups compatible with standard and experimental
    Iceberg. Unsupported runtimes report the inaccessible method when
    scanning is used.
    - Validate `TAG_VALUE` policy selectors in the core relation-store
    transaction while holding the tag row lock. This covers REST,
    `TagManager`, and direct relation-store callers.
    
    ### Why are the changes needed?
    
    Experimental scan planning throws `IllegalAccessError`, and invalid tag
    selectors create policy associations that can never match.
    
    Fixes #14749
    Fixes #14424
    
    ### Does this PR introduce _any_ user-facing change?
    
    Experimental scan planning and credential copying succeed. Invalid tag
    selector values return HTTP 400. Tag constraints remain fixed at
    creation; existing associations are not rewritten.
    
    ### How was this patch tested?
    
    - Core tag tests and policy-to-tag storage tests on H2, MySQL, and
    PostgreSQL, including concurrent constraint writes, rejected batch
    updates, case-sensitive values, no-value tags, and null constraints.
    - REST tag tests verify core validation failures return HTTP 400, plus
    missing tags, valid selectors, and hidden tag rejection.
    - Standard and experimental Iceberg regression tests cover scan
    planning, credential copying, historical partition specs, and actionable
    method-resolution failures.
    - Spotless and `git diff --check`.
---
 .../org/apache/gravitino/tag/TagOperations.java    |   1 +
 .../relational/service/PolicyTagRelService.java    |  25 ++-
 .../storage/relational/service/TagMetaService.java |   7 +-
 .../org/apache/gravitino/tag/TagDispatcher.java    |   4 +
 .../service/TestPolicyTagRelService.java           | 155 +++++++++++++++
 .../relational/service/TestTagMetaService.java     |  48 +++++
 .../org/apache/gravitino/tag/TestTagManager.java   |  36 +++-
 docs/policies.md                                   |   8 +
 gradle/libs.versions.toml                          |   1 +
 .../build.gradle.kts                               |   1 +
 .../TestExperimentalIcebergScanResponses.java      |  22 ++
 iceberg/iceberg-rest-server/build.gradle.kts       |   1 +
 .../iceberg/service/CatalogWrapperForREST.java     |   7 +-
 .../iceberg/service/IcebergRESTUtils.java          |  51 ++++-
 .../iceberg/service/TestIcebergScanResponses.java  | 221 +++++++++++++++++++++
 .../gravitino/server/web/rest/TagOperations.java   |   9 +-
 .../server/web/rest/TestTagOperations.java         |  77 +++++++
 17 files changed, 658 insertions(+), 16 deletions(-)

diff --git a/api/src/main/java/org/apache/gravitino/tag/TagOperations.java 
b/api/src/main/java/org/apache/gravitino/tag/TagOperations.java
index 4f0f41b561..2c6784dd47 100644
--- a/api/src/main/java/org/apache/gravitino/tag/TagOperations.java
+++ b/api/src/main/java/org/apache/gravitino/tag/TagOperations.java
@@ -159,6 +159,7 @@ public interface TagOperations {
    * @param selector The non-null policy association selector.
    * @return The resulting association.
    * @throws PolicyAlreadyAssociatedException If the policy is already 
associated with the tag.
+   * @throws IllegalArgumentException If the selector violates the tag's value 
constraint.
    * @throws UnsupportedOperationException If adding policy-to-tag 
associations is not supported.
    */
   default PolicyTagAssociation addPolicyForTag(
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyTagRelService.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyTagRelService.java
index 57cc32cd7e..a2de79441b 100644
--- 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyTagRelService.java
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyTagRelService.java
@@ -42,9 +42,12 @@ import org.apache.gravitino.SupportsRelationOperations;
 import org.apache.gravitino.exceptions.NoSuchEntityException;
 import org.apache.gravitino.exceptions.OptimisticLockException;
 import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.json.PolicyAssociationSelectorSerde;
 import org.apache.gravitino.meta.AuditInfo;
 import org.apache.gravitino.meta.PolicyEntity;
 import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.policy.PolicyAssociationSelector;
+import org.apache.gravitino.policy.TagValueSelector;
 import org.apache.gravitino.storage.relational.mapper.PolicyMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.PolicyTagRelMapper;
 import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
@@ -52,6 +55,7 @@ import org.apache.gravitino.storage.relational.po.PolicyPO;
 import org.apache.gravitino.storage.relational.po.PolicyTagRelPO;
 import org.apache.gravitino.storage.relational.po.TagPO;
 import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagValue;
 import org.apache.gravitino.utils.NameIdentifierUtil;
 import org.apache.gravitino.utils.PrincipalUtils;
 
@@ -118,7 +122,8 @@ public class PolicyTagRelService {
    * @return All active policy targets for the tag after the update.
    * @throws IOException If selector audit information cannot be serialized.
    * @throws EntityAlreadyExistsException If a relation to add already exists.
-   * @throws IllegalArgumentException If the same relation is both added and 
removed.
+   * @throws IllegalArgumentException If a selector violates the tag's value 
constraint or the same
+   *     relation is both added and removed.
    */
   public List<PolicyEntity> updateRelations(
       NameIdentifier tagIdentifier,
@@ -186,6 +191,12 @@ public class PolicyTagRelService {
     long tagId = tagPO.getTagId();
     Map<String, Long> policyIds = resolvePolicyIds(metalake, targetsToAdd, 
targetsToRemove);
 
+    // Validate the locked row in the same transaction as the relation write. 
Do not carry a
+    // constraint read by REST or a dispatcher across this transaction 
boundary.
+    for (RelationEdgeTarget target : targetsToAdd) {
+      validateSelector(tagPO, target.relationValue().orElse(null));
+    }
+
     for (RelationEdgeTarget target : targetsToRemove) {
       long policyId = policyIds.get(target.nameIdentifier().name());
       PolicyTagRelPO existing =
@@ -217,6 +228,18 @@ public class PolicyTagRelService {
         .collect(Collectors.toList());
   }
 
+  private static void validateSelector(TagPO tagPO, @Nullable String 
selectorJson)
+      throws IOException {
+    if (selectorJson == null) {
+      return;
+    }
+    PolicyAssociationSelector selector = 
PolicyAssociationSelectorSerde.deserialize(selectorJson);
+    if (selector instanceof TagValueSelector) {
+      TagMetaService.validateAllowedValue(
+          tagPO, TagValue.of(tagPO.getTagName(), ((TagValueSelector) 
selector).value()));
+    }
+  }
+
   private static List<RelationalEntity<?>> policyTargets(
       String metalake, List<PolicyTagRelPO> relations) {
     Set<String> policyNames =
diff --git 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
index 0f37a25658..62effef3bc 100644
--- 
a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
+++ 
b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
@@ -790,14 +790,17 @@ public class TagMetaService {
         tagValue.value().orElse(null));
   }
 
-  private static void validateAllowedValue(TagPO tagPO, TagValue tagValue)
-      throws JsonProcessingException {
+  static void validateAllowedValue(TagPO tagPO, TagValue tagValue) throws 
JsonProcessingException {
     if (tagPO.getAllowedValues() == null) {
       return;
     }
 
     String[] allowedValues =
         JsonUtils.anyFieldMapper().readValue(tagPO.getAllowedValues(), 
String[].class);
+    // Treat JSON null like SQL NULL, consistent with POConverters.
+    if (allowedValues == null) {
+      return;
+    }
     if (!tagValue.value().isPresent()) {
       Preconditions.checkArgument(
           allowedValues.length == 0,
diff --git a/core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java 
b/core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java
index e354254eca..04d1908cfe 100644
--- a/core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/tag/TagDispatcher.java
@@ -146,10 +146,14 @@ public interface TagDispatcher {
   /**
    * Add one policy association for a tag.
    *
+   * <p>A tag-value selector must satisfy the tag's value constraint. 
Validation and the association
+   * write occur in one storage transaction.
+   *
    * @param metalake The name of the metalake.
    * @param tagName The name of the tag.
    * @param policyName The name of the policy.
    * @param selector The non-null policy association selector.
+   * @throws IllegalArgumentException If the selector value violates the tag's 
value constraint.
    */
   default void addPolicyForTag(
       String metalake, String tagName, String policyName, 
PolicyAssociationSelector selector) {
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyTagRelService.java
 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyTagRelService.java
index 4ef7d0da69..5bdab31b73 100644
--- 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyTagRelService.java
+++ 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyTagRelService.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.storage.relational.service;
 
 import java.io.IOException;
 import java.sql.Connection;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
@@ -28,12 +29,15 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.CyclicBarrier;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
+import javax.annotation.Nullable;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.EntityAlreadyExistsException;
 import org.apache.gravitino.NameIdentifier;
@@ -65,6 +69,150 @@ public class TestPolicyTagRelService extends 
TestJDBCBackend {
   private static final String FINANCE_SELECTOR = 
"{\"type\":\"TAG_VALUE\",\"value\":\"finance\"}";
   private static final String RISK_SELECTOR = 
"{\"type\":\"TAG_VALUE\",\"value\":\"risk\"}";
 
+  /** Verifies selector constraints for direct storage callers and rolls back 
rejected updates. */
+  @TestTemplate
+  public void testSelectorValueConstraints() throws IOException {
+    createAndInsertMakeLake(METALAKE);
+    List<String[]> constraints =
+        Arrays.asList(null, new String[0], new String[] {"finance", "risk"});
+    for (int i = 0; i < constraints.size(); i++) {
+      String[] allowedValues = constraints.get(i);
+      RelationEndpoints endpoints =
+          createEndpoints(METALAKE, "domain_" + i, "retention_" + i, 
allowedValues);
+      RelationUpdate finance = relationUpdate(endpoints, FINANCE_SELECTOR, 
true);
+      if (allowedValues != null && allowedValues.length == 0) {
+        IllegalArgumentException error =
+            Assertions.assertThrows(
+                IllegalArgumentException.class, () -> 
backend.updateEntityRelations(finance));
+        Assertions.assertTrue(error.getMessage().contains("does not allow 
assignment values"));
+        Assertions.assertNull(getRelation(endpoints));
+      } else {
+        backend.updateEntityRelations(finance);
+        Assertions.assertEquals(FINANCE_SELECTOR, 
getRelation(endpoints).getSelector());
+        backend.updateEntityRelations(relationUpdate(endpoints, 
FINANCE_SELECTOR, false));
+      }
+
+      backend.updateEntityRelations(relationUpdate(endpoints, null, true));
+      if (allowedValues != null && allowedValues.length > 0) {
+        PolicyEntity otherPolicy =
+            createPolicy(
+                RandomIdGenerator.INSTANCE.nextId(),
+                NamespaceUtil.ofPolicy(METALAKE),
+                "other_retention",
+                AUDIT_INFO);
+        backend.insert(otherPolicy, false);
+        for (String invalidValue : new String[] {"engineering", "Finance"}) {
+          RelationEdgeTarget invalid =
+              RelationEdgeTarget.of(
+                  otherPolicy.nameIdentifier(),
+                  Entity.EntityType.POLICY,
+                  "{\"type\":\"TAG_VALUE\",\"value\":\"" + invalidValue + 
"\"}");
+          RelationEdgeTarget existing =
+              RelationEdgeTarget.of(
+                  endpoints.policy.nameIdentifier(), Entity.EntityType.POLICY, 
null);
+          Assertions.assertThrows(
+              IllegalArgumentException.class,
+              () ->
+                  backend.updateEntityRelations(
+                      RelationUpdate.of(
+                          SupportsRelationOperations.Type.POLICY_TAG_REL,
+                          endpoints.tag.nameIdentifier(),
+                          Entity.EntityType.TAG,
+                          new RelationEdgeTarget[] {invalid},
+                          new RelationEdgeTarget[] {existing})));
+          Assertions.assertNotNull(getRelation(endpoints));
+          Assertions.assertEquals(
+              1,
+              backend
+                  .batchListEntitiesByRelation(
+                      SupportsRelationOperations.Type.POLICY_TAG_REL,
+                      
Collections.singletonList(endpoints.tag.nameIdentifier()),
+                      Entity.EntityType.TAG)
+                  .size());
+        }
+      }
+    }
+  }
+
+  /** Verifies that a null JSON constraint is treated as unrestricted without 
a null dereference. */
+  @TestTemplate
+  public void testNullJsonAllowedValues() throws Exception {
+    createAndInsertMakeLake(METALAKE);
+    RelationEndpoints endpoints = createEndpoints(METALAKE, "domain", 
"retention");
+    try (SqlSession session =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(false);
+        PreparedStatement statement =
+            session
+                .getConnection()
+                .prepareStatement("UPDATE tag_meta SET allowed_values = ? 
WHERE tag_id = ?")) {
+      statement.setString(1, "null");
+      statement.setLong(2, endpoints.tag.id());
+      Assertions.assertEquals(1, statement.executeUpdate());
+      session.commit(true);
+    }
+    backend.updateEntityRelations(relationUpdate(endpoints, FINANCE_SELECTOR, 
true));
+    Assertions.assertEquals(FINANCE_SELECTOR, 
getRelation(endpoints).getSelector());
+  }
+
+  /** Verifies validation uses the row locked for writing, including 
concurrent storage changes. */
+  @TestTemplate
+  public void testSelectorValidationUsesLockedTagConstraint() throws Exception 
{
+    createAndInsertMakeLake(METALAKE);
+    RelationEndpoints endpoints = createEndpoints(METALAKE, "domain", 
"retention");
+    CountDownLatch constraintWritten = new CountDownLatch(1);
+    CountDownLatch allowCommit = new CountDownLatch(1);
+    CountDownLatch associationStarted = new CountDownLatch(1);
+    ExecutorService executor = Executors.newFixedThreadPool(2);
+    try {
+      // The public alter API cannot change constraints. Simulate a storage 
writer to prove that
+      // relation validation reads the committed constraint under the existing 
tag row lock.
+      Future<?> writer =
+          executor.submit(
+              () -> {
+                try (SqlSession session =
+                        SqlSessionFactoryHelper.getInstance()
+                            .getSqlSessionFactory()
+                            .openSession(false);
+                    PreparedStatement statement =
+                        session
+                            .getConnection()
+                            .prepareStatement(
+                                "UPDATE tag_meta SET allowed_values = ? WHERE 
tag_id = ?")) {
+                  statement.setString(1, "[\"risk\"]");
+                  statement.setLong(2, endpoints.tag.id());
+                  Assertions.assertEquals(1, statement.executeUpdate());
+                  constraintWritten.countDown();
+                  Assertions.assertTrue(allowCommit.await(30, 
TimeUnit.SECONDS));
+                  session.commit(true);
+                }
+                return null;
+              });
+      Assertions.assertTrue(constraintWritten.await(30, TimeUnit.SECONDS));
+      Future<Throwable> association =
+          executor.submit(
+              () -> {
+                try {
+                  associationStarted.countDown();
+                  backend.updateEntityRelations(relationUpdate(endpoints, 
FINANCE_SELECTOR, true));
+                  return null;
+                } catch (Throwable failure) {
+                  return failure;
+                }
+              });
+      Assertions.assertTrue(associationStarted.await(30, TimeUnit.SECONDS));
+      Assertions.assertThrows(
+          TimeoutException.class, () -> association.get(500, 
TimeUnit.MILLISECONDS));
+      allowCommit.countDown();
+      writer.get(30, TimeUnit.SECONDS);
+      Assertions.assertInstanceOf(
+          IllegalArgumentException.class, association.get(30, 
TimeUnit.SECONDS));
+      Assertions.assertNull(getRelation(endpoints));
+    } finally {
+      allowCommit.countDown();
+      executor.shutdownNow();
+    }
+  }
+
   @TestTemplate
   public void testSelectorCreateConflictBidirectionalReadAndIdempotentDelete() 
throws IOException {
     createAndInsertMakeLake(METALAKE);
@@ -506,12 +654,19 @@ public class TestPolicyTagRelService extends 
TestJDBCBackend {
 
   private RelationEndpoints createEndpoints(String metalake, String tagName, 
String policyName)
       throws IOException {
+    return createEndpoints(metalake, tagName, policyName, null);
+  }
+
+  private RelationEndpoints createEndpoints(
+      String metalake, String tagName, String policyName, @Nullable String[] 
allowedValues)
+      throws IOException {
     TagEntity tag =
         TagEntity.builder()
             .withId(RandomIdGenerator.INSTANCE.nextId())
             .withName(tagName)
             .withNamespace(NamespaceUtil.ofTag(metalake))
             .withProperties(Collections.emptyMap())
+            .withAllowedValues(allowedValues)
             .withAuditInfo(AUDIT_INFO)
             .build();
     PolicyEntity policy =
diff --git 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
index 7194e5dae3..86910b9c7a 100644
--- 
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
+++ 
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java
@@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
 import java.io.IOException;
 import java.sql.Connection;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
@@ -1326,6 +1327,53 @@ public class TestTagMetaService extends TestJDBCBackend {
     Assertions.assertTrue(containsValuelessTagAssignment(tagEntities7, 
tagEntity3));
   }
 
+  /** Verifies a stored JSON null constraint permits valued and valueless tag 
assignments. */
+  @TestTemplate
+  public void testAssociateTagValuesWithNullJsonConstraint() throws 
IOException {
+    createAndInsertMakeLake(METALAKE_NAME);
+    CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, 
"catalog_null_constraint");
+    TagMetaService service = TagMetaService.getInstance();
+    TagEntity tag =
+        TagEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("stage")
+            .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    service.insertTag(tag, false);
+    try (SqlSession session =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(false);
+        PreparedStatement statement =
+            session
+                .getConnection()
+                .prepareStatement("UPDATE tag_meta SET allowed_values = ? 
WHERE tag_id = ?")) {
+      statement.setString(1, "null");
+      statement.setLong(2, tag.id());
+      Assertions.assertEquals(1, statement.executeUpdate());
+      session.commit(true);
+    } catch (SQLException e) {
+      throw new IOException(e);
+    }
+
+    List<TagEntity> valued =
+        service.associateTagValuesWithMetadataObject(
+            catalog.nameIdentifier(),
+            catalog.type(),
+            new TagValue[] {TagValue.of(tag.name(), "dev")},
+            new TagValue[0]);
+    Assertions.assertEquals(1, valued.size());
+    assertAssignmentValues(valued.get(0), "dev");
+
+    List<TagEntity> valueless =
+        service.associateTagValuesWithMetadataObject(
+            catalog.nameIdentifier(),
+            catalog.type(),
+            new TagValue[] {TagValue.noValue(tag.name())},
+            new TagValue[] {TagValue.of(tag.name(), "dev")});
+    Assertions.assertEquals(1, valueless.size());
+    Assertions.assertTrue(containsValuelessTagAssignment(valueless, tag));
+  }
+
   @TestTemplate
   public void testAssociateTagValuesWithMetadataObject() throws IOException {
     createAndInsertMakeLake(METALAKE_NAME);
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java 
b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
index 21afbb94ba..ee2bc9e42e 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -1767,13 +1767,45 @@ public class TestTagManager {
       tagManager.removePolicyFromTag(METALAKE, tagName, policyName);
       Assertions.assertEquals(0, 
tagManager.listPolicyAssociationsForTag(METALAKE, tagName).length);
 
-      tagManager.addPolicyForTag(METALAKE, tagName, policyName, 
TagValueSelector.of("engineering"));
+      for (String invalidValue : new String[] {"engineering", "Finance"}) {
+        IllegalArgumentException error =
+            Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                    tagManager.addPolicyForTag(
+                        METALAKE, tagName, policyName, 
TagValueSelector.of(invalidValue)));
+        Assertions.assertTrue(error.getMessage().contains("is not in allowed 
values"));
+        Assertions.assertEquals(
+            0, tagManager.listPolicyAssociationsForTag(METALAKE, 
tagName).length);
+      }
+
+      tagManager.addPolicyForTag(METALAKE, tagName, policyName, 
TagValueSelector.of("finance"));
       associations = tagManager.listPolicyAssociationsForTag(METALAKE, 
tagName);
       Assertions.assertEquals(
-          TagValueSelector.of("engineering"),
+          TagValueSelector.of("finance"),
           PolicyAssociationSelectorSerde.deserialize(
               associations[0].relationValue().orElseThrow()));
       tagManager.removePolicyFromTag(METALAKE, tagName, policyName);
+
+      String noValueTag = "policy_no_value_tag";
+      tagManager.createTag(METALAKE, noValueTag, null, null, 
TagValueConstraint.noValue());
+      Assertions.assertThrows(
+          IllegalArgumentException.class,
+          () ->
+              tagManager.addPolicyForTag(
+                  METALAKE, noValueTag, policyName, 
TagValueSelector.of("finance")));
+      Assertions.assertEquals(
+          0, tagManager.listPolicyAssociationsForTag(METALAKE, 
noValueTag).length);
+      tagManager.addPolicyForTag(METALAKE, noValueTag, policyName, 
AllValuesSelector.get());
+      tagManager.removePolicyFromTag(METALAKE, noValueTag, policyName);
+
+      String anyValueTag = "policy_any_value_tag";
+      tagManager.createTag(METALAKE, anyValueTag, null, null);
+      tagManager.addPolicyForTag(
+          METALAKE, anyValueTag, policyName, 
TagValueSelector.of("engineering"));
+      Assertions.assertEquals(
+          1, tagManager.listPolicyAssociationsForTag(METALAKE, 
anyValueTag).length);
+      tagManager.removePolicyFromTag(METALAKE, anyValueTag, policyName);
     } finally {
       entityStore.delete(
           NameIdentifierUtil.ofPolicy(METALAKE, policyName), 
Entity.EntityType.POLICY);
diff --git a/docs/policies.md b/docs/policies.md
index 29c64b202c..0f940d2f2d 100644
--- a/docs/policies.md
+++ b/docs/policies.md
@@ -342,6 +342,14 @@ A policy may be associated with multiple tags. Association 
listings show those d
 and their selectors, even if no object currently matches them. An object 
policy lookup returns each
 matching policy once.
 
+When adding a `TAG_VALUE` association, Gravitino validates its value against 
the tag's constraint
+in the same storage transaction as the association write. `NO_VALUE` tags 
reject `TAG_VALUE`;
+`ALLOWED_VALUES` tags accept only an exact, case-sensitive match. Invalid 
values
+return HTTP 400. `ALL_VALUES` is valid for every constraint.
+
+Tag value constraints are fixed at creation; the tag alteration API does not 
change them. This
+validation applies when creating associations and does not rewrite existing 
associations.
+
 A selector cannot be changed in place. Remove the policy-to-tag association 
and add it again with
 the new selector. Removing an association leaves the policy, tag, and tag 
assignments intact.
 Deleting a policy removes its associations.
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 119f39530c..2d31540213 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -315,6 +315,7 @@ iceberg-aws-bundle = { group = "org.apache.iceberg", name = 
"iceberg-aws-bundle"
 iceberg-azure = { group = "org.apache.iceberg", name = "iceberg-azure", 
version.ref = "iceberg" }
 iceberg-azure-bundle = { group = "org.apache.iceberg", name = 
"iceberg-azure-bundle", version.ref = "iceberg" }
 iceberg-core = { group = "org.apache.iceberg", name = "iceberg-core", 
version.ref = "iceberg" }
+iceberg-common = { group = "org.apache.iceberg", name = "iceberg-common", 
version.ref = "iceberg" }
 iceberg-api = { group = "org.apache.iceberg", name = "iceberg-api", 
version.ref = "iceberg" }
 iceberg-hive-metastore = { group = "org.apache.iceberg", name = 
"iceberg-hive-metastore", version.ref = "iceberg" }
 iceberg-gcp = { group = "org.apache.iceberg", name = "iceberg-gcp", 
version.ref = "iceberg" }
diff --git a/iceberg/iceberg-rest-server-experiment/build.gradle.kts 
b/iceberg/iceberg-rest-server-experiment/build.gradle.kts
index 7303921cb4..5305e3057c 100644
--- a/iceberg/iceberg-rest-server-experiment/build.gradle.kts
+++ b/iceberg/iceberg-rest-server-experiment/build.gradle.kts
@@ -121,6 +121,7 @@ dependencies {
   implementation(libs.bundles.iceberg)
 
   testImplementation(testFixturesSources.output)
+  testImplementation(project(":iceberg:iceberg-rest-server", "testArtifacts"))
   testImplementation(project(":server-common"))
   testImplementation(libs.junit.jupiter.params)
   testImplementation(libs.junit.jupiter.api)
diff --git 
a/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/TestExperimentalIcebergScanResponses.java
 
b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/TestExperimentalIcebergScanResponses.java
new file mode 100644
index 0000000000..0000173ce0
--- /dev/null
+++ 
b/iceberg/iceberg-rest-server-experiment/src/test/java/org/apache/gravitino/iceberg/service/TestExperimentalIcebergScanResponses.java
@@ -0,0 +1,22 @@
+/*
+ * 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.iceberg.service;
+
+/** Runs the shared scan response tests with the experimental Iceberg 
distribution. */
+public class TestExperimentalIcebergScanResponses extends 
TestIcebergScanResponses {}
diff --git a/iceberg/iceberg-rest-server/build.gradle.kts 
b/iceberg/iceberg-rest-server/build.gradle.kts
index 7fe437c182..a93d09d8ae 100644
--- a/iceberg/iceberg-rest-server/build.gradle.kts
+++ b/iceberg/iceberg-rest-server/build.gradle.kts
@@ -49,6 +49,7 @@ dependencies {
     exclude("*")
   }
   implementation(libs.bundles.iceberg)
+  implementation(libs.iceberg.common)
   implementation(libs.bundles.jetty)
   implementation(libs.bundles.jersey)
   implementation(libs.bundles.jwt)
diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
index 0d749c3f19..a858409c95 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
@@ -708,12 +708,11 @@ public class CatalogWrapperForREST extends 
IcebergCatalogWrapper {
   @SuppressWarnings("deprecation")
   private static PlanTableScanResponse buildCompletedPlanTableScanResponse(
       Table table, List<FileScanTask> fileScanTasks) {
-    return PlanTableScanResponse.builder()
-        .withPlanStatus(PlanStatus.COMPLETED)
-        .withFileScanTasks(fileScanTasks)
-        .withSpecsById(
+    return IcebergRESTUtils.scanPlanResponseBuilder(
             IcebergScanPlanHelper.sanitizeSpecsForSerialization(
                 table.specs(), fileScanTasks, table.schemas().values()))
+        .withPlanStatus(PlanStatus.COMPLETED)
+        .withFileScanTasks(fileScanTasks)
         .build();
   }
 
diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergRESTUtils.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergRESTUtils.java
index 5b0d479675..f648b9e0ce 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergRESTUtils.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergRESTUtils.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.iceberg.service;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import java.io.IOException;
@@ -38,7 +39,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
+import java.util.function.Supplier;
 import java.util.stream.Stream;
+import javax.annotation.Nullable;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.core.EntityTag;
 import javax.ws.rs.core.MediaType;
@@ -50,15 +53,18 @@ import org.apache.gravitino.credential.Credential;
 import org.apache.gravitino.credential.CredentialPropertyUtils;
 import 
org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;
 import org.apache.gravitino.server.web.JettyServerConfig;
+import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.TableMetadata;
 import org.apache.iceberg.catalog.Namespace;
 import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.common.DynMethods;
 import org.apache.iceberg.exceptions.BadRequestException;
 import org.apache.iceberg.io.FileIO;
 import org.apache.iceberg.io.StorageCredential;
 import org.apache.iceberg.io.SupportsStorageCredentials;
 import org.apache.iceberg.rest.RESTRequest;
 import org.apache.iceberg.rest.RESTUtil;
+import org.apache.iceberg.rest.responses.BaseScanTaskResponse;
 import org.apache.iceberg.rest.responses.ErrorResponse;
 import org.apache.iceberg.rest.responses.ImmutableLoadCredentialsResponse;
 import org.apache.iceberg.rest.responses.LoadCredentialsResponse;
@@ -71,6 +77,17 @@ public class IcebergRESTUtils {
 
   private static final Logger LOG = 
LoggerFactory.getLogger(IcebergRESTUtils.class);
 
+  // Resolve scan-only methods lazily so an incompatible runtime cannot 
prevent unrelated REST
+  // helpers from loading. Successful lookups are cached; failed lookups 
retain a useful error.
+  private static final Supplier<DynMethods.UnboundMethod> SCAN_RESPONSE_SPECS =
+      Suppliers.memoize(() -> 
resolveScanResponseMethod(BaseScanTaskResponse.class, "specsById"));
+
+  private static final Supplier<DynMethods.UnboundMethod> 
SCAN_RESPONSE_WITH_SPECS =
+      Suppliers.memoize(
+          () ->
+              resolveScanResponseMethod(
+                  BaseScanTaskResponse.Builder.class, "withSpecsById", 
Map.class));
+
   /**
    * URL-encoded UTF-8 namespace separator ({@code 0x1F}) required by the 
Iceberg REST catalog spec.
    *
@@ -347,17 +364,47 @@ public class IcebergRESTUtils {
   static PlanTableScanResponse copyWithCredentials(
       PlanTableScanResponse response,
       List<org.apache.iceberg.rest.credentials.Credential> credentials) {
-    return PlanTableScanResponse.builder()
+    return scanPlanResponseBuilder(scanResponseSpecs(response))
         .withPlanStatus(response.planStatus())
         .withPlanId(response.planId())
         .withPlanTasks(response.planTasks())
         .withFileScanTasks(response.fileScanTasks())
-        .withSpecsById(response.specsById())
         .withErrorResponse(response.errorResponse())
         .withCredentials(credentials)
         .build();
   }
 
+  /** Creates a scan response builder with specs on both supported Iceberg 
runtimes. */
+  static PlanTableScanResponse.Builder scanPlanResponseBuilder(
+      @Nullable Map<Integer, PartitionSpec> specs) {
+    return 
SCAN_RESPONSE_WITH_SPECS.get().invoke(PlanTableScanResponse.builder(), specs);
+  }
+
+  /** Returns the full response spec map, including historical specs not 
referenced by tasks. */
+  @Nullable
+  static Map<Integer, PartitionSpec> scanResponseSpecs(PlanTableScanResponse 
response) {
+    return SCAN_RESPONSE_SPECS.get().invoke(response);
+  }
+
+  /** Resolves public methods first, then protected methods used by 
experimental Iceberg. */
+  static DynMethods.UnboundMethod resolveScanResponseMethod(
+      Class<?> implementation, String name, Class<?>... argumentTypes) {
+    try {
+      return DynMethods.builder(name)
+          .impl(implementation, argumentTypes)
+          .hiddenImpl(implementation, argumentTypes)
+          .buildChecked();
+    } catch (ReflectiveOperationException | RuntimeException e) {
+      throw new IllegalStateException(
+          "Cannot access Iceberg scan response method "
+              + implementation.getName()
+              + "."
+              + name
+              + ". Use a supported Iceberg runtime with accessible scan 
response spec methods.",
+          e);
+    }
+  }
+
   public static <T> Response ok(T t) {
     return 
Response.status(Response.Status.OK).entity(t).type(MediaType.APPLICATION_JSON).build();
   }
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanResponses.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanResponses.java
new file mode 100644
index 0000000000..5742d55185
--- /dev/null
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanResponses.java
@@ -0,0 +1,221 @@
+/*
+ * 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.iceberg.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.SupportsNamespaces;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.rest.PlanStatus;
+import org.apache.iceberg.rest.credentials.Credential;
+import org.apache.iceberg.rest.credentials.ImmutableCredential;
+import org.apache.iceberg.rest.requests.PlanTableScanRequest;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.iceberg.rest.responses.PlanTableScanResponse;
+import org.apache.iceberg.rest.responses.PlanTableScanResponseParser;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/** Scan response tests shared by the standard and experimental Iceberg 
runtimes. */
+public class TestIcebergScanResponses {
+
+  private static final TableIdentifier IDENT = TableIdentifier.of("db", 
"table");
+
+  @TempDir Path warehouse;
+
+  private CatalogWrapperForREST wrapper;
+  private Table table;
+
+  @BeforeEach
+  void setUp() {
+    wrapper =
+        new CatalogWrapperForREST(
+            "scan-response-test",
+            new IcebergConfig(
+                Map.of(
+                    IcebergConstants.CATALOG_BACKEND,
+                    "memory",
+                    IcebergConstants.WAREHOUSE,
+                    warehouse.toString())));
+    ((SupportsNamespaces) 
wrapper.getCatalog()).createNamespace(Namespace.of("db"));
+    table =
+        wrapper
+            .getCatalog()
+            .createTable(
+                IDENT,
+                new Schema(Types.NestedField.required(1, "id", 
Types.LongType.get())),
+                PartitionSpec.unpartitioned());
+  }
+
+  @AfterEach
+  void tearDown() throws Exception {
+    if (wrapper != null) {
+      wrapper.close();
+    }
+  }
+
+  @Test
+  void testMissingScanMethodHasActionableError() {
+    for (int attempt = 0; attempt < 2; attempt++) {
+      IllegalStateException error =
+          assertThrows(
+              IllegalStateException.class,
+              () -> IcebergRESTUtils.resolveScanResponseMethod(Object.class, 
"specsById"));
+      assertTrue(error.getMessage().contains("java.lang.Object.specsById"));
+      assertTrue(error.getMessage().contains("supported Iceberg runtime"));
+      assertTrue(error.getCause() instanceof NoSuchMethodException);
+      // A failed lookup must not poison the utility class for unrelated REST 
operations.
+      assertEquals(PlanStatus.COMPLETED, plan().planStatus());
+    }
+  }
+
+  @Test
+  void testPlanEmptyTable() throws IOException {
+    PlanTableScanResponse response = plan();
+    assertEquals(PlanStatus.COMPLETED, response.planStatus());
+    assertTrue(response.fileScanTasks().isEmpty());
+    assertEquals(table.specs().keySet(), 
IcebergRESTUtils.scanResponseSpecs(response).keySet());
+    assertEquals(PlanStatus.COMPLETED, roundTrip(response).planStatus());
+  }
+
+  @Test
+  void testPlanAndCopyCredentialsPreservesTasksAndHistoricalSpecs() throws 
IOException {
+    table
+        .newFastAppend()
+        .appendFile(
+            DataFiles.builder(table.spec())
+                .withPath(warehouse.resolve("data.parquet").toString())
+                .withFileSizeInBytes(10)
+                .withRecordCount(1)
+                .build())
+        .commit();
+    table.updateSpec().addField("id").commit();
+    PlanTableScanResponse original = plan();
+    assertEquals(1, original.fileScanTasks().size());
+    assertEquals(2, IcebergRESTUtils.scanResponseSpecs(original).size());
+
+    List<Credential> credentials =
+        Collections.singletonList(
+            ImmutableCredential.builder()
+                .prefix(table.location())
+                .config(Map.of("s3.access-key-id", "key"))
+                .build());
+    PlanTableScanResponse copied = 
IcebergRESTUtils.copyWithCredentials(original, credentials);
+    assertEquals(original.planStatus(), copied.planStatus());
+    assertEquals(original.fileScanTasks(), copied.fileScanTasks());
+    assertEquals(
+        IcebergRESTUtils.scanResponseSpecs(original), 
IcebergRESTUtils.scanResponseSpecs(copied));
+    assertEquals(credentials, copied.credentials());
+    assertTrue(original.credentials() == null || 
original.credentials().isEmpty());
+
+    PlanTableScanResponse decoded = roundTrip(copied);
+    assertEquals(1, decoded.fileScanTasks().size());
+    assertEquals(table.specs().keySet(), 
IcebergRESTUtils.scanResponseSpecs(decoded).keySet());
+    assertEquals(credentials.get(0).config(), 
decoded.credentials().get(0).config());
+  }
+
+  @Test
+  void testRewriteScanCredentials() {
+    PlanTableScanResponse original = plan();
+    assertSame(original, 
IcebergRESTUtils.rewriteScanPlanCredentials("catalog", IDENT, original));
+    Credential credential =
+        ImmutableCredential.builder()
+            .prefix(table.location())
+            .config(
+                Map.of(
+                    "s3.access-key-id", "key",
+                    "s3.session-token", "token",
+                    "client.refresh-credentials-endpoint", 
"https://upstream/credentials";))
+            .build();
+    PlanTableScanResponse upstream =
+        IcebergRESTUtils.copyWithCredentials(original, 
Collections.singletonList(credential));
+    PlanTableScanResponse rewritten =
+        IcebergRESTUtils.rewriteScanPlanCredentials("catalog", IDENT, 
upstream);
+    assertEquals(1, rewritten.credentials().size());
+    assertEquals(
+        "v1/catalog/namespaces/db/tables/table/credentials",
+        
rewritten.credentials().get(0).config().get("client.refresh-credentials-endpoint"));
+    assertEquals("key", 
rewritten.credentials().get(0).config().get("s3.access-key-id"));
+    assertEquals(
+        IcebergRESTUtils.scanResponseSpecs(original),
+        IcebergRESTUtils.scanResponseSpecs(rewritten));
+    assertFalse(
+        
upstream.credentials().get(0).config().equals(rewritten.credentials().get(0).config()));
+  }
+
+  @Test
+  void testCopyPreservesPlanIdAndTasks() {
+    PlanTableScanResponse original =
+        PlanTableScanResponse.builder()
+            .withPlanStatus(PlanStatus.COMPLETED)
+            .withPlanId("plan-id")
+            .withPlanTasks(Collections.singletonList("task"))
+            .build();
+    PlanTableScanResponse copied =
+        IcebergRESTUtils.copyWithCredentials(original, 
Collections.emptyList());
+    assertEquals(original.planStatus(), copied.planStatus());
+    assertEquals(original.planId(), copied.planId());
+    assertEquals(original.planTasks(), copied.planTasks());
+  }
+
+  @Test
+  void testCopyPreservesError() {
+    ErrorResponse error =
+        
ErrorResponse.builder().responseCode(500).withType("error").withMessage("failed").build();
+    PlanTableScanResponse original =
+        PlanTableScanResponse.builder()
+            .withPlanStatus(PlanStatus.FAILED)
+            .withErrorResponse(error)
+            .build();
+    PlanTableScanResponse copied =
+        IcebergRESTUtils.copyWithCredentials(original, 
Collections.emptyList());
+    assertEquals(original.planStatus(), copied.planStatus());
+    assertSame(error, copied.errorResponse());
+  }
+
+  private PlanTableScanResponse plan() {
+    return wrapper.planTableScan(IDENT, 
PlanTableScanRequest.builder().build());
+  }
+
+  private PlanTableScanResponse roundTrip(PlanTableScanResponse response) 
throws IOException {
+    return PlanTableScanResponseParser.fromJson(
+        
IcebergObjectMapper.getInstance().readTree(PlanTableScanResponseParser.toJson(response)),
+        table.specs(),
+        true);
+  }
+}
diff --git 
a/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java 
b/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java
index c2fa12597d..bd207cfeb2 100644
--- 
a/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java
+++ 
b/server/src/main/java/org/apache/gravitino/server/web/rest/TagOperations.java
@@ -66,6 +66,7 @@ import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.meta.PolicyEntity;
 import org.apache.gravitino.metrics.MetricNames;
 import org.apache.gravitino.policy.HiddenPolicyTag;
+import org.apache.gravitino.policy.PolicyAssociationSelector;
 import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
 import 
org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
 import 
org.apache.gravitino.server.authorization.annotations.AuthorizationFullName;
@@ -427,13 +428,11 @@ public class TagOperations {
             PolicyTagAddRequest effectiveRequest =
                 request == null ? new PolicyTagAddRequest() : request;
             effectiveRequest.validate();
-            tagDispatcher.addPolicyForTag(
-                metalake, tagName, policyName, effectiveRequest.selector());
+            PolicyAssociationSelector selector = effectiveRequest.selector();
+            tagDispatcher.addPolicyForTag(metalake, tagName, policyName, 
selector);
             return Utils.ok(
                 new PolicyTagAssociationResponse(
-                    policyName,
-                    tagName,
-                    
PolicyAssociationSelectorDTO.fromSelector(effectiveRequest.selector())));
+                    policyName, tagName, 
PolicyAssociationSelectorDTO.fromSelector(selector)));
           });
     } catch (Exception e) {
       return ExceptionHandlers.handleTagException(OperationType.ASSOCIATE, 
tagName, metalake, e);
diff --git 
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java
 
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java
index b9bdd1264b..e0c37cb8b5 100644
--- 
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java
+++ 
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTagOperations.java
@@ -74,6 +74,7 @@ import org.apache.gravitino.meta.PolicyEntity;
 import org.apache.gravitino.meta.TagEntity;
 import org.apache.gravitino.policy.AllValuesSelector;
 import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyAssociationSelector;
 import org.apache.gravitino.policy.PolicyContents;
 import org.apache.gravitino.policy.TagValueSelector;
 import org.apache.gravitino.rest.RESTUtils;
@@ -160,6 +161,12 @@ public class TestTagOperations extends BaseOperationsTest {
           operations.listMetadataObjectsForTag(metalake, name, null),
           operations.listPoliciesForTag(metalake, name, false),
           operations.addPolicyForTag(metalake, name, "policy", new 
PolicyTagAddRequest()),
+          operations.addPolicyForTag(
+              metalake,
+              name,
+              "policy",
+              new PolicyTagAddRequest(
+                  
PolicyAssociationSelectorDTO.fromSelector(TagValueSelector.of("finance")))),
           operations.removePolicyFromTag(metalake, name, "policy")
         }) {
       try (Response result = response) {
@@ -342,6 +349,66 @@ public class TestTagOperations extends BaseOperationsTest {
     }
   }
 
+  @ParameterizedTest
+  @ValueSource(strings = {"zzz", "A"})
+  void testAddPolicyForTagInvalidValue(String value) {
+    String message = "Tag tag1 value " + value + " is not in allowed values 
[a, b]";
+    doThrow(new IllegalArgumentException(message))
+        .when(tagManager)
+        .addPolicyForTag(metalake, "tag1", "policy1", 
TagValueSelector.of(value));
+    try (Response response = addPolicyForTag(TagValueSelector.of(value))) {
+      Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), 
response.getStatus());
+      ErrorResponse error = response.readEntity(ErrorResponse.class);
+      Assertions.assertEquals(ErrorConstants.ILLEGAL_ARGUMENTS_CODE, 
error.getCode());
+      Assertions.assertEquals(IllegalArgumentException.class.getSimpleName(), 
error.getType());
+      Assertions.assertTrue(error.getMessage().contains(message));
+    }
+    Mockito.verify(tagManager, Mockito.never()).getTag(Mockito.anyString(), 
Mockito.anyString());
+  }
+
+  @Test
+  void testAddPolicyForTagWithoutAllowedValues() {
+    doThrow(new IllegalArgumentException("Tag tag1 does not allow assignment 
values"))
+        .when(tagManager)
+        .addPolicyForTag(metalake, "tag1", "policy1", 
TagValueSelector.of("a"));
+    try (Response response = addPolicyForTag(TagValueSelector.of("a"))) {
+      Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), 
response.getStatus());
+      ErrorResponse error = response.readEntity(ErrorResponse.class);
+      Assertions.assertEquals(ErrorConstants.ILLEGAL_ARGUMENTS_CODE, 
error.getCode());
+      Assertions.assertEquals(IllegalArgumentException.class.getSimpleName(), 
error.getType());
+      Assertions.assertTrue(
+          error.getMessage().contains("Tag tag1 does not allow assignment 
values"));
+    }
+    Mockito.verify(tagManager, Mockito.never()).getTag(Mockito.anyString(), 
Mockito.anyString());
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"a", "b", "engineering"})
+  void testAddPolicyForTagValidSelector(String value) {
+    PolicyAssociationSelector selector = TagValueSelector.of(value);
+    try (Response response = addPolicyForTag(selector)) {
+      Assertions.assertEquals(Response.Status.OK.getStatusCode(), 
response.getStatus());
+      PolicyTagAssociationResponse association =
+          response.readEntity(PolicyTagAssociationResponse.class);
+      association.validate();
+      Assertions.assertEquals(selector, 
association.getSelector().toSelector());
+    }
+    Mockito.verify(tagManager).addPolicyForTag(metalake, "tag1", "policy1", 
selector);
+  }
+
+  @Test
+  void testAddPolicyForTagMissingTag() {
+    doThrow(new NoSuchTagException("Tag tag1 does not exist"))
+        .when(tagManager)
+        .addPolicyForTag(metalake, "tag1", "policy1", 
TagValueSelector.of("a"));
+    try (Response response = addPolicyForTag(TagValueSelector.of("a"))) {
+      Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), 
response.getStatus());
+      ErrorResponse error = response.readEntity(ErrorResponse.class);
+      Assertions.assertEquals(NoSuchTagException.class.getSimpleName(), 
error.getType());
+    }
+    Mockito.verify(tagManager, Mockito.never()).getTag(Mockito.anyString(), 
Mockito.anyString());
+  }
+
   @Test
   public void testListTagsInfo() {
     TagEntity tag1 =
@@ -1409,4 +1476,14 @@ public class TestTagOperations extends 
BaseOperationsTest {
   private String tagPath(String metalake) {
     return "/metalakes/" + metalake + "/tags";
   }
+
+  private Response addPolicyForTag(PolicyAssociationSelector selector) {
+    return target(tagPath(metalake) + "/tag1/policies/policy1")
+        .request(MediaType.APPLICATION_JSON_TYPE)
+        .accept("application/vnd.gravitino.v1+json")
+        .post(
+            Entity.entity(
+                new 
PolicyTagAddRequest(PolicyAssociationSelectorDTO.fromSelector(selector)),
+                MediaType.APPLICATION_JSON_TYPE));
+  }
 }

Reply via email to