World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14436] fix(core): Preserve table ownership when EXIST_OK returns an existing table (#14903)
Qi Yuc6e241670df3
diff --git a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.javaindex 44df60eabb..62a19062c1 100644--- a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java+++ b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedTable.java@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog;import java.util.Collections;import java.util.Map;+import java.util.OptionalLong;import java.util.Set;import org.apache.gravitino.Audit;import org.apache.gravitino.StringIdentifier;@@ -57,6 +58,10 @@ public final class EntityCombinedTable implements Table {// unique id, and based on this id, we can label and control the access to the entities.private boolean imported;+ // Present only when this create request inserted the metadata object. Loading an existing table+ // (including EXIST_OK) must never make its caller the owner, even if that table has no owner.+ private OptionalLong createdTableId = OptionalLong.empty();+// The columns to report instead of the catalog's, set only when the catalog reports none.private Column[] columnsOverride;@@ -98,6 +103,21 @@ public final class EntityCombinedTable implements Table {return this;}+ EntityCombinedTable withCreatedTableId(long id) {+ this.createdTableId = OptionalLong.of(id);+ return this;+ }++ /**+ * Returns the ID inserted by this create request, or empty for an existing table or a read. This+ * server-internal outcome is not a table property and is not serialized to clients.+ *+ * @return the newly created metadata object's ID, if this request created it+ */+ public OptionalLong createdTableId() {+ return createdTableId;+ }+MaskAndOmitKeys hiddenProperties() {return MaskAndOmitKeys.of(keysToMask, keysToOmit);}diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.javaindex 866d77dd2e..29521eaf88 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java@@ -29,6 +29,7 @@ import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Objects;import com.google.common.base.Preconditions;import com.google.common.collect.Lists;+import java.io.IOException;import java.time.Instant;import java.util.ArrayList;import java.util.Arrays;@@ -864,7 +865,34 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab// If the table is managed by Gravitino, we don't need to create TableEntity and store it again.if (catalogResult.managed) {- return EntityCombinedTable.of(table).withHiddenProperties(catalogResult.hiddenProperties);+ // ManagedTableOperations persists the server-issued ID on insertion and preserves the old+ // ID when returning an existing table. Inspect the unmasked snapshot: the public properties+ // omit this reserved identifier. Do not infer creation from the presence of an owner.+ StringIdentifier persistedId = StringIdentifier.fromProperties(table.properties());+ EntityCombinedTable result =+ EntityCombinedTable.of(table).withHiddenProperties(catalogResult.hiddenProperties);+ long persistedTableId;+ if (persistedId != null) {+ persistedTableId = persistedId.id();+ } else {+ // Custom managed connectors may omit reserved properties from their returned Table. Read+ // the stored identity in that case; absence or a replacement cannot prove this request+ // created the object. Never require an extra connector read after external creation.+ try {+ persistedTableId = store.get(ident, TABLE, TableEntity.class).id();+ } catch (NoSuchEntityException e) {+ return result;+ } catch (IOException e) {+ throw new GravitinoRuntimeException(+ e,+ "Table %s was returned by the catalog, but its stored creation identity could not be read. "+ + "Check the entity store before retrying or assigning ownership.",+ ident);+ }+ }+ return persistedTableId == catalogResult.id+ ? result.withCreatedTableId(catalogResult.id)+ : result;}AuditInfo audit =@@ -905,6 +933,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab// Merge both the metadata from catalog operation and the metadata from entity store.return EntityCombinedTable.of(table, tableEntity)+ .withCreatedTableId(tableEntity.id()).withHiddenProperties(catalogResult.hiddenProperties);}diff --git a/core/src/main/java/org/apache/gravitino/connector/capability/Capability.java b/core/src/main/java/org/apache/gravitino/connector/capability/Capability.javaindex 359ad24ee2..df5bf0a584 100644--- a/core/src/main/java/org/apache/gravitino/connector/capability/Capability.java+++ b/core/src/main/java/org/apache/gravitino/connector/capability/Capability.java@@ -126,6 +126,12 @@ public interface Capability {* data. For example, if a catalog storage is managed, when the catalog is dropped, Gravitino will* also delete all underlying data associated with the catalog.*+ * <p>For managed table storage, creating a new table must persist the server-supplied {@code+ * gravitino.identifier} as its entity ID. If creation returns an existing table, its stored ID+ * must be retained instead. Core uses these identities to distinguish creation from reuse before+ * assigning ownership. A connector may omit the reserved identifier from the returned table+ * properties if it is preserved in the entity store; core reads the stored ID in that case.+ ** @param scope The scope of the capability.* @return The capability of the managed storage.*/diff --git a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.javaindex 5bca74f82a..82e50be355 100644--- a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java@@ -18,8 +18,10 @@*/package org.apache.gravitino.hook;+import com.google.common.base.Preconditions;import java.util.List;import java.util.Map;+import java.util.OptionalLong;import java.util.function.Supplier;import org.apache.gravitino.Entity;import org.apache.gravitino.NameIdentifier;@@ -27,6 +29,7 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.catalog.EntityCombinedTable;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchSchemaException;@@ -96,14 +99,24 @@ public class TableHookDispatcher implements TableDispatcher {SortOrder[] sortOrders,Index[] indexes)throws NoSuchSchemaException, TableAlreadyExistsException {+ OwnerDispatcher ownerManager = ownerDispatcher.get();Table table =dispatcher.createTable(ident, columns, comment, properties, partitions, distribution, sortOrders, indexes);- // Set the creator as the owner of the table.- OwnerDispatcher ownerManager = ownerDispatcher.get();if (ownerManager != null) {+ Preconditions.checkState(+ table instanceof EntityCombinedTable,+ "Table %s was created, but the table dispatcher did not report whether this request "+ + "created it, so no owner was set. Set the owner explicitly.",+ ident);+ OptionalLong createdId = ((EntityCombinedTable) table).createdTableId();+ if (createdId.isEmpty()) {+ return table;+ }try {+ // Preserve the existing owner hook for actual creations. Identity-bound initialization+ // and its transfer/drop-recreate races are outside this EXIST_OK fix.ownerManager.setOwner(ident.namespace().level(0),NameIdentifierUtil.toMetadataObject(ident, Entity.EntityType.TABLE),diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestNormalizedOwnerOperations.java b/core/src/test/java/org/apache/gravitino/authorization/TestNormalizedOwnerOperations.javaindex a0de46e9eb..9f6016aa25 100644--- a/core/src/test/java/org/apache/gravitino/authorization/TestNormalizedOwnerOperations.java+++ b/core/src/test/java/org/apache/gravitino/authorization/TestNormalizedOwnerOperations.java@@ -31,6 +31,7 @@ import static org.mockito.Mockito.when;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.OptionalLong;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.Config;@@ -44,6 +45,7 @@ import org.apache.gravitino.cache.NoOpsCache;import org.apache.gravitino.catalog.CatalogDispatcher;import org.apache.gravitino.catalog.CatalogManager;import org.apache.gravitino.catalog.CatalogTestUtils;+import org.apache.gravitino.catalog.EntityCombinedTable;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.catalog.TableNormalizeDispatcher;import org.apache.gravitino.connector.BaseCatalog;@@ -52,6 +54,7 @@ import org.apache.gravitino.connector.capability.Capability;import org.apache.gravitino.connector.capability.CapabilityResult;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.hook.TableHookDispatcher;+import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;@@ -185,8 +188,11 @@ class TestNormalizedOwnerOperations extends TestJDBCBackend {void testQuotedCreateHookDoesNotNormalizeStoredNameAgain() throws Exception {NameIdentifier stored = putQuotedTable();TableDispatcher source = mock(TableDispatcher.class);+ EntityCombinedTable created = mock(EntityCombinedTable.class);+ long createdId = store.get(stored, Entity.EntityType.TABLE, TableEntity.class).id();+ when(created.createdTableId()).thenReturn(OptionalLong.of(createdId));when(source.createTable(any(), any(), any(), any(), any(), any(), any(), any()))- .thenReturn(mock(Table.class));+ .thenReturn(created);TableDispatcher tables =new TableNormalizeDispatcher(new TableHookDispatcher(source, () -> manager), catalogs);tables.createTable(diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.javaindex 0e6c237547..e967ba1258 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java@@ -69,10 +69,13 @@ import org.apache.gravitino.EntityFieldLimits;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.TestCatalog;import org.apache.gravitino.TestColumn;import org.apache.gravitino.TestTable;import org.apache.gravitino.auth.AuthConstants;+import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.connector.GenericTable;import org.apache.gravitino.connector.HiddenPropertyMaskUtils;import org.apache.gravitino.connector.TestCatalogOperations;import org.apache.gravitino.connector.capability.Capability;@@ -84,6 +87,7 @@ import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;+import org.apache.gravitino.hook.TableHookDispatcher;import org.apache.gravitino.lock.LockManager;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.meta.AuditInfo;@@ -523,6 +527,183 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {Assertions.assertEquals(1, tableOperationDispatcher.loadTable(ident).columns().length);}+ @Test+ void testManagedCreateOutcomeSkipsConcurrentExistOkOwnerInitialization() throws Exception {+ Namespace ns = Namespace.of(metalake, catalog, "managed_create_outcome");+ Map<String, String> props = Map.of("k1", "v1", "k2", "v2");+ schemaOperationDispatcher.createSchema(NameIdentifier.of(ns.levels()), "", props);+ NameIdentifier ident = NameIdentifier.of(ns, "t");+ TestCatalog source =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations originalOps = (TestCatalogOperations) source.ops();+ TestCatalogOperations operations = spy(originalOps);+ Capability originalCapability = source.capability();+ Capability managed =+ new Capability() {+ @Override+ public CapabilityResult managedStorage(Scope scope) {+ return scope == Scope.TABLE+ ? CapabilityResult.SUPPORTED+ : originalCapability.managedStorage(scope);+ }+ };+ doAnswer(+ invocation -> {+ try {+ return originalOps.loadTable(ident);+ } catch (NoSuchTableException e) {+ return invocation.callRealMethod();+ }+ })+ .when(operations)+ .createTable(eq(ident), any(), any(), any(), any(), any(), any(), any());+ FieldUtils.writeField(source, "capability", managed, true);+ FieldUtils.writeField(source, "ops", operations, true);+ OwnerDispatcher owners = mock(OwnerDispatcher.class);+ CountDownLatch initializing = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ doAnswer(+ invocation -> {+ initializing.countDown();+ Assertions.assertTrue(release.await(30, TimeUnit.SECONDS));+ return null;+ })+ .when(owners)+ .setOwner(any(), any(), any(), any());+ TableHookDispatcher hook = new TableHookDispatcher(tableOperationDispatcher, () -> owners);+ ExecutorService executor = Executors.newSingleThreadExecutor();+ try {+ Future<Table> first =+ executor.submit(() -> hook.createTable(ident, new Column[0], "", props));+ Assertions.assertTrue(initializing.await(30, TimeUnit.SECONDS));+ // The table exists, but its creator has not initialized ownership. A second create returning+ // it must not try to claim it, even though an owner lookup would still return empty.+ EntityCombinedTable existing =+ (EntityCombinedTable) hook.createTable(ident, new Column[0], "", props);+ Assertions.assertTrue(existing.createdTableId().isEmpty());+ Assertions.assertFalse(existing.properties().containsKey(ID_KEY));+ release.countDown();+ EntityCombinedTable created = (EntityCombinedTable) first.get(30, TimeUnit.SECONDS);+ long id = StringIdentifier.fromProperties(originalOps.loadTable(ident).properties()).id();+ Assertions.assertEquals(id, created.createdTableId().orElseThrow());+ verify(owners, times(1)).setOwner(eq(metalake), any(), any(), any());+ verify(owners, never()).getOwner(any(), any());+ } finally {+ release.countDown();+ executor.shutdownNow();+ Assertions.assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));+ FieldUtils.writeField(source, "capability", originalCapability, true);+ FieldUtils.writeField(source, "ops", originalOps, true);+ }+ }++ @Test+ void testManagedCreateWithoutReturnedIdentifierUsesStoredIdentity() throws Exception {+ Namespace ns = Namespace.of(metalake, catalog, "managed_sanitized_create");+ Map<String, String> props = Map.of("k1", "v1", "k2", "v2");+ schemaOperationDispatcher.createSchema(NameIdentifier.of(ns.levels()), "", props);+ NameIdentifier ident = NameIdentifier.of(ns, "t");+ TestCatalog source =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations originalOps = (TestCatalogOperations) source.ops();+ TestCatalogOperations operations = spy(originalOps);+ Capability originalCapability = source.capability();+ Capability managed =+ new Capability() {+ @Override+ public CapabilityResult managedStorage(Scope scope) {+ return scope == Scope.TABLE+ ? CapabilityResult.SUPPORTED+ : originalCapability.managedStorage(scope);+ }+ };+ doAnswer(+ invocation -> {+ Table table;+ try {+ table = originalOps.loadTable(ident);+ } catch (NoSuchTableException e) {+ table = (Table) invocation.callRealMethod();+ TableEntity entity =+ TableEntity.builder()+ .withId(StringIdentifier.fromProperties(table.properties()).id())+ .withName(ident.name())+ .withNamespace(ns)+ .withProperties(table.properties())+ .withColumns(List.of())+ .withAuditInfo(AuditInfo.EMPTY)+ .build();+ entityStore.put(entity, false);+ }+ // A valid managed connector can drop the identifier from its returned table and keep+ // it in storage. The same result is used for a new table and for EXIST_OK.+ return GenericTable.builder()+ .withName(table.name())+ .withColumns(new Column[0])+ .withPartitioning(new Transform[0])+ .withDistribution(Distributions.NONE)+ .withSortOrders(new SortOrder[0])+ .withIndexes(Indexes.EMPTY_INDEXES)+ .withProperties(StringIdentifier.newPropertiesWithoutId(table.properties()))+ .withAuditInfo(AuditInfo.EMPTY)+ .build();+ })+ .when(operations)+ .createTable(eq(ident), any(), any(), any(), any(), any(), any(), any());+ FieldUtils.writeField(source, "capability", managed, true);+ FieldUtils.writeField(source, "ops", operations, true);+ OwnerDispatcher owners = mock(OwnerDispatcher.class);+ TableHookDispatcher hook = new TableHookDispatcher(tableOperationDispatcher, () -> owners);+ try {+ EntityCombinedTable created =+ (EntityCombinedTable) hook.createTable(ident, new Column[0], "", props);+ long createdId = entityStore.get(ident, TABLE, TableEntity.class).id();+ Assertions.assertEquals(createdId, created.createdTableId().orElseThrow());+ Assertions.assertTrue(+ ((EntityCombinedTable) hook.createTable(ident, new Column[0], "", props))+ .createdTableId()+ .isEmpty());+ verify(owners, times(1)).setOwner(eq(metalake), any(), any(), any());++ // A replacement observed by the fallback belongs to another request.+ TableEntity replacement =+ TableEntity.builder()+ .withId(idGenerator.nextId())+ .withName(ident.name())+ .withNamespace(ns)+ .withColumns(List.of())+ .withAuditInfo(AuditInfo.EMPTY)+ .build();+ entityStore.delete(ident, TABLE);+ entityStore.put(replacement, false);+ Assertions.assertTrue(+ ((EntityCombinedTable) hook.createTable(ident, new Column[0], "", props))+ .createdTableId()+ .isEmpty());+ entityStore.delete(ident, TABLE);+ Assertions.assertTrue(+ ((EntityCombinedTable) hook.createTable(ident, new Column[0], "", props))+ .createdTableId()+ .isEmpty());+ verify(owners, times(1)).setOwner(any(), any(), any(), any());++ IOException failure = new IOException("entity store unavailable");+ doThrow(failure).when(entityStore).get(ident, TABLE, TableEntity.class);+ GravitinoRuntimeException error =+ Assertions.assertThrows(+ GravitinoRuntimeException.class,+ () -> hook.createTable(ident, new Column[0], "", props));+ Assertions.assertSame(failure, error.getCause());+ Assertions.assertTrue(error.getMessage().contains(ident.toString()));+ verify(owners, times(1)).setOwner(any(), any(), any(), any());+ } finally {+ FieldUtils.writeField(source, "capability", originalCapability, true);+ FieldUtils.writeField(source, "ops", originalOps, true);+ }+ }+@Testpublic void testCreateAndListTables() throws IOException {Namespace tableNs = Namespace.of(metalake, catalog, "schema41");@@ -547,6 +728,9 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {Table table1 =tableOperationDispatcher.createTable(tableIdent1, columns, "comment", props, new Transform[0]);+ Assertions.assertEquals(+ entityStore.get(tableIdent1, TABLE, TableEntity.class).id(),+ ((EntityCombinedTable) table1).createdTableId().orElseThrow());Assertions.assertEquals("table1", table1.name());Assertions.assertEquals("comment", table1.comment());testProperties(props, table1.properties());diff --git a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.javaindex a85f9f3cfc..dbd3665f44 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestTableHookDispatcher.java@@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.eq;import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import java.util.List;+import java.util.OptionalLong;import org.apache.gravitino.Entity;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;@@ -36,6 +37,7 @@ import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.catalog.CatalogManager;import org.apache.gravitino.catalog.CatalogTestUtils;+import org.apache.gravitino.catalog.EntityCombinedTable;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.catalog.TableNormalizeDispatcher;import org.apache.gravitino.connector.BaseCatalog;@@ -120,7 +122,7 @@ public class TestTableHookDispatcher {OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);- Table createdTable = Mockito.mock(Table.class);+ Table createdTable = createdTable();Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(createdTable);TableDispatcher hook =@@ -151,7 +153,7 @@ public class TestTableHookDispatcher {public void testCreateTableSkipsOwnerWhenAuthorizationDisabled() {CatalogManager catalogManager = Mockito.mock(CatalogManager.class);TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);- Table createdTable = Mockito.mock(Table.class);+ Table createdTable = createdTable();Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(createdTable);TableHookDispatcher hook = new TableHookDispatcher(dispatcher, () -> null);@@ -178,8 +180,9 @@ public class TestTableHookDispatcher {.when(ownerDispatcher).setOwner(any(), any(), any(), any());TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);+ Table created = createdTable();Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any()))- .thenReturn(Mockito.mock(Table.class));+ .thenReturn(created);CatalogManager catalogManager = Mockito.mock(CatalogManager.class);BaseCatalog<?> catalog = Mockito.mock(BaseCatalog.class);Mockito.when(catalog.capability()).thenReturn(Capability.DEFAULT);@@ -210,7 +213,7 @@ public class TestTableHookDispatcher {.when(ownerDispatcher).setOwner(any(), any(), any(), any());TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);- Table createdTable = Mockito.mock(Table.class);+ Table createdTable = createdTable();Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(createdTable);TableHookDispatcher hook = new TableHookDispatcher(dispatcher, () -> ownerDispatcher);@@ -225,13 +228,32 @@ public class TestTableHookDispatcher {.when(ownerDispatcher).setOwner(any(), any(), any(), any());TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);+ Table created = createdTable();Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any()))- .thenReturn(Mockito.mock(Table.class));+ .thenReturn(created);TableHookDispatcher hook = new TableHookDispatcher(dispatcher, () -> ownerDispatcher);assertThrows(NotFoundException.class, () -> createTable(hook));}+ @Test+ public void testExistingTableDoesNotInitializeOwner() {+ OwnerDispatcher owners = Mockito.mock(OwnerDispatcher.class);+ TableDispatcher dispatcher = Mockito.mock(TableDispatcher.class);+ EntityCombinedTable existing = EntityCombinedTable.of(Mockito.mock(Table.class));+ Mockito.when(dispatcher.createTable(any(), any(), any(), any(), any(), any(), any(), any()))+ .thenReturn(existing);+ assertSame(existing, createTable(new TableHookDispatcher(dispatcher, () -> owners)));+ Mockito.verify(owners, Mockito.never()).getOwner(any(), any());+ Mockito.verify(owners, Mockito.never()).setOwner(any(), any(), any(), any());+ }++ private static EntityCombinedTable createdTable() {+ EntityCombinedTable table = Mockito.mock(EntityCombinedTable.class);+ Mockito.when(table.createdTableId()).thenReturn(OptionalLong.of(42L));+ return table;+ }+private static Table createTable(TableHookDispatcher hook) {return hook.createTable(NameIdentifier.of(METALAKE, CATALOG, "schema", "table"),diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestTableEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestTableEvent.javaindex b2f34a9b08..5807c981d8 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestTableEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestTableEvent.java@@ -22,14 +22,17 @@ package org.apache.gravitino.listener.api.event;import static org.mockito.Mockito.any;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.spy;import static org.mockito.Mockito.when;import com.google.common.collect.ImmutableMap;import java.util.Arrays;import java.util.Map;+import java.util.OptionalLong;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.catalog.EntityCombinedTable;import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.exceptions.GravitinoRuntimeException;import org.apache.gravitino.hook.TableHookDispatcher;@@ -121,9 +124,13 @@ public class TestTableEvent {doThrow(new RuntimeException("Set owner failed")).when(ownerDispatcher).setOwner(any(), any(), any(), any());+ TableDispatcher source = mockTableDispatcher();+ EntityCombinedTable created = spy(EntityCombinedTable.of(table));+ when(created.createdTableId()).thenReturn(OptionalLong.of(1L));+ when(source.createTable(any(), any(), any(), any(), any(), any(), any(), any()))+ .thenReturn(created);TableEventDispatcher dispatcherWithHook =- new TableEventDispatcher(- eventBus, new TableHookDispatcher(mockTableDispatcher(), () -> ownerDispatcher));+ new TableEventDispatcher(eventBus, new TableHookDispatcher(source, () -> ownerDispatcher));NameIdentifier identifier = NameIdentifier.of("metalake", "catalog", "schema", table.name());RuntimeException thrown =diff --git a/docs/lakehouse-generic-lance-table.md b/docs/lakehouse-generic-lance-table.mdindex 02cdcc6579..c8a713f1de 100644--- a/docs/lakehouse-generic-lance-table.md+++ b/docs/lakehouse-generic-lance-table.md@@ -140,6 +140,20 @@ blob columns stored as `External(arrow_field_json_str)` keep that form instead o`External("lance.blob.legacy")`.:::+### Ownership with `EXIST_OK`++You can use `lance.creation-mode=EXIST_OK` with the Gravitino table API and with Lance REST.++- If the table already exists, Gravitino returns it and keeps its owner. This is also true when+ the table has no owner.+- If another request is still creating the table, the `EXIST_OK` request does not set the owner.+ The creator sets it.+- If the request creates a new table, the caller becomes the owner when authorization is enabled.++Gravitino creates the table and sets the owner in two separate steps. If the table is created but+setting the owner fails, a repeated `EXIST_OK` request does not fix the owner. Fix the cause, then+set the owner explicitly.+### Table PropertiesRequired and optional properties for tables in a Generic Lakehouse Catalog:diff --git a/docs/lance-rest-service.md b/docs/lance-rest-service.mdindex 490258d419..53f1acd054 100644--- a/docs/lance-rest-service.md+++ b/docs/lance-rest-service.md@@ -414,8 +414,10 @@ Schema owners additionally need `USE_CATALOG`, and table owners need `USE_CATALO`CREATE_TABLE` and `PROBE_TABLE_LIKE` authorize `TableExists` without authorizing`DescribeTable`. `CREATE_TABLE` alone does not authorize overwrite requests. The `DropTable`and `DeregisterTable` endpoints require ownership rather than `MODIFY_TABLE`. Similarly, namespace creation privileges do not authorize-overwriting or dropping another owner's namespace. Successful creation assigns ownership to-the effective caller.+overwriting or dropping another owner's namespace. Creating a new table assigns ownership to+the effective caller. `exist_ok` returning an existing table preserves its owner, even if no owner+has been assigned. This also applies to direct Gravitino table creation with+`lance.creation-mode=EXIST_OK`.### Listings and concealed objectsdiff --git a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.javaindex cfcbc129b0..471dd34bd2 100644--- a/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java+++ b/lance/lance-rest-server/src/test/java/org/apache/gravitino/lance/integration/test/LanceTableAuthorizationIT.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.lance.integration.test;+import java.io.File;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;@@ -44,6 +45,7 @@ import org.apache.gravitino.authorization.Owner;import org.apache.gravitino.authorization.Privileges;import org.apache.gravitino.authorization.SecurableObject;import org.apache.gravitino.authorization.SecurableObjects;+import org.apache.gravitino.client.GravitinoAdminClient;import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.integration.test.util.BaseIT;import org.apache.gravitino.lance.common.utils.ArrowUtils;@@ -97,6 +99,8 @@ public class LanceTableAuthorizationIT extends BaseIT {private static final String OWNED_SCHEMA_TABLE = "h_owned_schema_table";private static final String LONE_SCHEMA_TABLE = "i_lone_schema_table";private static final String NON_LANCE_TABLE = "j_non_lance_table";+ private static final String EXIST_OK_TABLE = "k_exist_ok_table";+ private static final String EXIST_OK_NEW_TABLE = "l_exist_ok_new_table";private static final String DELIMITER = ".";@TempDir private static Path tempDir;@@ -129,6 +133,7 @@ public class LanceTableAuthorizationIT extends BaseIT {registerTable(VISIBLE_TABLE);registerTable(HIDDEN_TABLE);createTable(WRITE_SCHEMA, MUTABLE_TABLE);+ createTable(WRITE_SCHEMA, EXIST_OK_TABLE);Catalog catalog = metalake.loadCatalog(CATALOG);catalog.asTableCatalog()@@ -310,6 +315,90 @@ public class LanceTableAuthorizationIT extends BaseIT {Assertions.assertEquals(location(HIDDEN_TABLE), describedLocation(ADMIN, HIDDEN_TABLE));}+ @Test+ public void testExistOkCreateKeepsTheExistingOwner() throws Exception {+ // The prober may create tables in the write schema but cannot read or remove this one.+ assertStatus(403, table(PROBER, WRITE_SCHEMA, EXIST_OK_TABLE, "describe"));++ // The response still carries the existing table's metadata; authorizing that is #12955.+ assertStatus(200, createTable(PROBER, WRITE_SCHEMA, EXIST_OK_TABLE, "exist_ok"));++ // exist_ok returned the existing table without creating it, so its owner is unchanged and the+ // prober still cannot read or remove it.+ Owner owner =+ client+ .loadMetalake(getLanceRESTServerMetalakeName())+ .getOwner(+ MetadataObjects.of(+ List.of(CATALOG, WRITE_SCHEMA, EXIST_OK_TABLE), MetadataObject.Type.TABLE))+ .orElseThrow();+ Assertions.assertEquals(ADMIN, owner.name());+ assertStatus(403, table(PROBER, WRITE_SCHEMA, EXIST_OK_TABLE, "describe"));+ assertStatus(403, table(PROBER, WRITE_SCHEMA, EXIST_OK_TABLE, "drop"));+ Assertions.assertTrue(new File(location(EXIST_OK_TABLE)).exists());+ }++ @Test+ public void testExistOkCreateOfMissingTableMakesTheCallerTheOwner() throws Exception {+ assertStatus(200, createTable(PROBER, WRITE_SCHEMA, EXIST_OK_NEW_TABLE, "exist_ok"));++ Owner owner =+ client+ .loadMetalake(getLanceRESTServerMetalakeName())+ .getOwner(+ MetadataObjects.of(+ List.of(CATALOG, WRITE_SCHEMA, EXIST_OK_NEW_TABLE), MetadataObject.Type.TABLE))+ .orElseThrow();+ Assertions.assertEquals(PROBER, owner.name());+ assertStatus(200, table(PROBER, WRITE_SCHEMA, EXIST_OK_NEW_TABLE, "describe"));+ }++ @Test+ public void testNativeExistOkKeepsExistingOwnerAndInitializesNewTable() throws Exception {+ try (GravitinoAdminClient prober =+ GravitinoAdminClient.builder(serverUri).withSimpleAuth(PROBER).build()) {+ GravitinoMetalake metalake = prober.loadMetalake(getLanceRESTServerMetalakeName());+ Catalog catalog = metalake.loadCatalog(CATALOG);+ Map<String, String> properties =+ Map.of(+ Table.PROPERTY_TABLE_FORMAT, "lance",+ Table.PROPERTY_LOCATION, location("native_exist_ok"),+ LanceConstants.LANCE_CREATION_MODE, "EXIST_OK",+ LanceConstants.LANCE_TABLE_DECLARED, "true");+ Table existing =+ catalog+ .asTableCatalog()+ .createTable(+ NameIdentifier.of(WRITE_SCHEMA, EXIST_OK_TABLE), new Column[0], null, properties);+ Assertions.assertEquals(+ location(EXIST_OK_TABLE), existing.properties().get(Table.PROPERTY_LOCATION));+ MetadataObject existingObject =+ MetadataObjects.of(+ List.of(CATALOG, WRITE_SCHEMA, EXIST_OK_TABLE), MetadataObject.Type.TABLE);+ Assertions.assertEquals(+ ADMIN,+ client+ .loadMetalake(getLanceRESTServerMetalakeName())+ .getOwner(existingObject)+ .orElseThrow()+ .name());+ assertStatus(403, table(PROBER, WRITE_SCHEMA, EXIST_OK_TABLE, "drop"));++ String newTable = "native_exist_ok_new";+ catalog+ .asTableCatalog()+ .createTable(NameIdentifier.of(WRITE_SCHEMA, newTable), new Column[0], null, properties);+ MetadataObject newObject =+ MetadataObjects.of(List.of(CATALOG, WRITE_SCHEMA, newTable), MetadataObject.Type.TABLE);+ Assertions.assertEquals(PROBER, metalake.getOwner(newObject).orElseThrow().name());+ // The same owner can repeat the request too; EXIST_OK does not become an ownership check.+ catalog+ .asTableCatalog()+ .createTable(NameIdentifier.of(WRITE_SCHEMA, newTable), new Column[0], null, properties);+ Assertions.assertEquals(PROBER, metalake.getOwner(newObject).orElseThrow().name());+ }+ }+@Testpublic void testColumnMutationRequiresModifyTable() throws Exception {// The reader holds USE_CATALOG, USE_SCHEMA and SELECT_TABLE on this exact table, so it can@@ -507,18 +596,26 @@ public class LanceTableAuthorizationIT extends BaseIT {}private void createTable(String schemaName, String tableName) throws Exception {+ assertStatus(200, createTable(ADMIN, schemaName, tableName, null));+ }++ private HttpResponse<String> createTable(+ String user, String schemaName, String tableName, String mode) throws Exception {Schema schema =new Schema(List.of(Field.nullable("id", new ArrowType.Int(32, true)),Field.nullable("value", new ArrowType.Utf8())));HttpRequest request =- request(ADMIN, "/v1/table/" + id(CATALOG, schemaName, tableName) + "/create", "")+ request(+ user,+ "/v1/table/" + id(CATALOG, schemaName, tableName) + "/create",+ mode == null ? "" : "&mode=" + mode).setHeader("Content-Type", "application/vnd.apache.arrow.stream").setHeader(LanceConstants.LANCE_TABLE_LOCATION_HEADER, location(tableName)).POST(HttpRequest.BodyPublishers.ofByteArray(ArrowUtils.generateIpcStream(schema))).build();- assertStatus(200, httpClient.send(request, HttpResponse.BodyHandlers.ofString()));+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());}private HttpResponse<String> registerExistingTable(String user, String schema, String tableName)