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

github-actions[bot] pushed a commit to branch cherry-pick-de323140-to-branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit d8f45b5867e05f344bb6cac497edf557d0e912a5
Author: Qi Yu <[email protected]>
AuthorDate: Mon Nov 9 22:29:44 2026 +0800

    [#14420] fix(core): Keep a table create successful when a concurrent drop 
removes the table (#14787)
    
    ### What changes were proposed in this pull request?
    
    - `OwnerManager.setOwner` throws `NoSuchMetadataObjectException` when
    the store reports a missing entity and the owner still exists. If the
    owner is missing too, the existing `NotFoundException` is kept.
    - `TableHookDispatcher.createTable` catches only that exception, logs a
    warning, and returns the created table.
    
    No interface changes and no SQL changes.
    
    ### Why are the changes needed?
    
    With authorization enabled, the owner is set after the table is created.
    A concurrent drop can remove the table between the two steps. The create
    has succeeded, but the client gets a 404.
    
    Fixes #14420
    
    ### Does this PR introduce _any_ user-facing change?
    
    A create that races a drop now returns 200 instead of 404. `setOwner` on
    an object dropped during the call still returns 404, with the more
    specific `NoSuchMetadataObjectException` type.
    
    Known limits, unchanged by this PR:
    - The owner-exists check is heuristic. If the owner is also removed
    between the assignment failure and the check, create can still fail with
    the generic `NotFoundException`.
    - A late owner step can still overwrite the owner of a new table with
    the same name. Fixing this needs a table ID check.
    - Other create paths have the same race. See #14786.
    - Two soft deletes of one name in the same millisecond can still make a
    drop return 500.
    
    ### How was this patch tested?
    
    - Comment follow-up: 19 filtered cases passed (`TestOwnerManager`: 9,
    `TestTableHookDispatcher`: 10) via `:core:coreUnitTest --tests ...`;
    scoped Spotless passed. This follow-up changes only the explanatory
    comment.
    
    - Added unit tests in `TestOwnerManager` and `TestTableHookDispatcher`.
    - Real server with authorization on, H2 store, Iceberg memory backend, 8
    create and 8 drop clients on one name. Before: 313 of 600 creates
    returned 404. After: 0 of 600.
    - After 60 more race rounds, the table was always live and had an owner.
    # Conflicts:
    #       
core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
---
 .../gravitino/authorization/OwnerManager.java      |  18 +++
 .../apache/gravitino/hook/TableHookDispatcher.java |  21 ++-
 .../gravitino/authorization/TestOwnerManager.java  | 157 +++++++++++++++++++++
 .../gravitino/hook/TestTableHookDispatcher.java    |  43 ++++++
 4 files changed, 234 insertions(+), 5 deletions(-)

diff --git 
a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java 
b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
index af83b65806..700ada353f 100644
--- a/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
+++ b/core/src/main/java/org/apache/gravitino/authorization/OwnerManager.java
@@ -124,6 +124,13 @@ public class OwnerManager implements OwnerDispatcher {
               authorizationPlugin.onOwnerSet(metadataObject, 
originOwner.orElse(null), newOwner));
       notifyOwnerChange(originOwner.orElse(null), metalake, metadataObject);
     } catch (NoSuchEntityException nse) {
+      // The object existed when getOwner ran, so it can have been dropped 
since then. This
+      // owner-exists check is a heuristic: if the owner is also removed 
between the failure and
+      // this check, keep the generic NotFoundException; table creation can 
still fail in that race.
+      if (ownerExists(metalake, ownerName, ownerType)) {
+        throw new NoSuchMetadataObjectException(
+            nse, "The metadata object of %s isn't found", 
metadataObject.fullName());
+      }
       LOG.warn(
           "Metadata object {} or owner {} is not found", 
metadataObject.fullName(), ownerName, nse);
       throw new NotFoundException(
@@ -345,6 +352,17 @@ public class OwnerManager implements OwnerDispatcher {
     }
   }
 
+  private boolean ownerExists(String metalake, String ownerName, Owner.Type 
ownerType) {
+    try {
+      return ownerType == Owner.Type.USER
+          ? store.exists(AuthorizationUtils.ofUser(metalake, ownerName), 
Entity.EntityType.USER)
+          : store.exists(AuthorizationUtils.ofGroup(metalake, ownerName), 
Entity.EntityType.GROUP);
+    } catch (IOException ioe) {
+      LOG.warn("Failed to check whether owner {} exists", ownerName, ioe);
+      return false;
+    }
+  }
+
   private static class OwnerImpl implements Owner {
 
     private String name;
diff --git 
a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java 
b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java
index 76dc96d2ed..5f472804aa 100644
--- a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java
@@ -28,6 +28,7 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
 import org.apache.gravitino.authorization.Owner;
 import org.apache.gravitino.authorization.OwnerDispatcher;
 import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
 import org.apache.gravitino.exceptions.NoSuchSchemaException;
 import org.apache.gravitino.exceptions.NoSuchTableException;
 import org.apache.gravitino.exceptions.TableAlreadyExistsException;
@@ -40,6 +41,8 @@ import 
org.apache.gravitino.rel.expressions.transforms.Transform;
 import org.apache.gravitino.rel.indexes.Index;
 import org.apache.gravitino.utils.NameIdentifierUtil;
 import org.apache.gravitino.utils.PrincipalUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * {@code TableHookDispatcher} is a decorator for {@link TableDispatcher} that 
not only delegates
@@ -47,6 +50,8 @@ import org.apache.gravitino.utils.PrincipalUtils;
  * or after the underlying operations.
  */
 public class TableHookDispatcher implements TableDispatcher {
+  private static final Logger LOG = 
LoggerFactory.getLogger(TableHookDispatcher.class);
+
   private final TableDispatcher dispatcher;
   private final Supplier<OwnerDispatcher> ownerDispatcher;
 
@@ -91,11 +96,17 @@ public class TableHookDispatcher implements TableDispatcher 
{
     // Set the creator as the owner of the table.
     OwnerDispatcher ownerManager = ownerDispatcher.get();
     if (ownerManager != null) {
-      ownerManager.setOwner(
-          ident.namespace().level(0),
-          NameIdentifierUtil.toMetadataObject(ident, Entity.EntityType.TABLE),
-          PrincipalUtils.getCurrentUserName(),
-          Owner.Type.USER);
+      try {
+        ownerManager.setOwner(
+            ident.namespace().level(0),
+            NameIdentifierUtil.toMetadataObject(ident, 
Entity.EntityType.TABLE),
+            PrincipalUtils.getCurrentUserName(),
+            Owner.Type.USER);
+      } catch (NoSuchMetadataObjectException e) {
+        // The create has already committed and a concurrent drop removed the 
table, so the create
+        // still succeeded. There is no table left to own.
+        LOG.warn("Table {} was dropped before its owner could be set", ident, 
e);
+      }
     }
     return table;
   }
diff --git 
a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java 
b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
index 9bdb976327..98f822bd8e 100644
--- 
a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
+++ 
b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
@@ -56,10 +56,12 @@ import org.apache.gravitino.MetadataObject;
 import org.apache.gravitino.MetadataObjects;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.Namespace;
+import org.apache.gravitino.SupportsRelationOperations;
 import org.apache.gravitino.catalog.CatalogManager;
 import org.apache.gravitino.catalog.CatalogTestUtils;
 import org.apache.gravitino.connector.BaseCatalog;
 import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
 import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
 import org.apache.gravitino.exceptions.NotFoundException;
 import org.apache.gravitino.lock.LockManager;
@@ -290,4 +292,159 @@ public class TestOwnerManager {
           GravitinoEnv.getInstance(), "gravitinoAuthorizer", 
originalAuthorizer, true);
     }
   }
+<<<<<<< HEAD
+=======
+
+  @Test
+  @Order(5)
+  public void testInitialOwnerSetByBatchNotifiesAuthorizer()
+      throws IllegalAccessException, IOException {
+    String catalogName = "catalog_initial_owner_notify_batch";
+    AuditInfo audit = 
AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
+    CatalogEntity catalog =
+        CatalogEntity.builder()
+            .withId(idGenerator.nextId())
+            .withName(catalogName)
+            .withNamespace(Namespace.of(METALAKE))
+            .withType(Catalog.Type.RELATIONAL)
+            .withProvider("test")
+            .withAuditInfo(audit)
+            .build();
+    entityStore.put(catalog, false);
+
+    GravitinoAuthorizer authorizer = Mockito.mock(GravitinoAuthorizer.class);
+    GravitinoAuthorizer originalAuthorizer = 
GravitinoEnv.getInstance().gravitinoAuthorizer();
+    FieldUtils.writeField(GravitinoEnv.getInstance(), "gravitinoAuthorizer", 
authorizer, true);
+    try {
+      MetadataObject catalogObject =
+          MetadataObjects.of(Lists.newArrayList(catalogName), 
MetadataObject.Type.CATALOG);
+
+      ownerManager.setOwners(
+          METALAKE, Collections.singletonList(catalogObject), USER, 
Owner.Type.USER);
+
+      Mockito.verify(authorizer)
+          .handleMetadataOwnerChange(
+              Mockito.eq(METALAKE),
+              Mockito.isNull(),
+              Mockito.eq(NameIdentifier.of(METALAKE, catalogName)),
+              Mockito.eq(Entity.EntityType.CATALOG));
+    } finally {
+      FieldUtils.writeField(
+          GravitinoEnv.getInstance(), "gravitinoAuthorizer", 
originalAuthorizer, true);
+    }
+  }
+
+  @Test
+  @Order(6)
+  public void testConcurrentSetOwnerKeepsOneOwner() throws Exception {
+    MetadataObject catalogObject = createCatalog("catalog_owner_race");
+
+    for (int i = 0; i < 10; i++) {
+      List<Object> outcomes =
+          RaceTestUtils.runTogether(
+              Arrays.asList(
+                  () -> {
+                    ownerManager.setOwner(METALAKE, catalogObject, USER, 
Owner.Type.USER);
+                    return null;
+                  },
+                  () -> {
+                    ownerManager.setOwner(METALAKE, catalogObject, GROUP, 
Owner.Type.GROUP);
+                    return null;
+                  }));
+
+      outcomes.forEach(Assertions::assertNull);
+      // getOwner fails if more than one live owner row exists for the object.
+      Owner owner = ownerManager.getOwner(METALAKE, catalogObject).get();
+      Assertions.assertTrue(
+          (USER.equals(owner.name()) && owner.type() == Owner.Type.USER)
+              || (GROUP.equals(owner.name()) && owner.type() == 
Owner.Type.GROUP),
+          "Unexpected owner " + owner.name());
+    }
+  }
+
+  @Test
+  @Order(7)
+  public void testOwnerOperationsDoNotWaitForMetalakeTreeLock() throws 
Exception {
+    // Use a catalog of its own so the test does not depend on running after 
another one.
+    MetadataObject catalogObject = createCatalog("catalog_owner_lock_free");
+
+    // A metalake WRITE lock covers every principal and metadata object below 
it. Owner writes are
+    // fenced by the entity store, so none of them may wait for it.
+    try (TreeLockTestSupport.HeldLock metalakeWriter =
+        TreeLockTestSupport.HeldLock.acquire(NameIdentifier.of(METALAKE), 
LockType.WRITE)) {
+      TreeLockTestSupport.assertRunsConcurrentlyWith(
+          metalakeWriter,
+          () -> ownerManager.setOwner(METALAKE, catalogObject, USER, 
Owner.Type.USER));
+      TreeLockTestSupport.assertRunsConcurrentlyWith(
+          metalakeWriter,
+          () ->
+              ownerManager.setOwners(
+                  METALAKE, Collections.singletonList(catalogObject), GROUP, 
Owner.Type.GROUP));
+      TreeLockTestSupport.assertRunsConcurrentlyWith(
+          metalakeWriter, () -> ownerManager.getOwner(METALAKE, 
catalogObject));
+    }
+  }
+
+  @Test
+  @Order(8)
+  public void testSetOwnerReportsObjectDroppedDuringAssignment() throws 
IOException {
+    EntityStore store = storeFailingOwnerInsert();
+    Mockito.when(store.exists(AuthorizationUtils.ofUser(METALAKE, USER), 
Entity.EntityType.USER))
+        .thenReturn(true);
+    MetadataObject table = MetadataObjects.parse("c.s.t", 
MetadataObject.Type.TABLE);
+
+    Assertions.assertThrows(
+        NoSuchMetadataObjectException.class,
+        () -> new OwnerManager(store).setOwner(METALAKE, table, USER, 
Owner.Type.USER));
+  }
+
+  @Test
+  @Order(9)
+  public void testSetOwnerKeepsGenericNotFoundForMissingOwner() throws 
IOException {
+    EntityStore store = storeFailingOwnerInsert();
+    Mockito.when(store.exists(AuthorizationUtils.ofUser(METALAKE, USER), 
Entity.EntityType.USER))
+        .thenReturn(false);
+    MetadataObject table = MetadataObjects.parse("c.s.t", 
MetadataObject.Type.TABLE);
+
+    NotFoundException thrown =
+        Assertions.assertThrows(
+            NotFoundException.class,
+            () -> new OwnerManager(store).setOwner(METALAKE, table, USER, 
Owner.Type.USER));
+    Assertions.assertFalse(thrown instanceof NoSuchMetadataObjectException);
+  }
+
+  private static EntityStore storeFailingOwnerInsert() throws IOException {
+    EntityStore store =
+        Mockito.mock(
+            EntityStore.class,
+            
Mockito.withSettings().extraInterfaces(SupportsRelationOperations.class));
+    SupportsRelationOperations relations = (SupportsRelationOperations) store;
+    Mockito.when(store.relationOperations()).thenReturn(relations);
+    Mockito.doThrow(new NoSuchEntityException("The entity is gone"))
+        .when(relations)
+        .insertRelation(
+            Mockito.any(),
+            Mockito.any(),
+            Mockito.any(),
+            Mockito.any(),
+            Mockito.any(),
+            Mockito.anyBoolean());
+    return store;
+  }
+
+  private static MetadataObject createCatalog(String catalogName) throws 
IOException {
+    AuditInfo audit = 
AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
+    entityStore.put(
+        CatalogEntity.builder()
+            .withId(idGenerator.nextId())
+            .withName(catalogName)
+            .withNamespace(Namespace.of(METALAKE))
+            .withType(Catalog.Type.RELATIONAL)
+            .withProvider("test")
+            .withAuditInfo(audit)
+            .build(),
+        false);
+    return MetadataObjects.of(Lists.newArrayList(catalogName), 
MetadataObject.Type.CATALOG);
+  }
+>>>>>>> de3231404 ([#14420] fix(core): Keep a table create successful when a 
concurrent drop removes the table (#14787))
 }
diff --git 
a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java 
b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
index 6aff59c0e7..a85f9f3cfc 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java
@@ -41,6 +41,8 @@ import org.apache.gravitino.catalog.TableNormalizeDispatcher;
 import org.apache.gravitino.connector.BaseCatalog;
 import org.apache.gravitino.connector.capability.Capability;
 import org.apache.gravitino.connector.capability.CapabilityResult;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
+import org.apache.gravitino.exceptions.NotFoundException;
 import org.apache.gravitino.rel.Column;
 import org.apache.gravitino.rel.Table;
 import org.apache.gravitino.rel.TableChange;
@@ -201,6 +203,47 @@ public class TestTableHookDispatcher {
     assertEquals("Set owner failed", thrown.getMessage());
   }
 
+  @Test
+  public void testCreateTableSucceedsWhenTableDroppedBeforeOwnerSet() throws 
Exception {
+    OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
+    Mockito.doThrow(new NoSuchMetadataObjectException("The table is gone"))
+        .when(ownerDispatcher)
+        .setOwner(any(), any(), any(), any());
+    TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);
+    Table createdTable = Mockito.mock(Table.class);
+    Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), 
any(), any(), any()))
+        .thenReturn(createdTable);
+    TableHookDispatcher hook = new TableHookDispatcher(dispatcher, () -> 
ownerDispatcher);
+
+    assertSame(createdTable, createTable(hook));
+  }
+
+  @Test
+  public void testCreateTableThrowsWhenOwnerNotFound() throws Exception {
+    OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
+    Mockito.doThrow(new NotFoundException("The owner is missing"))
+        .when(ownerDispatcher)
+        .setOwner(any(), any(), any(), any());
+    TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);
+    Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), 
any(), any(), any()))
+        .thenReturn(Mockito.mock(Table.class));
+    TableHookDispatcher hook = new TableHookDispatcher(dispatcher, () -> 
ownerDispatcher);
+
+    assertThrows(NotFoundException.class, () -> createTable(hook));
+  }
+
+  private static Table createTable(TableHookDispatcher hook) {
+    return hook.createTable(
+        NameIdentifier.of(METALAKE, CATALOG, "schema", "table"),
+        new Column[0],
+        "comment",
+        ImmutableMap.of(),
+        new Transform[0],
+        Distributions.NONE,
+        new SortOrder[0],
+        new Index[0]);
+  }
+
   @Test
   public void testRenameAuthorizationPrivilege() {
     TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);

Reply via email to