yuqi1129 commented on code in PR #13957:
URL: https://github.com/apache/gravitino/pull/13957#discussion_r4608712452


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/PolicyMetaService.java:
##########
@@ -429,6 +450,66 @@ private void insertPolicyWithoutCommit(
     updatePolicyRootWithVersion(observedIdentifier, existingPolicyPO, 
replacementPolicyPO);
     insertPolicyVersionIfAllocated(existingPolicyPO, replacementPolicyPO);
     afterUpdate(storedPolicy);
+    return replacementPolicyPO.getPolicyId();
+  }
+
+  /**
+   * Brings the role references derived from a policy's content in line with 
that content.
+   *
+   * <p>The references are written only here and never by a caller, so {@code 
content} stays the one
+   * authority on which roles a policy names.
+   *
+   * <p>Only the difference is written: a reference the content still names 
keeps its row, so a
+   * policy edit that leaves {@code applicableRoles} alone writes no reference 
rows at all.
+   *
+   * <p>A reference the content drops is deleted rather than soft-deleted, so 
no edit leaves a
+   * tombstone behind. Removing a role, naming it again, and removing it once 
more therefore cannot
+   * collide on the table's uniqueness over (policy, role, deleted_at), which 
the two removals would
+   * otherwise share whenever they read the same millisecond from the database 
clock.
+   */
+  private void updateRoleRelationsWithoutCommit(long policyId, PolicyEntity 
policyEntity) {
+    List<PolicyRoleRelPO> desired = 
POConverters.initializePolicyRoleRelPOs(policyId, policyEntity);
+    List<PolicyRoleRelPO> current =
+        SessionUtils.getWithoutCommit(
+            PolicyRoleRelMapper.class, mapper -> 
mapper.listByPolicyId(policyId));
+
+    Set<String> desiredRoles =
+        
desired.stream().map(PolicyRoleRelPO::getRoleName).collect(Collectors.toSet());
+    Set<String> currentRoles =
+        
current.stream().map(PolicyRoleRelPO::getRoleName).collect(Collectors.toSet());
+
+    for (PolicyRoleRelPO superseded : current) {
+      if (desiredRoles.contains(superseded.getRoleName())) {
+        continue;
+      }
+      // A zero-row delete means the reference is already gone, which is the 
intended end state.
+      SessionUtils.doWithoutCommit(
+          PolicyRoleRelMapper.class, mapper -> 
mapper.deleteByIdAndVersion(superseded));
+    }
+
+    for (PolicyRoleRelPO added : desired) {
+      if (currentRoles.contains(added.getRoleName())) {
+        continue;
+      }
+      try {
+        SessionUtils.doWithoutCommit(PolicyRoleRelMapper.class, mapper -> 
mapper.insert(added));
+      } catch (RuntimeException re) {
+        // This table names roles exactly as the role table does, so a 
duplicate here is content
+        // naming one role twice under the backend's own equality: MySQL 
ignores trailing spaces,
+        // PostgreSQL does not, and each matches how that backend identifies a 
role. Report the
+        // role that collided instead of letting the caller's handler blame 
the policy name. The
+        // SQL failure is deliberately not chained: the handlers upstream look 
for a duplicate key
+        // through the cause chain and would rewrite this back into an 
already-existing policy.
+        if (ExceptionUtils.isDuplicateKey(re)) {
+          throw new IllegalArgumentException(

Review Comment:
   [Nit] Could we log the original exception, with the policy and role 
identifiers, before converting it?
   
   Avoiding a chained cause makes sense with the upstream duplicate-key 
classifier, but the SQLState, violated constraint, and original stack are now 
discarded entirely. PolicyManager passes this IllegalArgumentException through 
and the REST handler only logs the replacement, so there is no diagnostic 
record of the underlying failure. Logging re here would preserve that evidence 
without changing the client-facing error or reintroducing the 
policy-already-exists misclassification.
   
   Verified by tracing ExceptionUtils.checkSQLException, PolicyManager, and the 
REST PolicyExceptionHandler; no MySQL runtime reproduction is claimed.



##########
core/src/main/java/org/apache/gravitino/storage/relational/utils/POConverters.java:
##########
@@ -1637,6 +1641,39 @@ public static PolicyPO initializePolicyPOWithVersion(
     }
   }
 
+  /**
+   * Builds the role reference rows derived from a policy's content.
+   *
+   * <p>Only access control content names roles, so every other policy type 
yields no rows.

Review Comment:
   [Nit] Could we qualify the duplicate-collapse statement and mention the 
additional rejection in the PR's user-facing-change section?
   
   Exact duplicate strings collapse here, but names that differ as Java strings 
and compare equal in the backend do not. For example, content containing both 
"analyst" and "analyst " is rejected on MySQL by the new duplicate-key 
conversion, while exact repeats are accepted. The PR currently lists only the 
128-character limit as a user-facing behavior change.
   
   Matching role_meta equality is a reasonable choice; documenting this 
distinction would make that choice explicit. Evidence: the LinkedHashSet 
conversion, the schema, and testReferenceEqualityFollowsTheRoleTable. This 
round ran H2 only, not the MySQL branch.



##########
core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyRoleRelService.java:
##########
@@ -0,0 +1,462 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.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;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.PolicyEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContents;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.PolicyRoleRelMapper;
+import org.apache.gravitino.storage.relational.po.PolicyRoleRelPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Tests the policy-to-role references derived from access control policy 
content. */
+public class TestPolicyRoleRelService extends TestJDBCBackend {
+
+  private static final String METALAKE = "policy_role_relation_metalake";
+
+  @TestTemplate
+  public void testReferencesFollowPolicyContent() throws IOException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Arrays.asList("analyst", "auditor"));
+    backend.insert(policy, false);
+
+    Assertions.assertEquals(Arrays.asList("analyst", "auditor"), 
rolesOf(policy.id()));
+    Assertions.assertEquals(Collections.singletonList("reader"), 
policiesReferencing("analyst"));
+    Long auditorRowId = referenceTo(policy.id(), "auditor").getId();
+
+    backend.update(
+        policy.nameIdentifier(),
+        Entity.EntityType.POLICY,
+        entity -> withRoles(policy, Arrays.asList("auditor", "steward")));
+
+    Assertions.assertEquals(Arrays.asList("auditor", "steward"), 
rolesOf(policy.id()));
+    Assertions.assertEquals(Collections.emptyList(), 
policiesReferencing("analyst"));
+    // A reference the content still names is left alone rather than rewritten.
+    Assertions.assertEquals(auditorRowId, referenceTo(policy.id(), 
"auditor").getId());
+  }
+
+  @TestTemplate
+  public void testOverwriteAttachesReferencesToTheSurvivingPolicyRow() throws 
IOException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity original = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(original, false);
+
+    PolicyEntity replacement = accessControlPolicy("reader", 
Collections.singletonList("auditor"));
+    backend.insert(replacement, true);
+
+    // An overwrite keeps the row the name already pointed at, so the 
references follow that ID.
+    Assertions.assertEquals(Collections.singletonList("auditor"), 
rolesOf(original.id()));
+    Assertions.assertEquals(Collections.emptyList(), 
rolesOf(replacement.id()));
+    Assertions.assertEquals(Collections.singletonList("reader"), 
policiesReferencing("auditor"));
+    Assertions.assertEquals(Collections.emptyList(), 
policiesReferencing("analyst"));
+  }
+
+  @TestTemplate
+  public void testFailedPolicyWriteLeavesNoReferences() throws IOException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(policy, false);
+
+    PolicyEntity duplicate = accessControlPolicy("reader", 
Collections.singletonList("steward"));
+    Assertions.assertThrows(
+        EntityAlreadyExistsException.class, () -> backend.insert(duplicate, 
false));
+
+    Assertions.assertEquals(Collections.emptyList(), 
policiesReferencing("steward"));
+    Assertions.assertEquals(Collections.singletonList("reader"), 
policiesReferencing("analyst"));
+  }
+
+  @TestTemplate
+  public void testFailedReferenceWriteRollsBackThePolicy() throws IOException, 
SQLException {
+    createAndInsertMakeLake(METALAKE);
+    String oversizedRoleName = "r".repeat(129);
+    PolicyEntity policy =
+        accessControlPolicy("reader", 
Collections.singletonList(oversizedRoleName));
+
+    Assertions.assertThrows(RuntimeException.class, () -> 
backend.insert(policy, false));
+
+    Assertions.assertEquals(
+        0L, count("SELECT COUNT(*) FROM policy_meta WHERE policy_id = ?", 
policy.id()));
+    Assertions.assertEquals(
+        0L, count("SELECT COUNT(*) FROM policy_version_info WHERE policy_id = 
?", policy.id()));
+    Assertions.assertEquals(
+        0L,
+        count("SELECT COUNT(*) FROM policy_role_relation_meta WHERE policy_id 
= ?", policy.id()));
+  }
+
+  @TestTemplate
+  public void testDuplicateRoleNamesCollapseToOneReference() throws 
IOException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Arrays.asList("analyst", "analyst"));
+    backend.insert(policy, false);
+
+    Assertions.assertEquals(Collections.singletonList("analyst"), 
rolesOf(policy.id()));
+  }
+
+  @TestTemplate
+  public void testReferenceEqualityFollowsTheRoleTable() throws IOException, 
SQLException {
+    createAndInsertMakeLake(METALAKE);
+    CatalogEntity catalog = createAndInsertCatalog(METALAKE, 
"policy_role_equality_catalog");
+
+    // Ask the authoritative table whether these two names are one role or 
two, rather than
+    // assuming: MySQL compares role names ignoring trailing spaces, 
PostgreSQL and H2 do not.
+    backend.insert(role(catalog, "analyst"), false);
+    boolean roleTableSeesTwoRoles;
+    try {
+      backend.insert(role(catalog, "analyst "), false);
+      roleTableSeesTwoRoles = true;
+    } catch (EntityAlreadyExistsException sameRoleTwice) {
+      roleTableSeesTwoRoles = false;
+    }
+
+    PolicyEntity policy = accessControlPolicy("reader", 
Arrays.asList("analyst", "analyst "));
+    if (roleTableSeesTwoRoles) {
+      backend.insert(policy, false);
+      Assertions.assertEquals(Arrays.asList("analyst", "analyst "), 
rolesOf(policy.id()));
+    } else {
+      // One role named twice. The write fails against the role that collided, 
not the policy name.
+      IllegalArgumentException failure =
+          Assertions.assertThrows(
+              IllegalArgumentException.class, () -> backend.insert(policy, 
false));
+      Assertions.assertTrue(failure.getMessage().contains("analyst"), 
failure.getMessage());
+      Assertions.assertEquals(0L, activeReferenceCount(policy.id()));
+    }
+  }
+
+  @TestTemplate
+  public void testPolicyWithoutAccessControlContentReferencesNoRoles() throws 
IOException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy =
+        createPolicy(
+            RandomIdGenerator.INSTANCE.nextId(),
+            NamespaceUtil.ofPolicy(METALAKE),
+            "compaction",
+            AUDIT_INFO);
+    backend.insert(policy, false);
+
+    Assertions.assertEquals(Collections.emptyList(), rolesOf(policy.id()));
+  }
+
+  @TestTemplate
+  public void testPolicyDeleteClearsReferences() throws IOException, 
SQLException {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(policy, false);
+
+    Assertions.assertTrue(backend.delete(policy.nameIdentifier(), 
Entity.EntityType.POLICY, false));
+
+    Assertions.assertEquals(0L, activeReferenceCount(policy.id()));
+  }
+
+  @TestTemplate
+  public void testMetalakeDeleteClearsOnlyItsOwnReferences() throws 
IOException, SQLException {
+    createAndInsertMakeLake(METALAKE);
+    String otherMetalake = METALAKE + "_other";
+    createAndInsertMakeLake(otherMetalake);
+
+    PolicyEntity policy = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(policy, false);
+    PolicyEntity otherPolicy =
+        PolicyEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withNamespace(NamespaceUtil.ofPolicy(otherMetalake))
+            .withName("reader")
+            .withPolicyType(Policy.BuiltInType.ACCESS_CONTROL)
+            .withComment("")
+            .withEnabled(true)
+            .withContent(
+                PolicyContents.accessControl(
+                    Collections.singletonList(Privilege.Name.SELECT_TABLE),
+                    Collections.singletonList("analyst")))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    backend.insert(otherPolicy, false);
+
+    Assertions.assertTrue(
+        backend.delete(NameIdentifier.of(METALAKE), 
Entity.EntityType.METALAKE, true));
+
+    Assertions.assertEquals(0L, activeReferenceCount(policy.id()));
+    Assertions.assertEquals(1L, activeReferenceCount(otherPolicy.id()));
+  }
+
+  @TestTemplate
+  public void testMetalakeDeleteClearsReferencesOfAnInFlightPolicyUpdate() 
throws Exception {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(policy, false);
+
+    AtomicReference<Throwable> deleteFailure = new AtomicReference<>();
+    Thread deleter =
+        new Thread(
+            () -> {
+              try {
+                backend.delete(NameIdentifier.of(METALAKE), 
Entity.EntityType.METALAKE, true);
+              } catch (Throwable t) {
+                deleteFailure.set(t);
+              }
+            });
+
+    // Stand in for a policy update that holds the policy row and adds a 
reference mid-delete.
+    try (SqlSession sqlSession =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(false);
+        Connection updater = sqlSession.getConnection()) {
+      updater.setAutoCommit(false);
+      updater.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+      try (PreparedStatement lock =
+          updater.prepareStatement(
+              "SELECT policy_id FROM policy_meta WHERE policy_id = ? FOR 
UPDATE")) {
+        lock.setLong(1, policy.id());
+        lock.executeQuery().close();
+      }
+
+      deleter.start();
+      // Only the policy lives in this metalake, so the delete reaches its row 
almost at once and
+      // the lock above is the one thing that can hold it up. Adding other 
entities here would
+      // slow that down and make this wait too short.
+      Thread.sleep(400);
+      Assertions.assertTrue(deleter.isAlive(), "The metalake delete should not 
have finished yet");
+
+      try (PreparedStatement insert =
+          updater.prepareStatement(
+              "INSERT INTO policy_role_relation_meta"
+                  + " (policy_id, role_name, current_version, last_version, 
deleted_at)"
+                  + " VALUES (?, 'auditor', 1, 1, 0)")) {
+        insert.setLong(1, policy.id());
+        insert.executeUpdate();
+      }
+      updater.commit();
+    }
+
+    deleter.join(30_000);
+    Assertions.assertFalse(deleter.isAlive());
+    Assertions.assertNull(deleteFailure.get());
+    Assertions.assertEquals(0L, activeReferenceCount(policy.id()));
+  }
+
+  @TestTemplate
+  public void 
testNonCascadeMetalakeDeleteClearsReferencesOfAnInFlightPolicyUpdate()
+      throws Exception {
+    createAndInsertMakeLake(METALAKE);
+    PolicyEntity policy = accessControlPolicy("reader", 
Collections.singletonList("analyst"));
+    backend.insert(policy, false);
+
+    AtomicReference<Throwable> deleteFailure = new AtomicReference<>();
+
+    // The updater callback runs before the write transaction opens, so 
finishing the delete here
+    // stands in for an update that read the policy before the metalake went 
away and commits
+    // after. The delete soft-deletes the policy row before the references, so 
this update can no
+    // longer write one: its own policy row is gone by the time it reaches the 
reference writes.
+    Assertions.assertThrows(
+        NoSuchEntityException.class,
+        () ->
+            backend.update(
+                policy.nameIdentifier(),
+                Entity.EntityType.POLICY,
+                entity -> {
+                  deleteMetalakeWithoutCascade(deleteFailure);

Review Comment:
   [Important] Could we make this regression test exercise an update that 
already holds the policy row while deletion waits for it?
   
   Here the updater callback waits for the entire metalake deletion to finish 
before the update transaction starts. Reordering reference cleanup before 
policy deletion therefore still leaves the policy deleted when the update 
resumes, so the test cannot detect the ordering regression this PR fixes.
   
   I verified this on H2 by moving only the non-cascade reference cleanup back 
before softDeletePolicyMetasByMetalakeId: 
testNonCascadeMetalakeDeleteClearsReferencesOfAnInFlightPolicyUpdate still 
passed.
   
   Please synchronize both deletion variants at the policy UPDATE/lock wait, 
then let the holding transaction add a reference and commit. The cascade test's 
sleep(400) and isAlive() have a related gap: a delayed deleter can still be 
alive without having reached that statement. Both tests should reliably fail 
when their cleanup order is reversed. The current production order looks 
correct; this finding concerns regression protection. MySQL/PostgreSQL mutation 
checks were not run locally.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to