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 42b42eeec6 [#13612] fix(authorization): Coalesce concurrent role 
policy loads (#14045)
42b42eeec6 is described below

commit 42b42eeec62184f272cca91dddae33a767538d96
Author: autoCAT <[email protected]>
AuthorDate: Thu Nov 12 18:03:05 2026 -0800

    [#13612] fix(authorization): Coalesce concurrent role policy loads (#14045)
    
    ### What changes were proposed in this pull request?
    
    Coalesce role-policy reloads across requests for the same role version
    and clear generation. Each request completes all loads it owns before
    waiting for other requests, preserving batch reads without introducing
    overlapping-batch deadlocks. Each role completes its own outcome, so a
    failed role cannot fail waiters that only need healthy roles. Failed
    loads reach their corresponding waiters, completed flights are removed,
    and interrupting a waiter does not cancel shared work.
    
    Keep a bounded active-call version floor so a late older load cannot
    overwrite a newer partial policy state while the newer call is still
    active or within its partial-load backoff. The floor is removed when all
    participating calls finish; it is not a persistent version watermark.
    After the backoff expires (or immediately after an unreadable load,
    which has no backoff), a caller delayed before retaining its floor can
    still publish an older probed version. A later request probing the newer
    version reloads it, as on main. Reject obsolete results explicitly when
    no complete current replacement exists. Clear-generation snapshots and
    publication checks also prevent a pre-invalidation load from
    republishing cleared policies.
    
    Two read-path details also change. Roles missing from a nonempty batch
    read are now read one by one instead of being skipped. A role dropped
    before that read has the policies of its previous load cleared, and a
    role read by name whose id differs from the probed id, because it was
    dropped and recreated, now fails the request closed and is logged,
    instead of being skipped. Each request captures clear generations and
    retains version floors in a single critical section. A load discarded
    because a newer version was observed without a complete load (still
    loading, partial or unreadable) is logged.
    
    Accepted correctness trade-off: a request loading an older version fails
    closed when a newer version has been observed without a complete
    replacement. This prevents the old snapshot from overwriting newer
    partial or unreadable state. A later request joins the newer load while
    it runs, uses its partial result during the existing retry backoff, or
    retries an unreadable load. Shared waits have no separate timeout: they
    depend on the owner's completion, including DB pool `maxWaitMillis` and
    query execution time (and query timeouts, if configured). A stuck owner
    can delay all requests waiting on its roles; interrupting one waiter
    still leaves the shared load running.
    
    Shared loads reuse the owner's request context, including any catalog
    normalization failure remembered earlier in that request. A transient
    failure can therefore become a shared partial load; unresolved DENY
    objects install catalog-level deny guards. All requests reuse this
    fail-closed state during the existing partial-load backoff (at most 10
    seconds), unless invalidated. Before coalescing, another request could
    replace that partial load immediately using its own context. Retaining
    the owner context preserves request-local lookup deduplication, at the
    cost of temporarily extending that request's normalization failure to
    other requests.
    
    Represent publication outcomes with a private `RolePolicyPublication`
    enum (`APPLIED`, `SKIPPED`, `UNREADABLE`), removing the mutable output
    parameter. Skipped publications still rely on the existing
    clear-generation revalidation.
    
    Add deterministic concurrency regressions and an H2/MyBatis fixture that
    exercises public authorization with separate request contexts and
    persisted role entities, including privilege revocation.
    
    ### Why are the changes needed?
    
    Concurrent requests currently duplicate role entity reads and metadata
    resolution after cache eviction or privilege changes. Serializing the
    final policy replacement alone does not coalesce that work. A
    complete-load marker also cannot protect a newer partial load from an
    older in-progress result.
    
    Fixes #13612
    
    ### Does this PR introduce _any_ user-facing change?
    
    Role reloads share work across requests while retaining request-local
    role membership. At larger policy counts, the H2 storm benchmark below
    shows higher throughput and lower p50 and role-read load, with worse p99
    and maximum latency. Fail-closed checks can temporarily deny an
    otherwise granted catalog during concurrent policy changes or repeated
    invalidation. No public API or configuration changes.
    
    ### How was this patch tested?
    
    Documentation follow-up at `0792ac7f1b`: clarified shared
    normalization-failure propagation and the active-call version floor's
    lifetime in comments and this description. No runtime behavior changes.
    All 119 `TestJcasbinAuthorizer` cases and both targeted H2
    `TestJcasbinRoleSingleFlightH2` cases passed on JDK 17; server-common
    Spotless passed. The full core suite was not run.
    
    Latest synchronization at `f7b8e08283`: merged upstream `main` at
    `3a6c706dd9` and resolved the `EnumSource` import conflict in
    `TestJcasbinAuthorizer`. Preserved the role-load coalescing changes and
    upstream incomplete-policy DENY tracking. All 224 targeted server-common
    authorization cases (including 131 `TestJcasbinAuthorizer` cases) and
    both H2 `TestJcasbinRoleSingleFlightH2` cases passed on JDK 17; Spotless
    passed. No full core suite was run.
    
    Validation of the follow-up fix at `248dd9e762`:
    
    ```sh
    ./gradlew :server-common:spotlessApply :server-common:test :core:coreH2Test 
\
      --tests org.apache.gravitino.authorization.TestJcasbinRoleSingleFlightH2 \
      -PskipITs -PskipWeb=true -PskipTrinoConnector=true \
      --no-daemon --no-parallel --max-workers=2 --console=plain
    ```
    
    * `server-common`: 556 tests executed; 555 passed. The unchanged
    `testMutualTlsRejectsMissingClientCertificate` failed because the JDK
    reported an `IOException` rather than the expected handshake exception.
    This also reproduced before the fix; its isolated rerun passed without
    changing that test.
    * All 116 Jcasbin authorizer cases passed, including four new cases
    covering failure before/after the healthy role and both
    `RuntimeException` and `Error`.
    * The two targeted H2/MyBatis public-authorization tests passed. The
    full core suite was not run for this follow-up.
    * Mutation check: reverting only the production fix made all four new
    cases fail; restoring it made them pass. The regression also checks that
    the owner retains one batch read and releases flight/version state.
    * Spotless checks and a fresh-context independent review passed.
    
    Follow-ups at `b01caa5f38` and `2241d7ee86` (batched retention,
    superseded and recreated-role logging, delayed-owner, dropped-role and
    recreated-role regressions): `TestJcasbinAuthorizer` 119 and
    `TestJcasbinRoleSingleFlightH2` 2 passed. Removing the post-claim marker
    recheck, the id check or the dropped-role invalidation fails
    `testDelayedOwnerRechecksMarkerAfterPreviousLoadFinished`,
    `testRoleRecreatedUnderSameNameFailsClosed` or
    `testRoleDroppedBeforeFallbackReadClearsItsPolicies` respectively.
    
    Review follow-up at `c8b2be6e7b`: all 119 `TestJcasbinAuthorizer` cases
    and both `TestJcasbinRoleSingleFlightH2` tests passed on JDK 17. The
    existing regressions cover applied and skipped publications, generation
    changes, superseded partial/unreadable versions, mixed-role failure
    isolation and interrupted waiters. Spotless passed. This refactor
    preserves the batching and version-floor protocol.
    
    ```sh
    ./gradlew :server-common:spotlessApply :server-common:test \
      --tests 
org.apache.gravitino.server.authorization.jcasbin.TestJcasbinAuthorizer \
      :core:coreH2Test \
      --tests org.apache.gravitino.authorization.TestJcasbinRoleSingleFlightH2 \
      -PskipITs -PskipWeb=true -PskipTrinoConnector=true \
      --no-daemon --no-parallel --max-workers=2 --console=plain
    ```
    
    Small-policy throughput benchmark (temporary H2/MyBatis harness, not
    committed): 32 threads authorize with a fresh request context each, for
    one user with 16 roles over 8 catalogs, while every loaded-role marker
    is invalidated periodically. 12-second runs on 10 cores, steady rounds:
    
    | Invalidation | Version | ops/s | p99 | Fail-closed denials | Role
    entities read |
    | ------------ | ------- | ----- | --- | ------------------- |
    ------------------ |
    | none | main | 6556–6867 | 34–47 ms | 0 | 0 |
    | none | this PR | 6522–6830 | 36–42 ms | 0 | 0 |
    | every 200 ms | main | 3936–4105 | 123 ms | 0 | ~27,000 |
    | every 200 ms | this PR | 6260–6422 | 44–49 ms | 0 | ~1,040 |
    | every 50 ms | main | 2523–2882 | 136–146 ms | 58–59 | ~38,000 |
    | every 50 ms | this PR | 5784–5920 | 49–63 ms | 0–4 | ~3,700 |
    | every 10 ms | main | 1239–1312 | 184–187 ms | 934–1045 | ~50,000 |
    | every 10 ms | this PR | 4305–4353 | 65–77 ms | 318–330 | ~11,700 |
    
    The steady-state path takes no new lock; its differences are within
    run-to-run noise. The added write locks are only taken by requests with
    stale roles. The p99 improvement above applies to this small-policy
    setup.
    
    Larger-scale H2 benchmark [run by
    
@yuqi1129](https://github.com/apache/gravitino/pull/14045#pullrequestreview-5698770618):
    32 threads, 10-core laptop, each request checks `USE_CATALOG` on a
    granted catalog. Case A has 200 users, 400 roles, 20 roles per user and
    20 objects per role (8,000 allow rows). Case B has 100 users, 100 roles,
    10 roles per user and 200 objects per role (20,000 allow rows). A
    background thread invalidates all loaded-role markers every 500 ms or
    100 ms. Runs alternated PR, base, PR, base in one worktree; paired
    values are reported as in the review, with about ±25% run-to-run drift.
    
    | Case | Version | ops/s | p50 | p99 | max | Role entities read |
    | ---- | ------- | ----- | --- | --- | --- | ------------------ |
    | A | base | 265 / 324 | 119 / 97 ms | 286 / 234 ms | 481 / 436 ms | 192
    / 249 |
    | A | this PR | 310 / 344 | 85 / 79 ms | 443 / 372 ms | 884 / 723 ms |
    121 / 147 |
    | B | base | 103 / 142 | 294 / 221 ms | 822 / 600 ms | 1.3 / 0.9 s | 153
    / 194 |
    | B | this PR | 137 / 156 | 174 / 158 ms | 975 / 835 ms | 1.7 / 1.5 s |
    65 / 88 |
    
    Steady-state performance showed no regression in that review. Under
    reload storms, coalescing improved throughput, p50 and role-read load,
    but increased p99 and maximum latency: all waiters share a slow owner's
    delay. The reviewer's alternatives did not consistently improve this
    trade-off, so the existing write-lock coordination is retained. Thread
    dumps identified `CoreEnforcer.enforce` / `getPTokens` and the read lock
    held during enforcement as the main larger-scale bottleneck; the
    separate JCasbin-free design is tracked in #13790.
    
    The reviewer also observed fail-closed denials on granted catalogs over
    twelve 10-second storm runs: A had 6 with this PR versus 0 with base; B
    had 2 versus 2. A superseded older load without a complete newer
    replacement deliberately fails closed, and repeated invalidation can
    also exhaust the bounded reload loop. The storm logs were not inspected,
    so these observed counts cannot be attributed to the superseded-version
    branch. Its warning starts with `Discarded the policies of role` and
    reports both versions; the reload-budget warning starts with `Policies
    of roles` and reports the number of reloads. These H2 results do not
    establish remote-database or production latency behavior.
    MySQL/PostgreSQL, multiple nodes and roles inherited through groups were
    not covered by these benchmarks.
    
    Existing controlled baseline/fix comparisons: eight stale request
    contexts make 8 versus 1 role batch reads; four real H2-backed
    authorization requests make 4 versus 1. These count `EntityStore`
    calls/entities, not total SQL queries or production throughput. Other
    regressions cover failure fanout/retry, independent roles and versions,
    overlapping batches, interruption, incomplete batches, clear-generation
    pruning, partial-version ordering, and cache-expiry lock/probe
    boundaries.
    
    MySQL, PostgreSQL and Docker integration suites were not run.
    
    ---------
    
    Co-authored-by: Qi Yu <[email protected]>
    Co-authored-by: Qi Yu <[email protected]>
---
 .../TestJcasbinRoleSingleFlightH2.java             |  420 ++++++
 .../authorization/jcasbin/JcasbinAuthorizer.java   |  432 +++++-
 .../jcasbin/TestJcasbinAuthorizer.java             | 1520 +++++++++++++++++++-
 3 files changed, 2295 insertions(+), 77 deletions(-)

diff --git 
a/core/src/test/java/org/apache/gravitino/authorization/TestJcasbinRoleSingleFlightH2.java
 
b/core/src/test/java/org/apache/gravitino/authorization/TestJcasbinRoleSingleFlightH2.java
new file mode 100644
index 0000000000..5eb954460c
--- /dev/null
+++ 
b/core/src/test/java/org/apache/gravitino/authorization/TestJcasbinRoleSingleFlightH2.java
@@ -0,0 +1,420 @@
+/*
+ * 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.authorization;
+
+import static org.apache.gravitino.authorization.Privilege.Name.USE_CATALOG;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.security.Principal;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+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.atomic.AtomicInteger;
+import java.util.function.Function;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.cache.GravitinoCache;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.EntityIdResolver;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.server.authorization.jcasbin.JcasbinAuthorizer;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.CoreBackend;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+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;
+
+/** Exercises public role authorization through the real H2/MyBatis entity 
store. */
[email protected]
+public class TestJcasbinRoleSingleFlightH2 {
+  private static final String METALAKE = "single_flight_metalake";
+  private static final String CATALOG = "single_flight_catalog";
+  private static final String ROLE = "single_flight_role";
+  private static final String USER = "single_flight_user";
+  private static final long ROLE_ID = 103L;
+  private static final long CATALOG_ID = 102L;
+  private static final Principal PRINCIPAL = () -> USER;
+  private static final MetadataObject OBJECT =
+      MetadataObjects.of(null, CATALOG, MetadataObject.Type.CATALOG);
+  private static final AuditInfo AUDIT =
+      
AuditInfo.builder().withCreator("creator").withCreateTime(Instant.EPOCH).build();
+
+  @TempDir Path directory;
+
+  private Object previousConfig;
+  private Object previousStore;
+  private Object previousIdGenerator;
+  private Object previousMetrics;
+  private EntityIdResolver previousIdResolver;
+  private CountingStore store;
+  private JcasbinAuthorizer authorizer;
+
+  @BeforeEach
+  void setUp() throws Exception {
+    GravitinoEnv env = GravitinoEnv.getInstance();
+    previousConfig = FieldUtils.readField(env, "config", true);
+    previousStore = FieldUtils.readField(env, "entityStore", true);
+    previousIdGenerator = FieldUtils.readField(env, "idGenerator", true);
+    previousMetrics = FieldUtils.readField(env, "metricsSystem", true);
+    previousIdResolver =
+        (EntityIdResolver)
+            FieldUtils.readStaticField(EntityIdService.class, 
"entityIdResolver", true);
+
+    // Like the core backend lane, this fixture owns one process-global 
MyBatis database at a
+    // time. Refuse to borrow an existing factory: its data source could 
belong to another test,
+    // and closing an unknown live backend merely to make this setup pass 
would be unsafe.
+    assertNull(
+        FieldUtils.readStaticField(SqlSessionFactoryHelper.class, 
"sqlSessionFactory", true),
+        "The isolated H2 fixture must not reuse another test's MyBatis 
factory");
+
+    Config config = new Config(false) {};
+    String dbPath = directory.resolve("roles").toAbsolutePath().toString();
+    config.set(Configs.ENTITY_STORE, Configs.RELATIONAL_ENTITY_STORE);
+    config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PATH, dbPath);
+    config.set(
+        Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL,
+        "jdbc:h2:file:" + dbPath + 
";DB_CLOSE_DELAY=-1;MODE=MYSQL;AUTO_SERVER=FALSE");
+    config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER, "org.h2.Driver");
+    config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER, "test");
+    config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD, "test");
+    // Count real reads, rather than hits in the EntityStore cache. The 
authorizer keeps its
+    // production caches and the relational implementation still executes 
normal MyBatis queries.
+    config.set(Configs.CACHE_ENABLED, false);
+    config.set(Configs.GRAVITINO_AUTHORIZATION_CHANGE_POLL_INTERVAL_SECS, 
3600L);
+    config.set(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS, 3600L);
+    FieldUtils.writeField(env, "config", config, true);
+    FieldUtils.writeField(env, "idGenerator", RandomIdGenerator.INSTANCE, 
true);
+    FieldUtils.writeField(env, "metricsSystem", null, true);
+
+    store = new CountingStore();
+    store.initialize(config);
+    FieldUtils.writeField(env, "entityStore", store, true);
+    seedEntities();
+    authorizer = new JcasbinAuthorizer();
+    authorizer.initialize();
+    store.resetCounts();
+  }
+
+  @AfterEach
+  void tearDown() throws Exception {
+    try {
+      if (store != null) {
+        store.releaseRoleReads.countDown();
+      }
+      if (authorizer != null) {
+        authorizer.close();
+      }
+    } finally {
+      try {
+        if (store != null) {
+          store.close();
+        }
+      } finally {
+        GravitinoEnv env = GravitinoEnv.getInstance();
+        FieldUtils.writeField(env, "config", previousConfig, true);
+        FieldUtils.writeField(env, "entityStore", previousStore, true);
+        FieldUtils.writeField(env, "idGenerator", previousIdGenerator, true);
+        FieldUtils.writeField(env, "metricsSystem", previousMetrics, true);
+        EntityIdService.initialize(previousIdResolver);
+      }
+    }
+  }
+
+  @Test
+  void testConcurrentRequestsShareOneRealRoleRead() throws Exception {
+    int requests = 4;
+    GravitinoCache<Long, Long> loaded = loadedRoles();
+    FieldUtils.writeField(authorizer, "loadedRoles", new 
FirstMissBarrier(loaded, requests), true);
+    store.blockRoleReads = true;
+    ExecutorService executor = Executors.newFixedThreadPool(requests);
+    List<Future<Boolean>> results = new ArrayList<>();
+    try {
+      for (int i = 0; i < requests; i++) {
+        results.add(executor.submit(this::authorize));
+      }
+      assertTrue(store.firstRoleRead.await(15, TimeUnit.SECONDS));
+      store.releaseRoleReads.countDown();
+      for (Future<Boolean> result : results) {
+        assertTrue(result.get(20, TimeUnit.SECONDS));
+      }
+      assertEquals(
+          1, store.roleBatchReads.get(), "one same-role load must serve the 
stale request wave");
+      assertEquals(1, store.roleEntitiesRequested.get());
+      assertEquals(0, store.rolePointReads.get(), "the real relational batch 
path is supported");
+      assertTrue(store.catalogReads.get() >= 1, "role policies must resolve a 
real catalog entity");
+      assertEquals(
+          List.of(
+              List.of(
+                  Long.toString(ROLE_ID),
+                  "CATALOG",
+                  Long.toString(CATALOG_ID),
+                  "USE_CATALOG",
+                  "allow")),
+          policies());
+    } finally {
+      store.releaseRoleReads.countDown();
+      for (Future<Boolean> result : results) {
+        result.cancel(true);
+      }
+      executor.shutdownNow();
+      assertTrue(executor.awaitTermination(20, TimeUnit.SECONDS));
+    }
+  }
+
+  @Test
+  void testPersistedRevocationReloadsPolicies() throws Exception {
+    assertTrue(authorize());
+    assertEquals(1, store.roleBatchReads.get());
+    long originalVersion = roleVersion();
+
+    store.update(
+        NameIdentifier.of(AuthorizationUtils.ofRoleNamespace(METALAKE), ROLE),
+        RoleEntity.class,
+        Entity.EntityType.ROLE,
+        old -> role(List.of()));
+    assertTrue(roleVersion() > originalVersion, "the MyBatis update must 
advance the role version");
+    assertFalse(authorize(), "a fresh request must not retain the revoked 
catalog privilege");
+    assertEquals(2, store.roleBatchReads.get());
+    assertTrue(policies().isEmpty());
+  }
+
+  private boolean authorize() {
+    // Every caller owns a request context, matching concurrent HTTP requests 
rather than workers
+    // sharing one context's initializer.
+    return authorizer.authorize(
+        PRINCIPAL, METALAKE, OBJECT, USE_CATALOG, new 
AuthorizationRequestContext());
+  }
+
+  private long roleVersion() {
+    return SessionUtils.getWithoutCommit(
+            RoleMetaMapper.class, mapper -> 
mapper.batchGetRoleUpdatedAt(List.of(ROLE_ID)))
+        .get(0)
+        .getUpdatedAt();
+  }
+
+  @SuppressWarnings("unchecked")
+  private GravitinoCache<Long, Long> loadedRoles() throws 
IllegalAccessException {
+    return (GravitinoCache<Long, Long>) FieldUtils.readField(authorizer, 
"loadedRoles", true);
+  }
+
+  @SuppressWarnings("unchecked")
+  private List<List<String>> policies() throws Exception {
+    Object enforcer = FieldUtils.readField(authorizer, "allowEnforcer", true);
+    return (List<List<String>>) 
enforcer.getClass().getMethod("getPolicy").invoke(enforcer);
+  }
+
+  private void seedEntities() throws IOException {
+    store.put(
+        BaseMetalake.builder()
+            .withId(101L)
+            .withName(METALAKE)
+            .withComment("")
+            .withProperties(null)
+            .withVersion(SchemaVersion.V_0_1)
+            .withAuditInfo(AUDIT)
+            .build(),
+        false);
+    store.put(
+        CatalogEntity.builder()
+            .withId(CATALOG_ID)
+            .withName(CATALOG)
+            .withNamespace(Namespace.of(METALAKE))
+            .withType(Catalog.Type.RELATIONAL)
+            .withProvider("test")
+            .withComment("")
+            .withProperties(null)
+            .withAuditInfo(AUDIT)
+            .build(),
+        false);
+    store.put(
+        role(List.of(SecurableObjects.ofCatalog(CATALOG, 
List.of(Privileges.UseCatalog.allow())))),
+        false);
+    store.put(
+        UserEntity.builder()
+            .withId(104L)
+            .withName(USER)
+            .withNamespace(AuthorizationUtils.ofUserNamespace(METALAKE))
+            .withRoleIds(List.of(ROLE_ID))
+            .withRoleNames(List.of(ROLE))
+            .withAuditInfo(AUDIT)
+            .build(),
+        false);
+  }
+
+  private static RoleEntity role(List<SecurableObject> objects) {
+    return RoleEntity.builder()
+        .withId(ROLE_ID)
+        .withName(ROLE)
+        .withNamespace(AuthorizationUtils.ofRoleNamespace(METALAKE))
+        .withProperties(null)
+        .withAuditInfo(AUDIT)
+        .withSecurableObjects(objects)
+        .build();
+  }
+
+  /** All reads below delegate to the actual relational store, including its 
MyBatis backend. */
+  private static class CountingStore extends RelationalEntityStore {
+    final AtomicInteger roleBatchReads = new AtomicInteger();
+    final AtomicInteger roleEntitiesRequested = new AtomicInteger();
+    final AtomicInteger rolePointReads = new AtomicInteger();
+    final AtomicInteger catalogReads = new AtomicInteger();
+    final CountDownLatch firstRoleRead = new CountDownLatch(1);
+    final CountDownLatch releaseRoleReads = new CountDownLatch(1);
+    volatile boolean blockRoleReads;
+
+    void resetCounts() {
+      roleBatchReads.set(0);
+      roleEntitiesRequested.set(0);
+      rolePointReads.set(0);
+      catalogReads.set(0);
+    }
+
+    @Override
+    public <E extends Entity & HasIdentifier> List<E> batchGet(
+        List<NameIdentifier> identifiers, Entity.EntityType type, Class<E> 
entityClass) {
+      if (type == Entity.EntityType.ROLE) {
+        roleBatchReads.incrementAndGet();
+        roleEntitiesRequested.addAndGet(identifiers.size());
+        firstRoleRead.countDown();
+        if (blockRoleReads) {
+          try {
+            if (!releaseRoleReads.await(20, TimeUnit.SECONDS)) {
+              throw new IllegalStateException("Timed out waiting to release 
the real role read");
+            }
+          } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new IllegalStateException("Interrupted real role read", e);
+          }
+        }
+      }
+      return super.batchGet(identifiers, type, entityClass);
+    }
+
+    @Override
+    public <E extends Entity & HasIdentifier> E get(
+        NameIdentifier identifier, Entity.EntityType type, Class<E> 
entityClass)
+        throws IOException {
+      if (type == Entity.EntityType.ROLE) {
+        rolePointReads.incrementAndGet();
+      } else if (type == Entity.EntityType.CATALOG) {
+        catalogReads.incrementAndGet();
+      }
+      return super.get(identifier, type, entityClass);
+    }
+  }
+
+  /** Freeze each worker's first cache miss before any worker can populate the 
role policies. */
+  private static class FirstMissBarrier implements GravitinoCache<Long, Long> {
+    private final GravitinoCache<Long, Long> delegate;
+    private final CyclicBarrier barrier;
+    private final Set<Thread> seen = ConcurrentHashMap.newKeySet();
+
+    FirstMissBarrier(GravitinoCache<Long, Long> delegate, int participants) {
+      this.delegate = delegate;
+      barrier = new CyclicBarrier(participants);
+    }
+
+    @Override
+    public Optional<Long> getIfPresent(Long key) {
+      Optional<Long> value = delegate.getIfPresent(key);
+      if (key == ROLE_ID && value.isEmpty() && 
seen.add(Thread.currentThread())) {
+        try {
+          barrier.await(15, TimeUnit.SECONDS);
+        } catch (Exception e) {
+          throw new IllegalStateException(
+              "Concurrent requests did not reach their first role miss", e);
+        }
+      }
+      return value;
+    }
+
+    @Override
+    public Long get(Long key, Function<Long, Long> loader) {
+      return delegate.get(key, loader);
+    }
+
+    @Override
+    public void put(Long key, Long value) {
+      delegate.put(key, value);
+    }
+
+    @Override
+    public void invalidate(Long key) {
+      delegate.invalidate(key);
+    }
+
+    @Override
+    public void invalidateAll() {
+      delegate.invalidateAll();
+    }
+
+    @Override
+    public void invalidateByPrefix(String prefix) {
+      delegate.invalidateByPrefix(prefix);
+    }
+
+    @Override
+    public void runInvalidationBatch(Runnable batch) {
+      delegate.runInvalidationBatch(batch);
+    }
+
+    @Override
+    public long size() {
+      return delegate.size();
+    }
+
+    @Override
+    public void close() throws IOException {
+      delegate.close();
+    }
+  }
+}
diff --git 
a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
 
b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
index ecb81cca83..cffbfd6c21 100644
--- 
a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
+++ 
b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
@@ -27,6 +27,7 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Locale;
@@ -34,7 +35,9 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -242,6 +245,25 @@ public class JcasbinAuthorizer implements 
GravitinoAuthorizer {
    */
   private GravitinoCache<Long, Long> loadedRoles;
 
+  /**
+   * In-progress policy loads shared across requests. Versions and clear 
generations are part of the
+   * key: an older load must not satisfy a request that observed newer 
privileges or a policy
+   * invalidation. Entries are removed on completion, including failures; this 
is not another cache.
+   */
+  private final Map<RolePolicyLoadKey, CompletableFuture<Boolean>> 
rolePolicyLoads =
+      new ConcurrentHashMap<>();
+
+  /**
+   * Highest observed role versions while calls are loading or waiting. A 
partial load has no
+   * loadedRoles marker, so that cache alone cannot stop an older in-progress 
load from overwriting
+   * it. References keep this floor alive until all such calls finish, 
independently of the partial
+   * retry backoff. This is not a persistent version watermark: once these 
calls finish and any
+   * partial-load backoff expires, a caller delayed before retention can still 
publish an older
+   * probed version. A later request probing the newer version reloads it. 
Guarded by the write lock
+   * of {@link #rolePolicyLock}; removed when idle.
+   */
+  private final Map<Long, RolePolicyLoadState> rolePolicyLoadStates = new 
HashMap<>();
+
   /**
    * partialRoleLoadBackoff: roleId -> marker present while a role whose last 
load was incomplete
    * must not be retried. Policy replacement writes this marker under {@link 
#rolePolicyLock}, so a
@@ -1429,8 +1451,10 @@ public class JcasbinAuthorizer implements 
GravitinoAuthorizer {
   /**
    * Reloads every role in {@code roleIds} whose loaded version is missing or 
older than the DB.
    *
-   * @return ids of stale roles whose entity could not be read, so their 
policies were not reloaded.
-   *     A role that no longer exists is not included: having no policies is 
correct for it.
+   * @return ids of stale roles whose policies could not be read, were 
superseded by a newer
+   *     observed version without a complete replacement, or were recreated 
under the same name
+   *     after the version probe. A role that no longer exists is not 
included: having no policies
+   *     is correct for it.
    */
   private Set<Long> versionCheckAndLoadRoles(
       String metalake, List<Long> roleIds, AuthorizationRequestContext 
requestContext) {
@@ -1467,102 +1491,357 @@ public class JcasbinAuthorizer implements 
GravitinoAuthorizer {
 
     List<RoleUpdatedAt> staleRoleVersions = new ArrayList<>();
     for (RoleUpdatedAt rv : roleVersions) {
-      Optional<Long> cachedUpdatedAt = 
loadedRoles.getIfPresent(rv.getRoleId());
-      if (cachedUpdatedAt.isPresent() && cachedUpdatedAt.get() >= 
rv.getUpdatedAt()) {
-        continue;
-      }
-      // A role missing from loadedRoles because its last load was incomplete 
would otherwise be
-      // retried on every single request. Its partially loaded policies stay 
in the enforcer, so
-      // the privileges that did resolve keep working while the backoff is in 
effect.
-      if (!cachedUpdatedAt.isPresent()
-          && partialRoleLoadBackoff.getIfPresent(rv.getRoleId()).isPresent()) {
-        continue;
+      if (needsRolePolicyLoad(rv)) {
+        staleRoleVersions.add(rv);
       }
-      staleRoleVersions.add(rv);
     }
 
     if (staleRoleVersions.isEmpty()) {
       return Collections.emptySet();
     }
 
+    List<Long> leasedRoles = new ArrayList<>();
+    try {
+      return coalesceRolePolicyLoads(metalake, staleRoleVersions, 
requestContext, leasedRoles);
+    } finally {
+      releaseRolePolicyLoadStates(leasedRoles);
+    }
+  }
+
+  private Set<Long> coalesceRolePolicyLoads(
+      String metalake,
+      List<RoleUpdatedAt> staleRoleVersions,
+      AuthorizationRequestContext requestContext,
+      List<Long> leasedRoles) {
+    Map<RolePolicyLoadKey, CompletableFuture<Boolean>> requestLoads = new 
LinkedHashMap<>();
+    List<RolePolicyLoadKey> ownedLoads = new ArrayList<>();
+    try {
+      for (RolePolicyLoadKey key : 
retainRolePolicyLoadStates(staleRoleVersions, leasedRoles)) {
+        CompletableFuture<Boolean> result = new CompletableFuture<>();
+        CompletableFuture<Boolean> existing = rolePolicyLoads.putIfAbsent(key, 
result);
+        requestLoads.put(key, existing == null ? result : existing);
+        if (existing == null) {
+          ownedLoads.add(key);
+        }
+      }
+
+      // Claim every role before doing I/O, and finish every load we own 
before waiting for another
+      // request. Waiting first could deadlock requests owning opposite halves 
of a role batch.
+      List<RolePolicyLoadKey> pendingLoads = new ArrayList<>();
+      // Recheck after claiming: a request can observe a stale marker, be 
delayed, and become the
+      // owner after the previous owner has already completed and removed its 
flight.
+      for (RolePolicyLoadKey key : ownedLoads) {
+        if (needsRolePolicyLoad(key.roleVersion)) {
+          pendingLoads.add(key);
+        } else {
+          requestLoads.get(key).complete(true);
+        }
+      }
+      loadRolePolicies(metalake, pendingLoads, requestContext, requestLoads);
+    } catch (RuntimeException | Error e) {
+      for (RolePolicyLoadKey key : ownedLoads) {
+        requestLoads.get(key).completeExceptionally(e);
+      }
+      throw e;
+    } finally {
+      for (RolePolicyLoadKey key : ownedLoads) {
+        rolePolicyLoads.remove(key, requestLoads.get(key));
+      }
+    }
+
     Set<Long> unreadableRoleIds = new HashSet<>();
+    for (Map.Entry<RolePolicyLoadKey, CompletableFuture<Boolean>> load : 
requestLoads.entrySet()) {
+      if (!awaitRolePolicyLoad(load.getKey(), load.getValue())) {
+        unreadableRoleIds.add(load.getKey().roleVersion.getRoleId());
+      }
+    }
+    return unreadableRoleIds;
+  }
+
+  /**
+   * Captures the clear generation of every stale role and retains its version 
floor, all in one
+   * critical section. The write lock is shared with every enforce() call, so 
it is taken once per
+   * request rather than once per role. Pruning removes map entries before 
publishing its watermark
+   * under the same lock, so a captured generation never observes the gap 
between the two.
+   */
+  private List<RolePolicyLoadKey> retainRolePolicyLoadStates(
+      List<RoleUpdatedAt> staleRoleVersions, List<Long> leasedRoles) {
+    List<RolePolicyLoadKey> keys = new ArrayList<>(staleRoleVersions.size());
+    rolePolicyLock.writeLock().lock();
+    try {
+      for (RoleUpdatedAt rv : staleRoleVersions) {
+        long roleId = rv.getRoleId();
+        RolePolicyLoadKey key = new RolePolicyLoadKey(rv, 
roleClearGenerationWithoutLock(roleId));
+        RolePolicyLoadState state = rolePolicyLoadStates.get(roleId);
+        if (state == null) {
+          rolePolicyLoadStates.put(roleId, new 
RolePolicyLoadState(rv.getUpdatedAt()));
+        } else {
+          state.highestVersion = Math.max(state.highestVersion, 
rv.getUpdatedAt());
+          state.references++;
+        }
+        leasedRoles.add(roleId);
+        keys.add(key);
+      }
+    } finally {
+      rolePolicyLock.writeLock().unlock();
+    }
+    return keys;
+  }
+
+  private void releaseRolePolicyLoadStates(List<Long> leasedRoles) {
+    rolePolicyLock.writeLock().lock();
+    try {
+      for (Long roleId : leasedRoles) {
+        RolePolicyLoadState state = rolePolicyLoadStates.get(roleId);
+        if (--state.references == 0) {
+          rolePolicyLoadStates.remove(roleId);
+        }
+      }
+    } finally {
+      rolePolicyLock.writeLock().unlock();
+    }
+  }
+
+  private boolean needsRolePolicyLoad(RoleUpdatedAt roleVersion) {
+    Optional<Long> cachedUpdatedAt = 
loadedRoles.getIfPresent(roleVersion.getRoleId());
+    if (cachedUpdatedAt.isPresent() && cachedUpdatedAt.get() >= 
roleVersion.getUpdatedAt()) {
+      return false;
+    }
+    // Partially loaded policies stay usable during their existing retry 
backoff, even though
+    // they deliberately have no loadedRoles marker.
+    return cachedUpdatedAt.isPresent()
+        || 
!partialRoleLoadBackoff.getIfPresent(roleVersion.getRoleId()).isPresent();
+  }
+
+  private boolean awaitRolePolicyLoad(RolePolicyLoadKey key, 
CompletableFuture<Boolean> result) {
+    try {
+      // There is no separate waiter timeout. This wait depends on the owner's 
completion,
+      // including its DB pool maxWaitMillis and query execution time (and 
query timeouts, if set).
+      // One stuck owner can delay every request waiting on its roles.
+      return result.get();
+    } catch (InterruptedException e) {
+      // Interrupting a waiter must not cancel the load other requests still 
depend on.
+      Thread.currentThread().interrupt();
+      throw new IllegalStateException(
+          "Interrupted while waiting for role policy load " + 
key.roleVersion.getRoleId(), e);
+    } catch (ExecutionException e) {
+      Throwable cause = e.getCause();
+      if (cause instanceof RuntimeException) {
+        throw (RuntimeException) cause;
+      }
+      if (cause instanceof Error) {
+        throw (Error) cause;
+      }
+      throw new IllegalStateException("Failed to load role policies", cause);
+    }
+  }
+
+  private void loadRolePolicies(
+      String metalake,
+      List<RolePolicyLoadKey> pendingLoads,
+      AuthorizationRequestContext requestContext,
+      Map<RolePolicyLoadKey, CompletableFuture<Boolean>> requestLoads) {
+    if (pendingLoads.isEmpty()) {
+      return;
+    }
     EntityStore entityStore = GravitinoEnv.getInstance().entityStore();
     List<NameIdentifier> roleIdents =
-        staleRoleVersions.stream()
-            .map(rv -> NameIdentifierUtil.ofRole(metalake, rv.getRoleName()))
+        pendingLoads.stream()
+            .map(key -> NameIdentifierUtil.ofRole(metalake, 
key.roleVersion.getRoleName()))
             .collect(Collectors.toList());
     List<RoleEntity> roleEntities;
     try {
       roleEntities = entityStore.batchGet(roleIdents, Entity.EntityType.ROLE, 
RoleEntity.class);
     } catch (Exception e) {
-      LOG.warn("Failed to batch load stale role policies for roleIds {}", 
staleRoleVersions, e);
-      roleEntities = new ArrayList<>();
-    }
-    if (roleEntities == null) {
-      roleEntities = new ArrayList<>();
-    }
-    // Some EntityStore implementations don't support batchGet for ROLE and 
return empty;
-    // fall back to per-role get so policies still load.
-    if (roleEntities.isEmpty()) {
-      roleEntities = new ArrayList<>(staleRoleVersions.size());
-      for (RoleUpdatedAt rv : staleRoleVersions) {
-        try {
-          roleEntities.add(
-              entityStore.get(
-                  NameIdentifierUtil.ofRole(metalake, rv.getRoleName()),
-                  Entity.EntityType.ROLE,
-                  RoleEntity.class));
-        } catch (NoSuchEntityException e) {
-          LOG.debug("Role {} was dropped before its policies could be loaded", 
rv.getRoleId(), e);
-        } catch (Exception e) {
-          LOG.warn("Failed to load role policies for roleId {}", 
rv.getRoleId(), e);
-          unreadableRoleIds.add(rv.getRoleId());
+      LOG.warn("Failed to batch load stale role policies for roles {}", 
roleIdents, e);
+      roleEntities = Collections.emptyList();
+    }
+    Map<Long, RoleEntity> roleEntitiesById = new HashMap<>();
+    if (roleEntities != null) {
+      for (RoleEntity roleEntity : roleEntities) {
+        if (roleEntity != null) {
+          roleEntitiesById.put(roleEntity.id(), roleEntity);
         }
       }
     }
 
-    Map<Long, RoleUpdatedAt> staleRoleVersionById =
-        
staleRoleVersions.stream().collect(Collectors.toMap(RoleUpdatedAt::getRoleId, 
rv -> rv));
-    for (RoleEntity roleEntity : roleEntities) {
-      if (roleEntity == null) {
-        continue;
-      }
-      RoleUpdatedAt rv = staleRoleVersionById.get(roleEntity.id());
-      if (rv == null) {
-        continue;
+    for (RolePolicyLoadKey key : pendingLoads) {
+      CompletableFuture<Boolean> result = requestLoads.get(key);
+      try {
+        result.complete(
+            loadRolePolicy(
+                entityStore,
+                metalake,
+                key,
+                roleEntitiesById.get(key.roleVersion.getRoleId()),
+                requestContext));
+      } catch (RuntimeException | Error e) {
+        // A failed role must not fail another role's waiters, including roles 
still to be loaded.
+        // Settle each owned flight before the caller awaits results and 
propagates its failure.
+        result.completeExceptionally(e);
       }
-      long roleId = rv.getRoleId();
-      long dbUpdatedAt = rv.getUpdatedAt();
-
-      // Resolve every securable object to a metadata id before touching the 
enforcers, so the
-      // critical section below stays free of DB round-trips.
-      Optional<ResolvedRolePolicies> resolution = 
resolveRolePolicies(roleEntity, requestContext);
-      if (!resolution.isPresent()) {
-        unreadableRoleIds.add(roleId);
-        continue;
+    }
+  }
+
+  private boolean loadRolePolicy(
+      EntityStore entityStore,
+      String metalake,
+      RolePolicyLoadKey key,
+      @Nullable RoleEntity roleEntity,
+      AuthorizationRequestContext requestContext) {
+    RoleUpdatedAt rv = key.roleVersion;
+    long roleId = rv.getRoleId();
+    // Stores may not support batchGet for ROLE, or may return only part of a 
batch. Every owned
+    // role needs a concrete outcome so all its waiters receive the same read 
failure, if any.
+    if (roleEntity == null) {
+      try {
+        roleEntity =
+            entityStore.get(
+                NameIdentifierUtil.ofRole(metalake, rv.getRoleName()),
+                Entity.EntityType.ROLE,
+                RoleEntity.class);
+      } catch (NoSuchEntityException e) {
+        LOG.debug("Role {} was dropped before its policies could be loaded", 
roleId, e);
+        invalidateRolePolicies(roleId);
+        return true;
+      } catch (Exception e) {
+        LOG.warn("Failed to load role policies for roleId {}", roleId, e);
+        return false;
       }
-      ResolvedRolePolicies resolved = resolution.get();
+    }
+    if (roleEntity == null) {
+      return false;
+    }
+    if (roleEntity.id() != roleId) {
+      LOG.warn(
+          "Role {} ({}) was read with id {}: it was dropped and recreated 
after its version was"
+              + " probed, so its policies are not loaded and requests on it 
fail closed",
+          roleId,
+          rv.getRoleName(),
+          roleEntity.id());
+      return false;
+    }
 
-      if (!replaceRolePolicies(roleId, dbUpdatedAt, resolved)) {
-        // Another request completed this version (or a newer one) while this 
request was resolving
-        // metadata ids. Its policies and marker are authoritative, even if 
this request's older
-        // resolution result was partial.
-        continue;
+    // Resolve every securable object to a metadata id before touching the 
enforcers, so the
+    // critical section below stays free of DB round-trips.
+    // Shared loads reuse the owner's request context, including catalog 
normalization failures
+    // remembered earlier in that request. A transient failure can therefore 
publish a partial load
+    // for all waiters; unresolved DENY objects install catalog-level deny 
guards. Other requests
+    // reuse that fail-closed state until PARTIAL_ROLE_LOAD_RETRY_MS expires 
(unless invalidated).
+    // Keeping this context also preserves request-local lookup deduplication.
+    Optional<ResolvedRolePolicies> resolution = 
resolveRolePolicies(roleEntity, requestContext);
+    if (!resolution.isPresent()) {
+      return false;
+    }
+    ResolvedRolePolicies resolved = resolution.get();
+
+    RolePolicyPublication publication = replaceUnclearedRolePolicies(key, 
resolved);
+    if (publication != RolePolicyPublication.APPLIED) {
+      // A skipped publication can follow an invalidation. Keep the caller's 
pre-load request
+      // generation so the bounded evaluation loop revalidates and reloads 
cleared policies.
+      return publication != RolePolicyPublication.UNREADABLE;
+    }
+
+    if (!resolved.isComplete()) {
+      LOG.warn(
+          "Loaded role {} ({}) with {} of {} securable objects; unresolved 
objects: {}. "
+              + "The role is not marked as loaded and will be retried in at 
most {} ms.",
+          roleId,
+          rv.getRoleName(),
+          roleEntity.securableObjects().size() - 
resolved.getUnresolvedObjects().size(),
+          roleEntity.securableObjects().size(),
+          resolved.getUnresolvedObjects(),
+          PARTIAL_ROLE_LOAD_RETRY_MS);
+    }
+    return true;
+  }
+
+  private long roleClearGenerationWithoutLock(long roleId) {
+    return Math.max(roleClearGenerations.getOrDefault(roleId, 0L), 
prunedRoleClearGeneration);
+  }
+
+  private RolePolicyPublication replaceUnclearedRolePolicies(
+      RolePolicyLoadKey key, ResolvedRolePolicies resolved) {
+    rolePolicyLock.writeLock().lock();
+    try {
+      long roleId = key.roleVersion.getRoleId();
+      if (roleClearGenerationWithoutLock(roleId) != key.clearGeneration) {
+        return RolePolicyPublication.SKIPPED;
+      }
+      RolePolicyLoadState state = rolePolicyLoadStates.get(roleId);
+      if (state.highestVersion > key.roleVersion.getUpdatedAt()) {
+        Optional<Long> loadedVersion = loadedRoles.getIfPresent(roleId);
+        if (!loadedVersion.isPresent() || loadedVersion.get() < 
state.highestVersion) {
+          // A newer partial load (or failed read) may have no loaded marker. 
Do not overwrite it
+          // with an old snapshot. Unlike an epoch change, this has no 
generation repair signal,
+          // so explicitly fail this load and every waiter closed.
+          LOG.warn(
+              "Discarded the policies of role {} loaded at version {}, as 
version {} was observed"
+                  + " concurrently without a complete load; failing closed",
+              roleId,
+              key.roleVersion.getUpdatedAt(),
+              state.highestVersion);
+          return RolePolicyPublication.UNREADABLE;
+        }
+        // A complete newer version already satisfies the request. Do not 
delegate an obsolete
+        // candidate to replacement: expiry between two marker probes could 
otherwise admit it.
+        return RolePolicyPublication.SKIPPED;
       }
+      return replaceRolePolicies(
+              key.roleVersion.getRoleId(), key.roleVersion.getUpdatedAt(), 
resolved)
+          ? RolePolicyPublication.APPLIED
+          : RolePolicyPublication.SKIPPED;
+    } finally {
+      rolePolicyLock.writeLock().unlock();
+    }
+  }
 
-      if (!resolved.isComplete()) {
-        LOG.warn(
-            "Loaded role {} ({}) with {} of {} securable objects; unresolved 
objects: {}. "
-                + "The role is not marked as loaded and will be retried in at 
most {} ms.",
-            roleId,
-            rv.getRoleName(),
-            roleEntity.securableObjects().size() - 
resolved.getUnresolvedObjects().size(),
-            roleEntity.securableObjects().size(),
-            resolved.getUnresolvedObjects(),
-            PARTIAL_ROLE_LOAD_RETRY_MS);
+  private enum RolePolicyPublication {
+    APPLIED,
+    SKIPPED,
+    UNREADABLE
+  }
+
+  private static final class RolePolicyLoadState {
+    private long highestVersion;
+    private int references = 1;
+
+    private RolePolicyLoadState(long highestVersion) {
+      this.highestVersion = highestVersion;
+    }
+  }
+
+  private static final class RolePolicyLoadKey {
+    private final RoleUpdatedAt roleVersion;
+    private final long clearGeneration;
+
+    private RolePolicyLoadKey(RoleUpdatedAt roleVersion, long clearGeneration) 
{
+      // RoleUpdatedAt is a mutable mapper DTO; keep the map key stable even 
if its caller reuses
+      // it.
+      this.roleVersion =
+          new RoleUpdatedAt(
+              roleVersion.getRoleId(), roleVersion.getRoleName(), 
roleVersion.getUpdatedAt());
+      this.clearGeneration = clearGeneration;
+    }
+
+    @Override
+    public boolean equals(Object other) {
+      if (this == other) {
+        return true;
+      }
+      if (!(other instanceof RolePolicyLoadKey)) {
+        return false;
       }
+      RolePolicyLoadKey that = (RolePolicyLoadKey) other;
+      return roleVersion.getRoleId() == that.roleVersion.getRoleId()
+          && roleVersion.getUpdatedAt() == that.roleVersion.getUpdatedAt()
+          && clearGeneration == that.clearGeneration;
+    }
+
+    @Override
+    public int hashCode() {
+      return Objects.hash(roleVersion.getRoleId(), roleVersion.getUpdatedAt(), 
clearGeneration);
     }
-    return unreadableRoleIds;
   }
 
   /**
@@ -1750,7 +2029,8 @@ public class JcasbinAuthorizer implements 
GravitinoAuthorizer {
       String metalake, AuthorizationRequestContext requestContext, 
BooleanSupplier evaluation) {
     if (!requestContext.getUnreadableRoleIds().isEmpty()) {
       LOG.warn(
-          "Failed to read roles {} during the initial role load; failing 
closed",
+          "Roles {} could not be read, were superseded by a newer version, or 
were recreated"
+              + " during the initial role load; failing closed",
           requestContext.getUnreadableRoleIds());
       return Optional.empty();
     }
@@ -1786,13 +2066,15 @@ public class JcasbinAuthorizer implements 
GravitinoAuthorizer {
             e);
         return Optional.empty();
       }
-      // A role whose entity could not be read has lost its policies without a 
replacement. Its
+      // A role whose entity could not be read, was superseded or was 
recreated under the same name
+      // has lost its policies without a replacement. Its
       // missing rows prove neither the absence of a deny nor of an allow, so 
the check cannot be
       // evaluated. Partially loaded and dropped roles are evaluated as usual: 
their policy state is
       // the same one any request would see.
       if (!unreadableRoleIds.isEmpty()) {
         LOG.warn(
-            "Failed to read roles {} to reload their cleared policies; failing 
closed",
+            "Roles {} could not be read, were superseded by a newer version, 
or were recreated"
+                + " while reloading their cleared policies; failing closed",
             unreadableRoleIds);
         return Optional.empty();
       }
diff --git 
a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
 
b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
index 67373a569a..cbc5523b10 100644
--- 
a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
+++ 
b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
@@ -61,6 +61,8 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
@@ -69,6 +71,7 @@ import java.util.concurrent.Future;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
@@ -1578,6 +1581,1373 @@ public class TestJcasbinAuthorizer {
     }
   }
 
+  /**
+   * A role failure must not fail waiters for a healthy role in the same 
owner's batch.
+   *
+   * @param failedRoleFirst whether the failed role precedes the healthy role
+   * @param failWithError whether the resolver throws an Error instead of a 
RuntimeException
+   */
+  @ParameterizedTest
+  @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+  public void testHealthyRoleWaiterDoesNotInheritOtherRoleFailure(
+      boolean failedRoleFirst, boolean failWithError) throws Exception {
+    long goodId = 9201L;
+    long badId = 9202L;
+    RoleEntity good =
+        mockRoleInStore(
+            goodId,
+            "healthyBatchRole",
+            ImmutableList.of(
+                buildSecurableObject(
+                    goodId,
+                    MetadataObject.Type.CATALOG,
+                    "healthyBatchCatalog",
+                    USE_CATALOG,
+                    "ALLOW")));
+    RoleEntity bad =
+        mockRoleInStore(
+            badId,
+            "failedBatchRole",
+            ImmutableList.of(
+                buildSecurableObject(
+                    badId,
+                    MetadataObject.Type.CATALOG,
+                    "failedBatchCatalog",
+                    USE_CATALOG,
+                    "ALLOW")));
+    RoleUpdatedAt goodVersion = mockedRoleVersions.get(goodId);
+    RoleUpdatedAt badVersion = mockedRoleVersions.get(badId);
+    CountDownLatch enteredRead = new CountDownLatch(1);
+    CountDownLatch releaseRead = new CountDownLatch(1);
+    CountDownLatch joined = new CountDownLatch(1);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined);
+    Throwable badFailure =
+        failWithError
+            ? new AssertionError("only the unrelated catalog failed")
+            : new IllegalStateException("only the unrelated catalog failed");
+    List<Long> roleIds =
+        failedRoleFirst ? ImmutableList.of(badId, goodId) : 
ImmutableList.of(goodId, badId);
+    List<NameIdentifier> roleIdents =
+        failedRoleFirst
+            ? ImmutableList.of(bad.nameIdentifier(), good.nameIdentifier())
+            : ImmutableList.of(good.nameIdentifier(), bad.nameIdentifier());
+    AtomicInteger batchReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              batchReads.incrementAndGet();
+              enteredRead.countDown();
+              assertTrue(releaseRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(good, bad);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Throwable> owner =
+          workers.submit(
+              () -> {
+                try (MockedStatic<GravitinoEnv> env = 
mockStatic(GravitinoEnv.class);
+                    MockedStatic<MetadataIdConverter> metadata =
+                        mockStatic(
+                            MetadataIdConverter.class,
+                            invocation -> {
+                              String method = invocation.getMethod().getName();
+                              if (method.equals("getID")
+                                  || 
method.equals("getIdForNormalizedObject")) {
+                                MetadataObject object = 
invocation.getArgument(0);
+                                if 
(object.fullName().equals("failedBatchCatalog")) {
+                                  if (badFailure instanceof Error) {
+                                    throw (Error) badFailure;
+                                  }
+                                  throw (RuntimeException) badFailure;
+                                }
+                                return Optional.of(CATALOG_ID);
+                              }
+                              return invocation.callRealMethod();
+                            })) {
+                  env.when(GravitinoEnv::getInstance).thenReturn(gravitinoEnv);
+                  try {
+                    invokeVersionCheckAndLoadRoles(
+                        jcasbinAuthorizer,
+                        METALAKE,
+                        roleIds,
+                        roleContext(ImmutableMap.of(goodId, goodVersion, 
badId, badVersion)));
+                    return null;
+                  } catch (InvocationTargetException e) {
+                    return e.getCause();
+                  }
+                }
+              });
+      assertTrue(enteredRead.await(10, TimeUnit.SECONDS));
+      Future<Set<Long>> goodOnly =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(
+                      ImmutableList.of(goodId), ImmutableMap.of(goodId, 
goodVersion)));
+      assertTrue(joined.await(10, TimeUnit.SECONDS));
+      releaseRead.countDown();
+      assertSame(badFailure, owner.get(10, TimeUnit.SECONDS));
+      assertEquals(
+          goodVersion.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(goodId).orElse(null));
+      assertFalse(
+          getAllowEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(goodId))
+              .isEmpty());
+      assertTrue(flights.isEmpty());
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(badId).isPresent());
+      assertEquals(1, batchReads.get(), "the owner must retain its batched 
role read");
+      assertTrue(
+          goodOnly.get(10, TimeUnit.SECONDS).isEmpty(),
+          "a waiter for the fully loaded healthy role must not inherit the 
other role's failure");
+      assertNoRolePolicyLoadStates();
+    } finally {
+      releaseRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Concurrent stale observations must share the entity read. */
+  @Test
+  public void testConcurrentRoleReloadReadsEntityOnce() throws Exception {
+    long roleId = 9101L;
+    String roleName = "singleFlightRole";
+    RoleEntity role =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    List<NameIdentifier> roleIdents =
+        ImmutableList.of(NameIdentifierUtil.ofRole(METALAKE, roleName));
+    AtomicInteger entityReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              entityReads.incrementAndGet();
+              return ImmutableList.of(role);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+
+    int callers = 8;
+    CountDownLatch observedStale = new CountDownLatch(callers);
+    GravitinoCache<Long, Long> loadedRoles = 
getLoadedRolesCache(jcasbinAuthorizer);
+    GravitinoCache<Long, Long> gatedLoadedRoles = Mockito.spy(loadedRoles);
+    Thread callerThread = Thread.currentThread();
+    ThreadLocal<Boolean> firstRead = ThreadLocal.withInitial(() -> true);
+    doAnswer(
+            invocation -> {
+              Optional<Long> snapshot = loadedRoles.getIfPresent(roleId);
+              if (Thread.currentThread() != callerThread && firstRead.get()) {
+                firstRead.set(false);
+                // Capture the missing marker before releasing any reader. A 
start latch alone
+                // would let late workers hit the completed cache and hide 
duplicate loads.
+                observedStale.countDown();
+                assertTrue(observedStale.await(10, TimeUnit.SECONDS));
+              }
+              return snapshot;
+            })
+        .when(gatedLoadedRoles)
+        .getIfPresent(roleId);
+    Field loadedRolesField = 
JcasbinAuthorizer.class.getDeclaredField("loadedRoles");
+    loadedRolesField.setAccessible(true);
+    loadedRolesField.set(jcasbinAuthorizer, gatedLoadedRoles);
+
+    ExecutorService workers = Executors.newFixedThreadPool(callers);
+    try {
+      List<Future<Set<Long>>> results = new ArrayList<>();
+      for (int i = 0; i < callers; i++) {
+        results.add(
+            workers.submit(
+                () ->
+                    reloadRolesInWorker(
+                        ImmutableList.of(roleId), ImmutableMap.of(roleId, 
version))));
+      }
+      for (Future<Set<Long>> result : results) {
+        assertTrue(result.get(10, TimeUnit.SECONDS).isEmpty());
+      }
+      assertEquals(1, entityReads.get(), "concurrent misses must share the 
role entity read");
+      assertEquals(version.getUpdatedAt(), 
loadedRoles.getIfPresent(roleId).orElse(null));
+      assertEquals(
+          1,
+          getAllowEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).size(),
+          "the shared read must still publish the role's actual policy");
+    } finally {
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      loadedRolesField.set(jcasbinAuthorizer, loadedRoles);
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** A request that observed a stale marker before the previous load finished 
must not reload. */
+  @Test
+  public void testDelayedOwnerRechecksMarkerAfterPreviousLoadFinished() throws 
Exception {
+    long roleId = 9103L;
+    String roleName = "delayedOwnerRole";
+    RoleEntity role =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    List<NameIdentifier> roleIdents =
+        ImmutableList.of(NameIdentifierUtil.ofRole(METALAKE, roleName));
+    AtomicInteger entityReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              entityReads.incrementAndGet();
+              return ImmutableList.of(role);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+
+    CountDownLatch observedStale = new CountDownLatch(1);
+    CountDownLatch previousLoadFinished = new CountDownLatch(1);
+    AtomicReference<Thread> delayedThread = new AtomicReference<>();
+    AtomicBoolean firstDelayedRead = new AtomicBoolean(true);
+    GravitinoCache<Long, Long> loadedRoles = 
getLoadedRolesCache(jcasbinAuthorizer);
+    GravitinoCache<Long, Long> gatedLoadedRoles = Mockito.spy(loadedRoles);
+    doAnswer(
+            invocation -> {
+              Optional<Long> snapshot = loadedRoles.getIfPresent(roleId);
+              if (Thread.currentThread() == delayedThread.get()
+                  && firstDelayedRead.compareAndSet(true, false)) {
+                // Observe the missing marker, then stall until another 
request has loaded the
+                // role and removed its flight, so this request becomes a new 
owner.
+                observedStale.countDown();
+                assertTrue(previousLoadFinished.await(10, TimeUnit.SECONDS));
+              }
+              return snapshot;
+            })
+        .when(gatedLoadedRoles)
+        .getIfPresent(roleId);
+    Field loadedRolesField = 
JcasbinAuthorizer.class.getDeclaredField("loadedRoles");
+    loadedRolesField.setAccessible(true);
+    loadedRolesField.set(jcasbinAuthorizer, gatedLoadedRoles);
+
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> delayed =
+          workers.submit(
+              () -> {
+                delayedThread.set(Thread.currentThread());
+                return reloadRolesInWorker(
+                    ImmutableList.of(roleId), ImmutableMap.of(roleId, 
version));
+              });
+      assertTrue(observedStale.await(10, TimeUnit.SECONDS));
+      assertTrue(
+          workers
+              .submit(
+                  () ->
+                      reloadRolesInWorker(
+                          ImmutableList.of(roleId), ImmutableMap.of(roleId, 
version)))
+              .get(10, TimeUnit.SECONDS)
+              .isEmpty());
+      assertEquals(1, entityReads.get());
+      previousLoadFinished.countDown();
+
+      assertTrue(delayed.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(1, entityReads.get(), "a delayed owner must recheck the 
loaded marker");
+      assertEquals(version.getUpdatedAt(), 
loadedRoles.getIfPresent(roleId).orElse(null));
+      assertNoRolePolicyLoadStates();
+    } finally {
+      previousLoadFinished.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      loadedRolesField.set(jcasbinAuthorizer, loadedRoles);
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Attached waiters share an unreadable outcome, while a fresh request can 
retry. */
+  @Test
+  public void testFailedRoleReloadIsSharedAndNextRequestRetries() throws 
Exception {
+    long roleId = 9102L;
+    String roleName = "unreadableSingleFlightRole";
+    RoleEntity role = mockRoleInStore(roleId, roleName, 
ImmutableList.of(getDenySecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    NameIdentifier roleIdent = NameIdentifierUtil.ofRole(METALAKE, roleName);
+    List<NameIdentifier> roleIdents = ImmutableList.of(roleIdent);
+    int callers = 6;
+    CountDownLatch enteredRead = new CountDownLatch(1);
+    CountDownLatch releaseRead = new CountDownLatch(1);
+    CountDownLatch joined = new CountDownLatch(callers - 1);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined);
+    AtomicInteger batchReads = new AtomicInteger();
+    AtomicInteger individualReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              batchReads.incrementAndGet();
+              enteredRead.countDown();
+              assertTrue(releaseRead.await(10, TimeUnit.SECONDS));
+              return Collections.emptyList();
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              individualReads.incrementAndGet();
+              throw new IOException("role storage unavailable");
+            })
+        .when(entityStore)
+        .get(eq(roleIdent), eq(Entity.EntityType.ROLE), eq(RoleEntity.class));
+
+    ExecutorService workers = Executors.newFixedThreadPool(callers);
+    try {
+      List<Future<Set<Long>>> results = new ArrayList<>();
+      results.add(
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(ImmutableList.of(roleId), 
ImmutableMap.of(roleId, version))));
+      assertTrue(enteredRead.await(10, TimeUnit.SECONDS));
+      for (int i = 1; i < callers; i++) {
+        results.add(
+            workers.submit(
+                () ->
+                    reloadRolesInWorker(
+                        ImmutableList.of(roleId), ImmutableMap.of(roleId, 
version))));
+      }
+      assertTrue(joined.await(10, TimeUnit.SECONDS), "all waiters must join 
the blocked read");
+      releaseRead.countDown();
+      for (Future<Set<Long>> result : results) {
+        assertEquals(ImmutableSet.of(roleId), result.get(10, 
TimeUnit.SECONDS));
+      }
+      assertEquals(1, batchReads.get());
+      assertEquals(1, individualReads.get());
+      assertTrue(flights.isEmpty(), "failed flights must not prevent a later 
retry");
+      assertNoRolePolicyLoadStates();
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertTrue(
+          getDenyEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty());
+
+      doAnswer(
+              invocation -> {
+                individualReads.incrementAndGet();
+                return role;
+              })
+          .when(entityStore)
+          .get(eq(roleIdent), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer,
+                  METALAKE,
+                  ImmutableList.of(roleId),
+                  roleContext(ImmutableMap.of(roleId, version)))
+              .isEmpty());
+      assertEquals(2, batchReads.get());
+      assertEquals(2, individualReads.get());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+      assertEquals(
+          version.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty());
+    } finally {
+      releaseRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(role)
+          .when(entityStore)
+          .get(eq(roleIdent), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Blocking one role's storage read must not serialize an unrelated role's 
load. */
+  @Test
+  public void testBlockedRoleReloadDoesNotBlockAnotherRole() throws Exception {
+    long blockedId = 9103L;
+    long otherId = 9104L;
+    RoleEntity blockedRole =
+        mockRoleInStore(blockedId, "blockedRole", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity otherRole =
+        mockRoleInStore(otherId, "independentRole", 
ImmutableList.of(getDenySecurableObject()));
+    Map<Long, RoleUpdatedAt> versions =
+        ImmutableMap.of(
+            blockedId, mockedRoleVersions.get(blockedId),
+            otherId, mockedRoleVersions.get(otherId));
+    List<NameIdentifier> blockedIdents = 
ImmutableList.of(blockedRole.nameIdentifier());
+    List<NameIdentifier> otherIdents = 
ImmutableList.of(otherRole.nameIdentifier());
+    CountDownLatch enteredRead = new CountDownLatch(1);
+    CountDownLatch releaseRead = new CountDownLatch(1);
+    AtomicInteger otherReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              enteredRead.countDown();
+              assertTrue(releaseRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(blockedRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(blockedIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              otherReads.incrementAndGet();
+              return ImmutableList.of(otherRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(otherIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> blocked =
+          workers.submit(() -> 
reloadRolesInWorker(ImmutableList.of(blockedId), versions));
+      assertTrue(enteredRead.await(10, TimeUnit.SECONDS));
+      Future<Set<Long>> other =
+          workers.submit(() -> reloadRolesInWorker(ImmutableList.of(otherId), 
versions));
+      assertTrue(other.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(1, otherReads.get());
+      assertFalse(blocked.isDone(), "role A is still inside the explicitly 
blocked backend read");
+      
assertTrue(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(otherId).isPresent());
+      releaseRead.countDown();
+      assertTrue(blocked.get(10, TimeUnit.SECONDS).isEmpty());
+    } finally {
+      releaseRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(blockedIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(otherIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /**
+   * A newer complete version remains authoritative when an older load 
finishes later.
+   *
+   * @param expireOnSecondProbe whether a repeated old-worker marker probe 
would expire the entry
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testNewerRoleVersionDoesNotJoinOlderLoad(boolean 
expireOnSecondProbe)
+      throws Exception {
+    long roleId = 9105L;
+    String roleName = "changingSingleFlightRole";
+    RoleEntity oldRole =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity newRole =
+        getRoleEntity(roleId, roleName, 
ImmutableList.of(getDenySecurableObject()));
+    RoleUpdatedAt oldVersion = mockedRoleVersions.get(roleId);
+    RoleUpdatedAt newVersion = new RoleUpdatedAt(roleId, roleName, 
oldVersion.getUpdatedAt() + 1L);
+    List<NameIdentifier> roleIdents = 
ImmutableList.of(oldRole.nameIdentifier());
+    CountDownLatch enteredOldRead = new CountDownLatch(1);
+    CountDownLatch releaseOldRead = new CountDownLatch(1);
+    CountDownLatch enteredNewRead = new CountDownLatch(1);
+    CountDownLatch releaseNewRead = new CountDownLatch(1);
+    AtomicInteger reads = new AtomicInteger();
+    AtomicInteger oldMarkerProbes = new AtomicInteger();
+    AtomicReference<Thread> oldWorker = new AtomicReference<>();
+    GravitinoCache<Long, Long> loadedRoles = 
getLoadedRolesCache(jcasbinAuthorizer);
+    GravitinoCache<Long, Long> observedLoadedRoles = Mockito.spy(loadedRoles);
+    Field loadedRolesField = 
JcasbinAuthorizer.class.getDeclaredField("loadedRoles");
+    loadedRolesField.setAccessible(true);
+    doAnswer(
+            invocation -> {
+              int read = reads.incrementAndGet();
+              if (read == 1) {
+                enteredOldRead.countDown();
+                assertTrue(releaseOldRead.await(10, TimeUnit.SECONDS));
+                return ImmutableList.of(oldRole);
+              }
+              assertEquals(2, read, "each requested role version should have 
one read");
+              enteredNewRead.countDown();
+              assertTrue(releaseNewRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(newRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> older =
+          workers.submit(
+              () -> {
+                oldWorker.set(Thread.currentThread());
+                return reloadRolesInWorker(
+                    ImmutableList.of(roleId), ImmutableMap.of(roleId, 
oldVersion));
+              });
+      assertTrue(enteredOldRead.await(10, TimeUnit.SECONDS));
+      Future<Set<Long>> newer =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(
+                      ImmutableList.of(roleId), ImmutableMap.of(roleId, 
newVersion)));
+      assertTrue(
+          enteredNewRead.await(10, TimeUnit.SECONDS),
+          "a request for a newer version must not be satisfied by the older 
blocked flight");
+      releaseNewRead.countDown();
+      assertTrue(newer.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(
+          newVersion.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty());
+      doAnswer(
+              invocation -> {
+                Optional<Long> marker = loadedRoles.getIfPresent(roleId);
+                if (Thread.currentThread() == oldWorker.get()) {
+                  int probe = oldMarkerProbes.incrementAndGet();
+                  if (expireOnSecondProbe && probe == 2) {
+                    // A second replacement probe could run after expiry of 
the marker accepted
+                    // by the version-floor check. Obsolete work must skip 
replacement entirely.
+                    loadedRoles.invalidate(roleId);
+                    return Optional.empty();
+                  }
+                }
+                return marker;
+              })
+          .when(observedLoadedRoles)
+          .getIfPresent(roleId);
+      loadedRolesField.set(jcasbinAuthorizer, observedLoadedRoles);
+      releaseOldRead.countDown();
+      assertTrue(older.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(2, reads.get());
+      assertEquals(
+          newVersion.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).isEmpty(),
+          "a late old load must not replace the newer deny policy");
+      assertEquals(
+          1,
+          oldMarkerProbes.get(),
+          "obsolete work must not re-probe the newer marker in a replacement 
fast path");
+    } finally {
+      releaseOldRead.countDown();
+      releaseNewRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      loadedRolesField.set(jcasbinAuthorizer, loadedRoles);
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Opposite role-batch ownership must complete without a cross-flight 
waiting cycle. */
+  @Test
+  public void testOverlappingRoleBatchesCompleteOwnedLoadsBeforeWaiting() 
throws Exception {
+    long firstId = 9106L;
+    long secondId = 9107L;
+    RoleEntity firstRole =
+        mockRoleInStore(firstId, "overlappingFirst", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity secondRole =
+        mockRoleInStore(secondId, "overlappingSecond", 
ImmutableList.of(getDenySecurableObject()));
+    Map<Long, RoleUpdatedAt> versions =
+        ImmutableMap.of(
+            firstId, mockedRoleVersions.get(firstId),
+            secondId, mockedRoleVersions.get(secondId));
+    CountDownLatch joined = new CountDownLatch(2);
+    CountDownLatch ownersClaimed = new CountDownLatch(2);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined, ownersClaimed);
+    List<NameIdentifier> firstIdents = 
ImmutableList.of(firstRole.nameIdentifier());
+    List<NameIdentifier> secondIdents = 
ImmutableList.of(secondRole.nameIdentifier());
+    AtomicInteger firstReads = new AtomicInteger();
+    AtomicInteger secondReads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              firstReads.incrementAndGet();
+              return ImmutableList.of(firstRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(firstIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              secondReads.incrementAndGet();
+              return ImmutableList.of(secondRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(secondIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> first =
+          workers.submit(() -> reloadRolesInWorker(ImmutableList.of(firstId, 
secondId), versions));
+      Future<Set<Long>> second =
+          workers.submit(() -> reloadRolesInWorker(ImmutableList.of(secondId, 
firstId), versions));
+      assertTrue(first.get(10, TimeUnit.SECONDS).isEmpty());
+      assertTrue(second.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(0, ownersClaimed.getCount());
+      assertEquals(0, joined.getCount(), "each caller must join the role owned 
by the other");
+      assertEquals(1, firstReads.get());
+      assertEquals(1, secondReads.get());
+      assertTrue(flights.isEmpty());
+      
assertTrue(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(firstId).isPresent());
+      
assertTrue(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(secondId).isPresent());
+    } finally {
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(firstIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(secondIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Interrupting one follower preserves its status without cancelling the 
owner's work. */
+  @Test
+  public void testInterruptedRoleWaiterDoesNotCancelSharedLoad() throws 
Exception {
+    long roleId = 9108L;
+    RoleEntity role =
+        mockRoleInStore(
+            roleId, "interruptedWaiterRole", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    List<NameIdentifier> roleIdents = ImmutableList.of(role.nameIdentifier());
+    CountDownLatch enteredRead = new CountDownLatch(1);
+    CountDownLatch releaseRead = new CountDownLatch(1);
+    CountDownLatch joined = new CountDownLatch(1);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined);
+    AtomicInteger reads = new AtomicInteger();
+    AtomicReference<Thread> waiterThread = new AtomicReference<>();
+    doAnswer(
+            invocation -> {
+              reads.incrementAndGet();
+              enteredRead.countDown();
+              assertTrue(releaseRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(role);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> owner =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(ImmutableList.of(roleId), 
ImmutableMap.of(roleId, version)));
+      assertTrue(enteredRead.await(10, TimeUnit.SECONDS));
+      Future<Throwable> waiter =
+          workers.submit(
+              () -> {
+                waiterThread.set(Thread.currentThread());
+                try {
+                  reloadRolesInWorker(ImmutableList.of(roleId), 
ImmutableMap.of(roleId, version));
+                  throw new AssertionError("an interrupted waiter must report 
its failed wait");
+                } catch (InvocationTargetException e) {
+                  assertTrue(
+                      Thread.currentThread().isInterrupted(),
+                      "the failed wait must preserve the thread's interruption 
status");
+                  return e.getCause();
+                }
+              });
+      assertTrue(joined.await(10, TimeUnit.SECONDS));
+      waiterThread.get().interrupt();
+      Throwable failure = waiter.get(10, TimeUnit.SECONDS);
+      assertTrue(failure instanceof IllegalStateException);
+      assertTrue(failure.getCause() instanceof InterruptedException);
+      assertFalse(owner.isDone(), "the owner remains inside the explicitly 
blocked read");
+      assertEquals(1, flights.size());
+      assertFalse(flights.values().iterator().next().isCancelled());
+      releaseRead.countDown();
+      assertTrue(owner.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(1, reads.get());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+      assertEquals(
+          version.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+    } finally {
+      releaseRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /**
+   * Resolver failures reach all attached waiters and do not pin a failed 
flight.
+   *
+   * @param failWithError whether the resolver throws an Error instead of a 
RuntimeException
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testRoleResolutionFailureReachesWaitersAndAllowsRetry(boolean 
failWithError)
+      throws Exception {
+    long roleId = 9109L;
+    RoleEntity role =
+        mockRoleInStore(
+            roleId, "failedResolutionRole", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    List<NameIdentifier> roleIdents = ImmutableList.of(role.nameIdentifier());
+    Throwable resolutionFailure =
+        failWithError
+            ? new AssertionError("metadata resolution failed")
+            : new IllegalStateException("metadata resolution failed");
+    int callers = 4;
+    CountDownLatch enteredRead = new CountDownLatch(1);
+    CountDownLatch releaseRead = new CountDownLatch(1);
+    CountDownLatch joined = new CountDownLatch(callers - 1);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined);
+    AtomicInteger reads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              reads.incrementAndGet();
+              enteredRead.countDown();
+              assertTrue(releaseRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(role);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(callers);
+    try {
+      List<Future<Throwable>> results = new ArrayList<>();
+      for (int i = 0; i < callers; i++) {
+        results.add(
+            workers.submit(
+                () -> {
+                  try {
+                    reloadRolesInWorker(
+                        ImmutableList.of(roleId),
+                        ImmutableMap.of(roleId, version),
+                        resolutionFailure);
+                    throw new AssertionError(
+                        "a resolution failure must not be reported as 
success");
+                  } catch (InvocationTargetException e) {
+                    return e.getCause();
+                  }
+                }));
+        if (i == 0) {
+          assertTrue(enteredRead.await(10, TimeUnit.SECONDS));
+        }
+      }
+      assertTrue(joined.await(10, TimeUnit.SECONDS));
+      releaseRead.countDown();
+      for (Future<Throwable> result : results) {
+        assertSame(resolutionFailure, result.get(10, TimeUnit.SECONDS));
+      }
+      assertEquals(1, reads.get());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer,
+                  METALAKE,
+                  ImmutableList.of(roleId),
+                  roleContext(ImmutableMap.of(roleId, version)))
+              .isEmpty());
+      assertEquals(2, reads.get());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+      assertEquals(
+          version.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+    } finally {
+      releaseRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /**
+   * An explicit clear fences old work even when the database version has not 
changed.
+   *
+   * @param oldCompletesFirst whether the old load finishes while the new deny 
is still blocked
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testClearedRoleLoadCannotRepublishBeforeNewEpochDeny(boolean 
oldCompletesFirst)
+      throws Exception {
+    long roleId = 9110L;
+    String roleName = "clearedInFlightRole";
+    RoleEntity oldRole =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity newRole =
+        getRoleEntity(roleId, roleName, 
ImmutableList.of(getDenySecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    List<NameIdentifier> roleIdents = 
ImmutableList.of(oldRole.nameIdentifier());
+    AuthorizationRequestContext oldContext = 
roleContext(ImmutableMap.of(roleId, version));
+    oldContext.setBoundRoleIds(ImmutableList.of(roleId));
+    oldContext.setRolePolicyGeneration(0L);
+    CountDownLatch enteredOldRead = new CountDownLatch(1);
+    CountDownLatch releaseOldRead = new CountDownLatch(1);
+    CountDownLatch enteredNewRead = new CountDownLatch(1);
+    CountDownLatch releaseNewRead = new CountDownLatch(1);
+    AtomicInteger reads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              int read = reads.incrementAndGet();
+              if (read == 1) {
+                enteredOldRead.countDown();
+                assertTrue(releaseOldRead.await(10, TimeUnit.SECONDS));
+                return ImmutableList.of(oldRole);
+              }
+              assertEquals(2, read);
+              enteredNewRead.countDown();
+              assertTrue(releaseNewRead.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(newRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> older =
+          workers.submit(() -> reloadRolesInWorker(ImmutableList.of(roleId), 
oldContext, null));
+      assertTrue(enteredOldRead.await(10, TimeUnit.SECONDS));
+      jcasbinAuthorizer.handleRolePrivilegeChange(roleId);
+      Future<Set<Long>> newer =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(ImmutableList.of(roleId), 
ImmutableMap.of(roleId, version)));
+      assertTrue(
+          enteredNewRead.await(10, TimeUnit.SECONDS),
+          "the same database version after an explicit clear needs an 
independent flight");
+      if (oldCompletesFirst) {
+        releaseOldRead.countDown();
+        assertTrue(older.get(10, TimeUnit.SECONDS).isEmpty());
+        assertFalse(
+            
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent(),
+            "old work must not publish a loaded marker in the new clear 
epoch");
+        assertTrue(
+            getAllowEnforcer(jcasbinAuthorizer)
+                .getFilteredPolicy(0, String.valueOf(roleId))
+                .isEmpty(),
+            "the cleared allow must stay absent while the new deny is still 
loading");
+      }
+      releaseNewRead.countDown();
+      assertTrue(
+          newer.get(10, TimeUnit.SECONDS).isEmpty(),
+          "the new clear epoch must be able to install its deny policy");
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty());
+      releaseOldRead.countDown();
+      assertTrue(older.get(10, TimeUnit.SECONDS).isEmpty());
+      assertEquals(2, reads.get());
+      assertEquals(0L, oldContext.getRolePolicyGeneration());
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).isEmpty(),
+          "old same-version work must not replace the new clear epoch's deny 
policy");
+      assertFalse(
+          invokeAuthorizeByJcasbin(
+              jcasbinAuthorizer,
+              USER_ID,
+              METALAKE,
+              catalogObject(),
+              CATALOG_ID,
+              USE_CATALOG,
+              oldContext),
+          "the old request must revalidate its generation before evaluating 
the new deny");
+      assertTrue(oldContext.getRolePolicyGeneration() > 0L);
+      assertEquals(2, reads.get(), "revalidation can reuse the new epoch's 
loaded policy");
+    } finally {
+      releaseOldRead.countDown();
+      releaseNewRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** A missing role in a nonempty batch gets one shared fallback read and a 
retryable outcome. */
+  @Test
+  public void testMissingEntityInNonemptyBatchSharesFallbackFailure() throws 
Exception {
+    long readableId = 9111L;
+    long unreadableId = 9112L;
+    RoleEntity readable =
+        mockRoleInStore(readableId, "batchReadable", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity unreadable =
+        mockRoleInStore(
+            unreadableId, "batchUnreadable", 
ImmutableList.of(getDenySecurableObject()));
+    List<Long> roleIds = ImmutableList.of(readableId, unreadableId);
+    Map<Long, RoleUpdatedAt> versions =
+        ImmutableMap.of(
+            readableId, mockedRoleVersions.get(readableId),
+            unreadableId, mockedRoleVersions.get(unreadableId));
+    List<NameIdentifier> batchIdents =
+        ImmutableList.of(readable.nameIdentifier(), 
unreadable.nameIdentifier());
+    List<NameIdentifier> retryIdents = 
ImmutableList.of(unreadable.nameIdentifier());
+    int callers = 4;
+    CountDownLatch enteredBatch = new CountDownLatch(1);
+    CountDownLatch releaseBatch = new CountDownLatch(1);
+    CountDownLatch joined = new CountDownLatch((callers - 1) * 2);
+    Map<Object, CompletableFuture<Boolean>> flights = 
observeRoleLoadJoins(joined);
+    AtomicInteger batchReads = new AtomicInteger();
+    AtomicInteger readableGets = new AtomicInteger();
+    AtomicInteger unreadableGets = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              batchReads.incrementAndGet();
+              enteredBatch.countDown();
+              assertTrue(releaseBatch.await(10, TimeUnit.SECONDS));
+              return ImmutableList.of(readable);
+            })
+        .when(entityStore)
+        .batchGet(eq(batchIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              batchReads.incrementAndGet();
+              return Collections.emptyList();
+            })
+        .when(entityStore)
+        .batchGet(eq(retryIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              readableGets.incrementAndGet();
+              return readable;
+            })
+        .when(entityStore)
+        .get(eq(readable.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              unreadableGets.incrementAndGet();
+              throw new IOException("missing batch role temporarily 
unreadable");
+            })
+        .when(entityStore)
+        .get(eq(unreadable.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(callers);
+    try {
+      List<Future<Set<Long>>> results = new ArrayList<>();
+      results.add(workers.submit(() -> reloadRolesInWorker(roleIds, 
versions)));
+      assertTrue(enteredBatch.await(10, TimeUnit.SECONDS));
+      for (int i = 1; i < callers; i++) {
+        results.add(workers.submit(() -> reloadRolesInWorker(roleIds, 
versions)));
+      }
+      assertTrue(joined.await(10, TimeUnit.SECONDS));
+      releaseBatch.countDown();
+      for (Future<Set<Long>> result : results) {
+        assertEquals(ImmutableSet.of(unreadableId), result.get(10, 
TimeUnit.SECONDS));
+      }
+      assertEquals(1, batchReads.get());
+      assertEquals(0, readableGets.get(), "entities present in the batch need 
no fallback read");
+      assertEquals(1, unreadableGets.get());
+      assertTrue(flights.isEmpty());
+      
assertTrue(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(readableId).isPresent());
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(unreadableId).isPresent());
+      doAnswer(
+              invocation -> {
+                unreadableGets.incrementAndGet();
+                return unreadable;
+              })
+          .when(entityStore)
+          .get(eq(unreadable.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer, METALAKE, roleIds, roleContext(versions))
+              .isEmpty());
+      assertEquals(2, batchReads.get());
+      assertEquals(0, readableGets.get());
+      assertEquals(2, unreadableGets.get());
+      
assertTrue(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(unreadableId).isPresent());
+      assertTrue(flights.isEmpty());
+    } finally {
+      releaseBatch.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(batchIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(retryIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(readable)
+          .when(entityStore)
+          .get(eq(readable.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(unreadable)
+          .when(entityStore)
+          .get(eq(unreadable.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** A role dropped after its version probe loses the policies of its 
previous load. */
+  @Test
+  public void testRoleDroppedBeforeFallbackReadClearsItsPolicies() throws 
Exception {
+    long roleId = 9115L;
+    String roleName = "droppedDuringLoad";
+    RoleEntity role =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt loaded = mockedRoleVersions.get(roleId);
+    assertTrue(
+        invokeVersionCheckAndLoadRoles(
+                jcasbinAuthorizer,
+                METALAKE,
+                ImmutableList.of(roleId),
+                roleContext(ImmutableMap.of(roleId, loaded)))
+            .isEmpty());
+    assertFalse(
+        getAllowEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).isEmpty());
+
+    // The role changed and was then dropped, so the read that follows the 
probe finds nothing.
+    RoleUpdatedAt changed = new RoleUpdatedAt(roleId, roleName, 
nextRoleVersion());
+    Mockito.doThrow(new NoSuchEntityException("Role %s does not exist", 
roleName))
+        .when(entityStore)
+        .get(eq(role.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    try {
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer,
+                  METALAKE,
+                  ImmutableList.of(roleId),
+                  roleContext(ImmutableMap.of(roleId, changed)))
+              .isEmpty(),
+          "a dropped role has no policies, which is not a read failure");
+      assertTrue(
+          getAllowEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty(),
+          "the dropped role must not keep granting the privileges of its 
previous load");
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertNoRolePolicyLoadStates();
+    } finally {
+      Mockito.doReturn(role)
+          .when(entityStore)
+          .get(eq(role.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** A role recreated under its name after its version probe fails closed 
without loading. */
+  @Test
+  public void testRoleRecreatedUnderSameNameFailsClosed() throws Exception {
+    long roleId = 9116L;
+    long recreatedId = 9117L;
+    String roleName = "recreatedDuringLoad";
+    RoleEntity role =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity recreated =
+        getRoleEntity(recreatedId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    Mockito.doReturn(recreated)
+        .when(entityStore)
+        .get(eq(role.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    try {
+      assertEquals(
+          ImmutableSet.of(roleId),
+          invokeVersionCheckAndLoadRoles(
+              jcasbinAuthorizer,
+              METALAKE,
+              ImmutableList.of(roleId),
+              roleContext(ImmutableMap.of(roleId, 
mockedRoleVersions.get(roleId)))));
+      for (long id : ImmutableList.of(roleId, recreatedId)) {
+        assertTrue(
+            getAllowEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(id)).isEmpty(),
+            "neither the probed role nor the recreated one may receive the 
other's policies");
+        
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(id).isPresent());
+      }
+      assertNoRolePolicyLoadStates();
+    } finally {
+      Mockito.doReturn(role)
+          .when(entityStore)
+          .get(eq(role.nameIdentifier()), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /** Generation capture observes the map removal and pruning watermark as one 
publication. */
+  @Test
+  public void testRoleGenerationCaptureWaitsForPruningPublication() throws 
Exception {
+    long roleId = 9113L;
+    Field generationsField = 
JcasbinAuthorizer.class.getDeclaredField("roleClearGenerations");
+    generationsField.setAccessible(true);
+    @SuppressWarnings("unchecked")
+    Map<Long, Long> generations = (Map<Long, Long>) 
generationsField.get(jcasbinAuthorizer);
+    Field watermarkField = 
JcasbinAuthorizer.class.getDeclaredField("prunedRoleClearGeneration");
+    watermarkField.setAccessible(true);
+    Method capture =
+        JcasbinAuthorizer.class.getDeclaredMethod(
+            "retainRolePolicyLoadStates", List.class, List.class);
+    capture.setAccessible(true);
+    Method release =
+        
JcasbinAuthorizer.class.getDeclaredMethod("releaseRolePolicyLoadStates", 
List.class);
+    release.setAccessible(true);
+    ReentrantReadWriteLock policyLock = getRolePolicyLock(jcasbinAuthorizer);
+    CountDownLatch started = new CountDownLatch(1);
+    AtomicReference<Long> captured = new AtomicReference<>();
+    AtomicReference<Throwable> failure = new AtomicReference<>();
+    Thread reader =
+        new Thread(
+            () -> {
+              started.countDown();
+              try {
+                List<Long> leased = new ArrayList<>();
+                List<?> keys =
+                    (List<?>)
+                        capture.invoke(
+                            jcasbinAuthorizer,
+                            ImmutableList.of(new RoleUpdatedAt(roleId, 
"pruningRole", 1L)),
+                            leased);
+                Field generation = 
keys.get(0).getClass().getDeclaredField("clearGeneration");
+                generation.setAccessible(true);
+                captured.set(generation.getLong(keys.get(0)));
+                release.invoke(jcasbinAuthorizer, leased);
+              } catch (Throwable e) {
+                failure.set(e);
+              }
+            });
+    reader.setDaemon(true);
+    policyLock.writeLock().lock();
+    try {
+      generations.put(roleId, 10L);
+      watermarkField.setLong(jcasbinAuthorizer, 3L);
+      // Pause pruning after removal and before its watermark publication. 
Only a reader that
+      // respects the mutation lock can avoid the temporary fallback to the 
older watermark.
+      generations.remove(roleId);
+      reader.start();
+      assertTrue(started.await(10, TimeUnit.SECONDS));
+      assertTrue(
+          waitForBlockedGenerationCapture(reader),
+          "generation capture must block on the pruning write lock, not return 
the gap value");
+      assertNull(captured.get());
+      watermarkField.setLong(jcasbinAuthorizer, 20L);
+    } finally {
+      policyLock.writeLock().unlock();
+      reader.join(10000L);
+    }
+    assertFalse(reader.isAlive());
+    assertNull(failure.get());
+    assertEquals(20L, captured.get());
+    assertNoRolePolicyLoadStates();
+  }
+
+  /** Loaded-role cache probes must permit removal callbacks to acquire the 
policy write lock. */
+  @Test
+  public void testRoleReloadDoesNotProbeLoadedCacheUnderPolicyReadLock() 
throws Exception {
+    long roleId = 9114L;
+    mockRoleInStore(roleId, "cacheProbeLockRole", 
ImmutableList.of(getAllowSecurableObject()));
+    RoleUpdatedAt version = mockedRoleVersions.get(roleId);
+    GravitinoCache<Long, Long> loadedRoles = 
getLoadedRolesCache(jcasbinAuthorizer);
+    GravitinoCache<Long, Long> observedLoadedRoles = Mockito.spy(loadedRoles);
+    ReentrantReadWriteLock policyLock = getRolePolicyLock(jcasbinAuthorizer);
+    AtomicInteger probes = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              assertEquals(
+                  0,
+                  policyLock.getReadHoldCount(),
+                  "loaded-role cache maintenance may invoke a write-lock 
removal callback");
+              probes.incrementAndGet();
+              return loadedRoles.getIfPresent(invocation.getArgument(0));
+            })
+        .when(observedLoadedRoles)
+        .getIfPresent(anyLong());
+    Field loadedRolesField = 
JcasbinAuthorizer.class.getDeclaredField("loadedRoles");
+    loadedRolesField.setAccessible(true);
+    loadedRolesField.set(jcasbinAuthorizer, observedLoadedRoles);
+    try {
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer,
+                  METALAKE,
+                  ImmutableList.of(roleId),
+                  roleContext(ImmutableMap.of(roleId, version)))
+              .isEmpty());
+      assertTrue(probes.get() > 0);
+      assertEquals(version.getUpdatedAt(), 
loadedRoles.getIfPresent(roleId).orElse(null));
+    } finally {
+      loadedRolesField.set(jcasbinAuthorizer, loadedRoles);
+    }
+  }
+
+  /**
+   * An older complete flight must preserve a newer partial version's resolved 
deny policy.
+   *
+   * @param expireBackoff whether the partial-load backoff is removed before 
old work completes
+   */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testOlderCompleteLoadPreservesNewerPartialDeny(boolean 
expireBackoff)
+      throws Exception {
+    long roleId = 9115L;
+    String roleName = "olderCompleteNewerPartial";
+    String missingCatalog = "missingPartialCatalog";
+    RoleEntity oldRole =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity partialRole =
+        getRoleEntity(
+            roleId,
+            roleName,
+            ImmutableList.of(
+                getDenySecurableObject(),
+                buildSecurableObject(
+                    roleId, MetadataObject.Type.CATALOG, missingCatalog, 
USE_CATALOG, "ALLOW")));
+    RoleUpdatedAt oldVersion = mockedRoleVersions.get(roleId);
+    RoleUpdatedAt newVersion = new RoleUpdatedAt(roleId, roleName, 
oldVersion.getUpdatedAt() + 1L);
+    List<NameIdentifier> roleIdents = 
ImmutableList.of(oldRole.nameIdentifier());
+    CountDownLatch enteredOldRead = new CountDownLatch(1);
+    CountDownLatch releaseOldRead = new CountDownLatch(1);
+    AtomicInteger reads = new AtomicInteger();
+    doAnswer(
+            invocation -> {
+              int read = reads.incrementAndGet();
+              if (read == 1) {
+                enteredOldRead.countDown();
+                assertTrue(releaseOldRead.await(10, TimeUnit.SECONDS));
+                return ImmutableList.of(oldRole);
+              }
+              assertEquals(2, read);
+              return ImmutableList.of(partialRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> older =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(
+                      ImmutableList.of(roleId), ImmutableMap.of(roleId, 
oldVersion)));
+      assertTrue(enteredOldRead.await(10, TimeUnit.SECONDS));
+      Future<Set<Long>> newer =
+          workers.submit(
+              () ->
+                  reloadRoleWithMissingCatalogInWorker(
+                      ImmutableList.of(roleId),
+                      ImmutableMap.of(roleId, newVersion),
+                      missingCatalog));
+      assertTrue(newer.get(10, TimeUnit.SECONDS).isEmpty());
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertTrue(
+          
getPartialRoleLoadBackoffCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).isEmpty(),
+          "the newer partial load must publish the deny whose object 
resolved");
+      if (expireBackoff) {
+        getPartialRoleLoadBackoffCache(jcasbinAuthorizer).invalidate(roleId);
+      }
+      releaseOldRead.countDown();
+      Set<Long> olderOutcome = older.get(10, TimeUnit.SECONDS);
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer).getFilteredPolicy(0, 
String.valueOf(roleId)).isEmpty(),
+          "an older complete load must not clear the newer partial version's 
resolved deny");
+      assertFalse(
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent(),
+          "an older success must not mark the newer partial policy state as 
fully loaded");
+      assertEquals(
+          !expireBackoff,
+          
getPartialRoleLoadBackoffCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent(),
+          "version ordering must survive independently of the partial-load 
retry marker");
+      assertEquals(ImmutableSet.of(roleId), olderOutcome);
+      assertEquals(2, reads.get());
+      assertNoRolePolicyLoadStates();
+    } finally {
+      releaseOldRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
+  /**
+   * A failed newer read keeps older in-flight policies from publishing and 
permits a fresh retry.
+   */
+  @Test
+  public void testNewerReadFailurePreventsOlderPublicationUntilCallsFinish() 
throws Exception {
+    long roleId = 9116L;
+    String roleName = "newerReadFailedRole";
+    RoleEntity oldRole =
+        mockRoleInStore(roleId, roleName, 
ImmutableList.of(getAllowSecurableObject()));
+    RoleEntity recoveredRole =
+        getRoleEntity(roleId, roleName, 
ImmutableList.of(getDenySecurableObject()));
+    RoleUpdatedAt oldVersion = mockedRoleVersions.get(roleId);
+    RoleUpdatedAt newVersion = new RoleUpdatedAt(roleId, roleName, 
oldVersion.getUpdatedAt() + 1L);
+    NameIdentifier roleIdent = oldRole.nameIdentifier();
+    List<NameIdentifier> roleIdents = ImmutableList.of(roleIdent);
+    CountDownLatch enteredOldRead = new CountDownLatch(1);
+    CountDownLatch releaseOldRead = new CountDownLatch(1);
+    AtomicInteger batchReads = new AtomicInteger();
+    AtomicInteger pointReads = new AtomicInteger();
+    Map<Object, CompletableFuture<Boolean>> flights = observeRoleLoadJoins(new 
CountDownLatch(0));
+    doAnswer(
+            invocation -> {
+              int read = batchReads.incrementAndGet();
+              if (read == 1) {
+                enteredOldRead.countDown();
+                assertTrue(releaseOldRead.await(10, TimeUnit.SECONDS));
+                return ImmutableList.of(oldRole);
+              }
+              if (read == 2) {
+                return Collections.emptyList();
+              }
+              assertEquals(3, read);
+              return ImmutableList.of(recoveredRole);
+            })
+        .when(entityStore)
+        .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    doAnswer(
+            invocation -> {
+              pointReads.incrementAndGet();
+              throw new IOException("newer role read unavailable");
+            })
+        .when(entityStore)
+        .get(eq(roleIdent), eq(Entity.EntityType.ROLE), eq(RoleEntity.class));
+    ExecutorService workers = Executors.newFixedThreadPool(2);
+    try {
+      Future<Set<Long>> older =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(
+                      ImmutableList.of(roleId), ImmutableMap.of(roleId, 
oldVersion)));
+      assertTrue(enteredOldRead.await(10, TimeUnit.SECONDS));
+      Future<Set<Long>> newer =
+          workers.submit(
+              () ->
+                  reloadRolesInWorker(
+                      ImmutableList.of(roleId), ImmutableMap.of(roleId, 
newVersion)));
+      assertEquals(ImmutableSet.of(roleId), newer.get(10, TimeUnit.SECONDS));
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      releaseOldRead.countDown();
+      Set<Long> olderOutcome = older.get(10, TimeUnit.SECONDS);
+      assertTrue(
+          getAllowEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty(),
+          "the failed newer version must not permit an old allow to publish");
+      
assertFalse(getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).isPresent());
+      assertEquals(ImmutableSet.of(roleId), olderOutcome);
+      assertEquals(2, batchReads.get());
+      assertEquals(1, pointReads.get());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+
+      assertTrue(
+          invokeVersionCheckAndLoadRoles(
+                  jcasbinAuthorizer,
+                  METALAKE,
+                  ImmutableList.of(roleId),
+                  roleContext(ImmutableMap.of(roleId, newVersion)))
+              .isEmpty());
+      assertEquals(3, batchReads.get());
+      assertEquals(1, pointReads.get());
+      assertEquals(
+          newVersion.getUpdatedAt(),
+          
getLoadedRolesCache(jcasbinAuthorizer).getIfPresent(roleId).orElse(null));
+      assertFalse(
+          getDenyEnforcer(jcasbinAuthorizer)
+              .getFilteredPolicy(0, String.valueOf(roleId))
+              .isEmpty());
+      assertTrue(flights.isEmpty());
+      assertNoRolePolicyLoadStates();
+    } finally {
+      releaseOldRead.countDown();
+      workers.shutdownNow();
+      assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+      Mockito.doReturn(Collections.emptyList())
+          .when(entityStore)
+          .batchGet(eq(roleIdents), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+      Mockito.doReturn(oldRole)
+          .when(entityStore)
+          .get(eq(roleIdent), eq(Entity.EntityType.ROLE), 
eq(RoleEntity.class));
+    }
+  }
+
   @Test
   public void testConcurrentAuthorizationWaitsForPolicyReload() throws 
Exception {
     Principal currentPrincipal = PrincipalUtils.getCurrentPrincipal();
@@ -2296,7 +3666,8 @@ public class TestJcasbinAuthorizer {
   }
 
   /** Reflectively invoke the private versionCheckAndLoadRoles. */
-  private static void invokeVersionCheckAndLoadRoles(
+  @SuppressWarnings("unchecked")
+  private static Set<Long> invokeVersionCheckAndLoadRoles(
       JcasbinAuthorizer authorizer,
       String metalake,
       List<Long> roleIds,
@@ -2309,7 +3680,152 @@ public class TestJcasbinAuthorizer {
             List.class,
             AuthorizationRequestContext.class);
     m.setAccessible(true);
-    m.invoke(authorizer, metalake, roleIds, requestContext);
+    return (Set<Long>) m.invoke(authorizer, metalake, roleIds, requestContext);
+  }
+
+  /** Runs a real role reload with the thread-local bridges required by worker 
threads. */
+  private Set<Long> reloadRolesInWorker(
+      List<Long> roleIds, Map<Long, RoleUpdatedAt> prefetchedVersions) throws 
Exception {
+    return reloadRolesInWorker(roleIds, prefetchedVersions, null);
+  }
+
+  private Set<Long> reloadRolesInWorker(
+      List<Long> roleIds, Map<Long, RoleUpdatedAt> prefetchedVersions, 
Throwable metadataFailure)
+      throws Exception {
+    return reloadRolesInWorker(roleIds, roleContext(prefetchedVersions), 
metadataFailure);
+  }
+
+  private Set<Long> reloadRolesInWorker(
+      List<Long> roleIds, AuthorizationRequestContext requestContext, 
Throwable metadataFailure)
+      throws Exception {
+    try (MockedStatic<GravitinoEnv> env = mockStatic(GravitinoEnv.class);
+        MockedStatic<MetadataIdConverter> metadata =
+            mockStatic(
+                MetadataIdConverter.class,
+                invocation -> {
+                  String methodName = invocation.getMethod().getName();
+                  if (methodName.equals("getID") || 
methodName.equals("getIdForNormalizedObject")) {
+                    if (metadataFailure instanceof RuntimeException) {
+                      throw (RuntimeException) metadataFailure;
+                    }
+                    if (metadataFailure instanceof Error) {
+                      throw (Error) metadataFailure;
+                    }
+                    return Optional.of(CATALOG_ID);
+                  }
+                  return invocation.callRealMethod();
+                })) {
+      env.when(GravitinoEnv::getInstance).thenReturn(gravitinoEnv);
+      return invokeVersionCheckAndLoadRoles(jcasbinAuthorizer, METALAKE, 
roleIds, requestContext);
+    }
+  }
+
+  private Set<Long> reloadRoleWithMissingCatalogInWorker(
+      List<Long> roleIds, Map<Long, RoleUpdatedAt> prefetchedVersions, String 
missingCatalog)
+      throws Exception {
+    try (MockedStatic<GravitinoEnv> env = mockStatic(GravitinoEnv.class);
+        MockedStatic<MetadataIdConverter> metadata =
+            mockStatic(
+                MetadataIdConverter.class,
+                invocation -> {
+                  String methodName = invocation.getMethod().getName();
+                  if (methodName.equals("getID") || 
methodName.equals("getIdForNormalizedObject")) {
+                    Object object = invocation.getArgument(0);
+                    if (object instanceof MetadataObject
+                        && ((MetadataObject) 
object).fullName().equals(missingCatalog)) {
+                      return Optional.empty();
+                    }
+                    return Optional.of(CATALOG_ID);
+                  }
+                  return invocation.callRealMethod();
+                })) {
+      env.when(GravitinoEnv::getInstance).thenReturn(gravitinoEnv);
+      return invokeVersionCheckAndLoadRoles(
+          jcasbinAuthorizer, METALAKE, roleIds, 
roleContext(prefetchedVersions));
+    }
+  }
+
+  private static boolean waitForBlockedGenerationCapture(Thread reader) {
+    long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+    while (reader.isAlive() && System.nanoTime() < deadline) {
+      if (reader.getState() == Thread.State.WAITING
+          && Arrays.stream(reader.getStackTrace())
+              .anyMatch(
+                  frame ->
+                      
frame.getClassName().equals(JcasbinAuthorizer.class.getName())
+                          && 
frame.getMethodName().equals("retainRolePolicyLoadStates"))) {
+        return true;
+      }
+      Thread.yield();
+    }
+    return false;
+  }
+
+  private void assertNoRolePolicyLoadStates() throws Exception {
+    Field statesField = 
JcasbinAuthorizer.class.getDeclaredField("rolePolicyLoadStates");
+    statesField.setAccessible(true);
+    ReentrantReadWriteLock policyLock = getRolePolicyLock(jcasbinAuthorizer);
+    policyLock.readLock().lock();
+    try {
+      assertTrue(
+          ((Map<?, ?>) statesField.get(jcasbinAuthorizer)).isEmpty(),
+          "version-floor state must be released when all participating calls 
finish");
+    } finally {
+      policyLock.readLock().unlock();
+    }
+  }
+
+  private static AuthorizationRequestContext roleContext(
+      Map<Long, RoleUpdatedAt> prefetchedVersions) {
+    AuthorizationRequestContext context = new AuthorizationRequestContext();
+    context.setPrefetchedRoleVersions(prefetchedVersions);
+    return context;
+  }
+
+  private Map<Object, CompletableFuture<Boolean>> 
observeRoleLoadJoins(CountDownLatch joined)
+      throws Exception {
+    return observeRoleLoadJoins(joined, null);
+  }
+
+  private Map<Object, CompletableFuture<Boolean>> observeRoleLoadJoins(
+      CountDownLatch joined, CountDownLatch ownersClaimed) throws Exception {
+    ThreadLocal<Boolean> firstOwned = ThreadLocal.withInitial(() -> true);
+    Map<Object, CompletableFuture<Boolean>> flights =
+        new ConcurrentHashMap<Object, CompletableFuture<Boolean>>() {
+          private static final long serialVersionUID = 1L;
+
+          /** {@inheritDoc} */
+          @Override
+          public CompletableFuture<Boolean> putIfAbsent(
+              Object key, CompletableFuture<Boolean> candidate) {
+            CompletableFuture<Boolean> existing = super.putIfAbsent(key, 
candidate);
+            if (existing != null) {
+              joined.countDown();
+              if (ownersClaimed != null) {
+                try {
+                  assertTrue(joined.await(10, TimeUnit.SECONDS));
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new AssertionError(e);
+                }
+              }
+            } else if (ownersClaimed != null && firstOwned.get()) {
+              firstOwned.set(false);
+              ownersClaimed.countDown();
+              try {
+                assertTrue(ownersClaimed.await(10, TimeUnit.SECONDS));
+              } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                throw new AssertionError(e);
+              }
+            }
+            return existing;
+          }
+        };
+    Field flightsField = 
JcasbinAuthorizer.class.getDeclaredField("rolePolicyLoads");
+    flightsField.setAccessible(true);
+    flightsField.set(jcasbinAuthorizer, flights);
+    return flights;
   }
 
   /** Reflectively invoke the allow-side JCasbin authorization step. */

Reply via email to