You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polaris.apache.org by yu...@apache.org on 2026/09/21 17:21:01 UTC

(polaris) branch main updated: fix: return 404 instead of 500 when detaching a policy that is not attached (#5568)

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

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


The following commit(s) were added to refs/heads/main by this push:
     new d66f916b5a fix: return 404 instead of 500 when detaching a policy that is not attached (#5568)
d66f916b5a is described below

commit d66f916b5a4570c98a08ee7062fc31057bfb676c
Author: youngrae81 <16...@users.noreply.github.com>
AuthorDate: Tue Sep 22 02:20:55 2026 +0900

    fix: return 404 instead of 500 when detaching a policy that is not attached (#5568)
---
 CHANGELOG.md                                       |  3 ++
 .../test/PolarisPolicyServiceIntegrationTest.java  | 29 +++++++++++++++++
 .../nosql/metastore/mutation/PolicyMutation.java   | 28 ++++++++--------
 .../policy/exceptions/NoSuchMappingException.java  | 37 ++++++++++++++++++++++
 .../persistence/PolarisTestMetaStoreManager.java   |  8 +++++
 .../service/catalog/policy/PolicyCatalog.java      | 14 +++++---
 .../catalog/policy/AbstractPolicyCatalogTest.java  | 15 +++++++++
 .../service/exception/ExceptionMapperTest.java     |  2 ++
 8 files changed, 117 insertions(+), 19 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a5a8a9e46..1a5d4d7f83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -134,6 +134,9 @@ request adding CHANGELOG notes for breaking (!) changes and possibly other secti
 
 ### Fixes
 
+- Policy API: detaching a policy from a target it was never attached to now returns
+  `404 Not Found` with error type `NoSuchMappingException`, as the policy API specification
+  requires, instead of `500 Internal Server Error`.
 - OPA authorizer HTTP client creation no longer silently falls back to a default client when
   truststore or SSL setup fails. Misconfiguration (for example a bad truststore path) now fails
   startup instead of continuing with system trust and no configured response timeout.
diff --git a/integration-tests/src/main/java/org/apache/polaris/service/it/test/PolarisPolicyServiceIntegrationTest.java b/integration-tests/src/main/java/org/apache/polaris/service/it/test/PolarisPolicyServiceIntegrationTest.java
index a9d1a15abb..ba601e7a26 100644
--- a/integration-tests/src/main/java/org/apache/polaris/service/it/test/PolarisPolicyServiceIntegrationTest.java
+++ b/integration-tests/src/main/java/org/apache/polaris/service/it/test/PolarisPolicyServiceIntegrationTest.java
@@ -449,6 +449,35 @@ public class PolarisPolicyServiceIntegrationTest {
     policyApi.dropPolicy(currentCatalogName, NS1_P1);
   }
 
+  @Test
+  public void testDetachPolicyWithoutMapping() {
+    restCatalog.createNamespace(NS1);
+    policyApi.createPolicy(
+        currentCatalogName,
+        NS1_P1,
+        PredefinedPolicyTypes.DATA_COMPACTION,
+        EXAMPLE_TABLE_MAINTENANCE_POLICY_CONTENT,
+        "test policy");
+    // The policy and the target both exist, but the policy was never attached to the target.
+    var namespaceTarget =
+        new PolicyAttachmentTarget(
+            PolicyAttachmentTarget.TypeEnum.NAMESPACE, List.of(NS1.levels()));
+
+    DetachPolicyRequest request = DetachPolicyRequest.builder().setTarget(namespaceTarget).build();
+    try (Response res =
+        policyApi
+            .request(
+                "polaris/v1/{cat}/namespaces/{ns}/policies/{policy-name}/mappings",
+                Map.of("cat", currentCatalogName, "ns", NS1_NAME, "policy-name", NS1_P1.name()))
+            .post(Entity.json(request))) {
+      Assertions.assertThat(res.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
+      Assertions.assertThat(res.readEntity(String.class))
+          .contains("NoSuchMappingException")
+          .contains("The given mapping between policy");
+    }
+    policyApi.dropPolicy(currentCatalogName, NS1_P1);
+  }
+
   @Test
   public void testDropPolicy() {
     restCatalog.createNamespace(NS1);
diff --git a/persistence/nosql/persistence/metastore/src/main/java/org/apache/polaris/persistence/nosql/metastore/mutation/PolicyMutation.java b/persistence/nosql/persistence/metastore/src/main/java/org/apache/polaris/persistence/nosql/metastore/mutation/PolicyMutation.java
index ec2ff1bebf..0daf62d868 100644
--- a/persistence/nosql/persistence/metastore/src/main/java/org/apache/polaris/persistence/nosql/metastore/mutation/PolicyMutation.java
+++ b/persistence/nosql/persistence/metastore/src/main/java/org/apache/polaris/persistence/nosql/metastore/mutation/PolicyMutation.java
@@ -20,6 +20,7 @@
 package org.apache.polaris.persistence.nosql.metastore.mutation;
 
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.ENTITY_NOT_FOUND;
+import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.POLICY_MAPPING_NOT_FOUND;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.POLICY_MAPPING_OF_SAME_TYPE_ALREADY_EXISTS;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.UNEXPECTED_ERROR_SIGNALED;
 import static org.apache.polaris.persistence.nosql.coretypes.realm.PolicyMapping.POLICY_MAPPING_SERIALIZER;
@@ -27,7 +28,6 @@ import static org.apache.polaris.persistence.nosql.coretypes.realm.PolicyMapping
 import static org.apache.polaris.persistence.nosql.coretypes.realm.PolicyMappingsObj.PolicyMappingKey.fromIndexKey;
 
 import java.util.Map;
-import org.apache.polaris.core.persistence.dao.entity.BaseResult;
 import org.apache.polaris.core.persistence.dao.entity.PolicyAttachmentResult;
 import org.apache.polaris.core.policy.PolarisPolicyMappingRecord;
 import org.apache.polaris.core.policy.PolicyType;
@@ -92,9 +92,7 @@ public record PolicyMutation(
 
                 var policyOptional = policyCatalogAccess.byId(policyId);
                 if (policyOptional.isEmpty()) {
-                  return state.noCommit(
-                      new PolicyAttachmentResult(
-                          BaseResult.ReturnStatus.POLICY_MAPPING_NOT_FOUND, null));
+                  return state.noCommit(new PolicyAttachmentResult(POLICY_MAPPING_NOT_FOUND, null));
                 }
                 if (targetCatalogId != 0L && targetCatalogId != targetId) {
                   // catalog content, check whether the entity exists
@@ -126,7 +124,6 @@ public record PolicyMutation(
                     new PolicyMappingsObj.KeyByEntity(
                         targetCatalogId, targetId, policyType.getCode(), policyCatalogId, policyId);
 
-                var changed = false;
                 if (doAttach) {
                   if (policyType.isInheritable()) {
                     // The contract says that at max one policy of the same inheritable policy type
@@ -163,19 +160,20 @@ public record PolicyMutation(
                   // note: parameters are only added to the "by entity" entry
                   index.put(keyByPolicy.toIndexKey(), PolicyMapping.EMPTY);
                   index.put(keyByEntity.toIndexKey(), policyMapping);
-                  changed = true;
                 } else {
-                  changed |= index.remove(keyByPolicy.toIndexKey());
-                  changed |= index.remove(keyByEntity.toIndexKey());
+                  var removedByPolicy = index.remove(keyByPolicy.toIndexKey());
+                  var removedByEntity = index.remove(keyByEntity.toIndexKey());
+                  if (!removedByPolicy && !removedByEntity) {
+                    // Nothing to detach: the policy was never attached to this target.
+                    return state.noCommit(
+                        new PolicyAttachmentResult(POLICY_MAPPING_NOT_FOUND, null));
+                  }
                 }
 
-                if (changed) {
-                  // Replacing this inline index leaves older mapping objects and stripes stale
-                  // until a later maintenance purge.
-                  builder.policyMappings(index.toIndexed("mappings", state::writeOrReplace));
-                  return state.commitResult(result, builder, refObj);
-                }
-                return state.noCommit(result);
+                // Replacing this inline index leaves older mapping objects and stripes stale
+                // until a later maintenance purge.
+                builder.policyMappings(index.toIndexed("mappings", state::writeOrReplace));
+                return state.commitResult(result, builder, refObj);
               })
           .orElseThrow();
     } finally {
diff --git a/polaris-core/src/main/java/org/apache/polaris/core/policy/exceptions/NoSuchMappingException.java b/polaris-core/src/main/java/org/apache/polaris/core/policy/exceptions/NoSuchMappingException.java
new file mode 100644
index 0000000000..59e81baa01
--- /dev/null
+++ b/polaris-core/src/main/java/org/apache/polaris/core/policy/exceptions/NoSuchMappingException.java
@@ -0,0 +1,37 @@
+/*
+ * 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.polaris.core.policy.exceptions;
+
+import com.google.errorprone.annotations.FormatMethod;
+import jakarta.ws.rs.core.Response;
+import org.apache.polaris.core.exceptions.PolarisException;
+
+/** Thrown when the mapping between a policy and a target entity does not exist. */
+public class NoSuchMappingException extends PolarisException {
+
+  @FormatMethod
+  public NoSuchMappingException(String message, Object... args) {
+    super(String.format(message, args));
+  }
+
+  @Override
+  public int httpStatusCode() {
+    return Response.Status.NOT_FOUND.getStatusCode();
+  }
+}
diff --git a/polaris-core/src/testFixtures/java/org/apache/polaris/core/persistence/PolarisTestMetaStoreManager.java b/polaris-core/src/testFixtures/java/org/apache/polaris/core/persistence/PolarisTestMetaStoreManager.java
index e3f329d6c0..c8f0d9b6c0 100644
--- a/polaris-core/src/testFixtures/java/org/apache/polaris/core/persistence/PolarisTestMetaStoreManager.java
+++ b/polaris-core/src/testFixtures/java/org/apache/polaris/core/persistence/PolarisTestMetaStoreManager.java
@@ -3368,6 +3368,14 @@ public class PolarisTestMetaStoreManager {
 
     detachPolicyFromTarget(List.of(catalog, N1, N1_N2), N1_N2_T1, List.of(catalog, N1), N1_P1);
     detachPolicyFromTarget(List.of(catalog, N1, N1_N2), N1_N2_T1, List.of(catalog, N5), N5_P3);
+
+    // detaching a policy that is not attached to the target must report the missing mapping
+    PolicyAttachmentResult detachResult =
+        polarisMetaStoreManager.detachPolicyFromEntity(
+            polarisCallContext, List.of(catalog, N1, N1_N2), N1_N2_T1, List.of(catalog, N1), N1_P1);
+    Assertions.assertThat(detachResult.isSuccess()).isFalse();
+    Assertions.assertThat(detachResult.getReturnStatus())
+        .isEqualTo(BaseResult.ReturnStatus.POLICY_MAPPING_NOT_FOUND);
   }
 
   void testPolicyMappingCleanup() {
diff --git a/runtime/service/src/main/java/org/apache/polaris/service/catalog/policy/PolicyCatalog.java b/runtime/service/src/main/java/org/apache/polaris/service/catalog/policy/PolicyCatalog.java
index 5955088ede..45a9bb997d 100644
--- a/runtime/service/src/main/java/org/apache/polaris/service/catalog/policy/PolicyCatalog.java
+++ b/runtime/service/src/main/java/org/apache/polaris/service/catalog/policy/PolicyCatalog.java
@@ -21,6 +21,7 @@ package org.apache.polaris.service.catalog.policy;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.CATALOG_PATH_CANNOT_BE_RESOLVED;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.ENTITY_NOT_FOUND;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.POLICY_HAS_MAPPINGS;
+import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.POLICY_MAPPING_NOT_FOUND;
 import static org.apache.polaris.core.persistence.dao.entity.BaseResult.ReturnStatus.POLICY_MAPPING_OF_SAME_TYPE_ALREADY_EXISTS;
 import static org.apache.polaris.service.catalog.common.ExceptionUtils.noSuchNamespaceException;
 import static org.apache.polaris.service.catalog.common.ExceptionUtils.notFoundExceptionForTableLikeEntity;
@@ -58,6 +59,7 @@ import org.apache.polaris.core.persistence.resolver.PolarisResolutionManifestCat
 import org.apache.polaris.core.persistence.resolver.ResolvedPathKey;
 import org.apache.polaris.core.policy.PolicyEntity;
 import org.apache.polaris.core.policy.PolicyType;
+import org.apache.polaris.core.policy.exceptions.NoSuchMappingException;
 import org.apache.polaris.core.policy.exceptions.NoSuchPolicyException;
 import org.apache.polaris.core.policy.exceptions.PolicyAttachException;
 import org.apache.polaris.core.policy.exceptions.PolicyInUseException;
@@ -346,13 +348,17 @@ public class PolicyCatalog {
             policyEntity);
 
     if (!result.isSuccess()) {
+      var targetId = getIdentifier(target);
+      if (result.getReturnStatus() == POLICY_MAPPING_NOT_FOUND) {
+        throw new NoSuchMappingException(
+            "The given mapping between policy %s and %s does not exist",
+            policyIdentifier, targetId);
+      }
+
       throw new IllegalStateException(
           String.format(
               "Failed to detach policy %s from %s error status: %s with extraInfo: %s",
-              policyIdentifier,
-              getIdentifier(target),
-              result.getReturnStatus(),
-              result.getExtraInformation()));
+              policyIdentifier, targetId, result.getReturnStatus(), result.getExtraInformation()));
     }
 
     return true;
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/catalog/policy/AbstractPolicyCatalogTest.java b/runtime/service/src/test/java/org/apache/polaris/service/catalog/policy/AbstractPolicyCatalogTest.java
index 42641e0bb6..18d706eae1 100644
--- a/runtime/service/src/test/java/org/apache/polaris/service/catalog/policy/AbstractPolicyCatalogTest.java
+++ b/runtime/service/src/test/java/org/apache/polaris/service/catalog/policy/AbstractPolicyCatalogTest.java
@@ -68,6 +68,7 @@ import org.apache.polaris.core.persistence.dao.entity.EntityResult;
 import org.apache.polaris.core.persistence.resolver.ResolutionManifestFactory;
 import org.apache.polaris.core.persistence.resolver.ResolverFactory;
 import org.apache.polaris.core.policy.PredefinedPolicyTypes;
+import org.apache.polaris.core.policy.exceptions.NoSuchMappingException;
 import org.apache.polaris.core.policy.exceptions.NoSuchPolicyException;
 import org.apache.polaris.core.policy.exceptions.PolicyInUseException;
 import org.apache.polaris.core.policy.exceptions.PolicyVersionMismatchException;
@@ -582,6 +583,20 @@ public abstract class AbstractPolicyCatalogTest {
     assertThat(policyCatalog.getApplicablePolicies(NS, null, null).size()).isEqualTo(0);
   }
 
+  @Test
+  public void testDetachPolicyWithoutMapping() {
+    icebergCatalog.createNamespace(NS);
+    policyCatalog.createPolicy(POLICY1, DATA_COMPACTION.getName(), "test", "{\"enable\": false}");
+
+    // The policy and the target both exist, but the policy was never attached to the target.
+    assertThatThrownBy(() -> policyCatalog.detachPolicy(POLICY1, POLICY_ATTACH_TARGET_NS))
+        .isInstanceOf(NoSuchMappingException.class)
+        .hasMessage(
+            String.format(
+                "The given mapping between policy %s and %s does not exist",
+                POLICY1, CATALOG_NAME + "." + String.join(".", NS.levels())));
+  }
+
   @Test
   public void testPolicyOverwrite() {
     icebergCatalog.createNamespace(NS);
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/exception/ExceptionMapperTest.java b/runtime/service/src/test/java/org/apache/polaris/service/exception/ExceptionMapperTest.java
index b642190b2c..428f2f96eb 100644
--- a/runtime/service/src/test/java/org/apache/polaris/service/exception/ExceptionMapperTest.java
+++ b/runtime/service/src/test/java/org/apache/polaris/service/exception/ExceptionMapperTest.java
@@ -45,6 +45,7 @@ import org.apache.polaris.core.exceptions.FileIOUnknownHostException;
 import org.apache.polaris.core.exceptions.PolarisException;
 import org.apache.polaris.core.exceptions.PolarisServiceUnavailableException;
 import org.apache.polaris.core.persistence.PolicyMappingAlreadyExistsException;
+import org.apache.polaris.core.policy.exceptions.NoSuchMappingException;
 import org.apache.polaris.core.policy.exceptions.NoSuchPolicyException;
 import org.apache.polaris.core.policy.exceptions.PolicyAttachException;
 import org.apache.polaris.core.policy.exceptions.PolicyInUseException;
@@ -181,6 +182,7 @@ public class ExceptionMapperTest {
         Arguments.of(new PolicyAttachException("msg"), 400),
         Arguments.of(new PolicyInUseException("msg"), 400),
         Arguments.of(new NoSuchPolicyException("msg"), 404),
+        Arguments.of(new NoSuchMappingException("msg"), 404),
         Arguments.of(new PolicyVersionMismatchException("msg"), 409),
         Arguments.of(new PolicyMappingAlreadyExistsException("msg"), 409),
         Arguments.of(new NoSuchSemanticModelException("msg"), 404),