World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14468] perf(iceberg-rest): record creators in the initial entity import (#14540)
roryqidf58cf7cb9b1
diff --git a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedSchema.java b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedSchema.javaindex c4314ea914..44fc923537 100644--- a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedSchema.java+++ b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedSchema.java@@ -85,6 +85,10 @@ public final class EntityCombinedSchema implements Schema {return this;}+ MaskAndOmitKeys hiddenProperties() {+ return MaskAndOmitKeys.of(keysToMask, keysToOmit);+ }+@Overridepublic String name() {return schema.name();diff --git a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.javaindex 51e4e15488..6f4f13bfbc 100644--- a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java+++ b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java@@ -77,6 +77,10 @@ public final class EntityCombinedView implements View {return this;}+ MaskAndOmitKeys hiddenProperties() {+ return MaskAndOmitKeys.of(keysToMask, keysToOmit);+ }+@Overridepublic Column[] columns() {return view.columns();diff --git a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.javaindex 683f9d57d1..dd0486318d 100644--- a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java@@ -23,6 +23,10 @@ import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifierimport com.google.common.collect.Maps;import java.util.Map;+import java.util.function.BiFunction;+import javax.annotation.Nullable;+import org.apache.gravitino.Audit;+import org.apache.gravitino.Auditable;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.HasIdentifier;@@ -38,6 +42,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.file.FilesetChange;import org.apache.gravitino.messaging.TopicChange;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.model.ModelChange;import org.apache.gravitino.model.ModelVersionChange;import org.apache.gravitino.rel.SupportsPartitions;@@ -83,6 +88,75 @@ public abstract class OperationDispatcher {this.secretManager = secretManager;}+ /**+ * Fills missing creation fields when another node imported the same object first. The cold import+ * already carries these fields in its initial write and needs no additional update. Ordinary+ * loads pass an empty requested audit, leaving an unknown source creator unknown.+ *+ * @param entity the imported registration, or null for a managed object+ * @param type the entity class+ * @param reported the audit reported by the source catalog+ * @param requested the creation audit supplied by the create operation, or empty for ordinary+ * loads+ * @param withAudit copies the current entity with the new audit+ * @param <E> the auditable entity type+ * @return the current registration, with missing creation fields filled if it still matches, or+ * null if the registration disappeared during recovery; callers then return the source+ * snapshot as not imported+ */+ @Nullable+ protected <E extends Entity & HasIdentifier & Auditable> E fillMissingCreationAudit(+ @Nullable E entity,+ Class<E> type,+ Audit reported,+ AuditInfo requested,+ BiFunction<E, AuditInfo, E> withAudit) {+ if (entity == null || entity.auditInfo().creator() != null || requested.creator() == null) {+ return entity;+ }+ try {+ return store.update(+ entity.nameIdentifier(),+ type,+ entity.type(),+ current -> {+ // Recheck inside the store's optimistic update, including identity: the name may+ // have been dropped and recreated since the source snapshot was read.+ if (!current.id().equals(entity.id())) {+ throw new OptimisticLockException("Entity identity changed during audit import");+ }+ Audit audit = current.auditInfo();+ if (audit.creator() != null) {+ return current;+ }+ AuditInfo filled =+ AuditInfo.builder()+ .withCreator(+ reported.creator() == null ? requested.creator() : reported.creator())+ .withCreateTime(+ audit.createTime() != null+ ? audit.createTime()+ : reported.createTime() != null+ ? reported.createTime()+ : requested.createTime())+ .withLastModifier(audit.lastModifier())+ .withLastModifiedTime(audit.lastModifiedTime())+ .build();+ return withAudit.apply(current, filled);+ });+ } catch (NoSuchEntityException e) {+ // A rename or drop can remove the observed registration before the store read or CAS.+ // Return the source snapshot without a registration; never resurrect it with the old audit.+ return null;+ } catch (OptimisticLockException e) {+ LOG.warn("Failed to import creation audit for {}", entity.nameIdentifier(), e);+ return getEntity(entity.nameIdentifier(), entity.type(), type);+ } catch (Exception e) {+ LOG.warn("Failed to import creation audit for {}", entity.nameIdentifier(), e);+ return entity;+ }+ }+protected <R, E extends Throwable> R doWithTable(NameIdentifier tableIdent, ThrowableFunction<SupportsPartitions, R> fn, Class<E> ex)throws E {diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.javaindex f09eca41f2..f3ede7d48d 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java@@ -25,7 +25,9 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Schema;import org.apache.gravitino.connector.SupportsSchemas;import org.apache.gravitino.exceptions.NoSuchCatalogException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;@@ -89,4 +91,17 @@ public interface SchemaDispatcher extends SupportsSchemas {throws NoSuchCatalogException, SchemaAlreadyExistsException {throw new UnsupportedOperationException("Creating a schema with secrets is not supported");}++ /**+ * Imports an externally created schema into Gravitino, or returns the already imported entity.+ * Catalog-reported audit fields take precedence over the supplied audit. Existing nonempty+ * creation fields are preserved; missing creation fields may be filled after a competing import.+ * This operation does not create the schema in the underlying catalog.+ *+ * @param ident the identifier of the existing external schema+ * @param auditInfo fallback creation audit used when the catalog reports no creator+ * @return the imported schema+ * @throws NoSuchSchemaException if the external schema does not exist+ */+ Schema importSchema(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchSchemaException;}diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.javaindex 149c6fc3b4..20e23b32bf 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaNormalizeDispatcher.java@@ -36,6 +36,7 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;@@ -52,6 +53,13 @@ public class SchemaNormalizeDispatcher implements SchemaDispatcher {this.catalogManager = catalogManager;}+ /** {@inheritDoc} */+ @Override+ public Schema importSchema(NameIdentifier ident, AuditInfo auditInfo)+ throws NoSuchSchemaException {+ return dispatcher.importSchema(normalizeCaseSensitive(ident), auditInfo);+ }+@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {// A namespace with more than two levels ([metalake, catalog]) carries a parentSchema, i.e. thediff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.javaindex 1125b1c044..670c1ef380 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java@@ -24,6 +24,7 @@ import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validateProimport static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;import static org.apache.gravitino.utils.NameIdentifierUtil.ofFileset;+import com.google.common.base.Preconditions;import java.io.IOException;import java.time.Instant;import java.util.Collections;@@ -310,35 +311,15 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc*/@Overridepublic Schema loadSchema(NameIdentifier ident) throws NoSuchSchemaException {- // Load the schema and check if this schema is already imported.- EntityCombinedSchema schema =- TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadSchema(ident));-- if (!schema.imported()) {- try {- TreeLockUtils.doWithTreeLock(- NameIdentifier.of(ident.namespace().levels()),- LockType.WRITE,- () -> {- importSchema(ident);- return null;- });- } catch (EntityAlreadyExistsException e) {- // HA race: another Gravitino node concurrently imported this schema. Reload from the- // entity store to verify the entity stored by the winning node is consistent.- LOG.info(- "Schema {} was concurrently imported by another node; reloading from store.", ident);- EntityCombinedSchema reloaded =- TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadSchema(ident));- if (!reloaded.imported()) {- throw new UnsupportedOperationException(- "Schema managed by multiple catalogs. This may cause unexpected issues such as privilege conflicts. "- + "To resolve: Remove all catalogs managing this schema, then recreate one catalog to ensure single-catalog management.");- }- }- }+ return loadAndImportSchema(ident, AuditInfo.EMPTY);+ }- return schema;+ /** {@inheritDoc} */+ @Override+ public Schema importSchema(NameIdentifier ident, AuditInfo auditInfo)+ throws NoSuchSchemaException {+ Preconditions.checkArgument(auditInfo != null, "auditInfo must not be null");+ return loadAndImportSchema(ident, auditInfo);}/**@@ -676,10 +657,61 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Screturn newProps;}- private void importSchema(NameIdentifier identifier) {+ private Schema loadAndImportSchema(NameIdentifier ident, AuditInfo importAudit)+ throws NoSuchSchemaException {+ // Load the schema and check if this schema is already imported.+ EntityCombinedSchema schema =+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadSchema(ident));++ if (!schema.imported()) {+ try {+ schema =+ TreeLockUtils.doWithTreeLock(+ NameIdentifier.of(ident.namespace().levels()),+ LockType.WRITE,+ () -> importSchemaFromCatalog(ident, importAudit));+ } catch (EntityAlreadyExistsException e) {+ // HA race: another Gravitino node concurrently imported this schema. Reload from the+ // entity store to verify the entity stored by the winning node is consistent.+ LOG.info(+ "Schema {} was concurrently imported by another node; reloading from store.", ident);+ EntityCombinedSchema reloaded =+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadSchema(ident));+ if (!reloaded.imported()) {+ throw new UnsupportedOperationException(+ "Schema managed by multiple catalogs. This may cause unexpected issues such as "+ + "privilege conflicts. To resolve: Remove all catalogs managing this schema, "+ + "then recreate one catalog to ensure single-catalog management.");+ }+ schema = reloaded;+ }+ }++ SchemaEntity entity =+ fillMissingCreationAudit(+ schema.schemaEntity(),+ SchemaEntity.class,+ schema.schema().auditInfo(),+ importAudit,+ (current, audit) ->+ SchemaEntity.builder()+ .withId(current.id())+ .withName(current.name())+ .withNamespace(current.namespace())+ .withComment(current.comment())+ .withProperties(current.properties())+ .withAuditInfo(audit)+ .build());+ return EntityCombinedSchema.of(schema.schema(), entity)+ .withHiddenProperties(schema.hiddenProperties())+ .withImported(schema.imported() && (schema.schemaEntity() == null || entity != null));+ }++ private EntityCombinedSchema importSchemaFromCatalog(+ NameIdentifier identifier, AuditInfo importAudit) {EntityCombinedSchema schema = internalLoadSchema(identifier);if (schema.imported()) {- return;+ return schema;}StringIdentifier stringId = null;@@ -734,6 +766,17 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc}}+ AuditInfo audit =+ AuditInfo.builder()+ .withCreator(schema.auditInfo().creator())+ .withCreateTime(schema.auditInfo().createTime())+ .withLastModifier(schema.auditInfo().lastModifier())+ .withLastModifiedTime(schema.auditInfo().lastModifiedTime())+ .build();+ if (audit.creator() == null) {+ audit = audit.merge(importAudit, false /* overwrite */);+ }+// Persist source properties, not the masked client view, so a recovered registration retains// secret URNs. The EntityCombinedSchema returned to the caller still applies masking.Map<String, String> sourceProperties =@@ -760,13 +803,7 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc.withName(identifier.name()).withNamespace(identifier.namespace()).withProperties(sourceProperties)- .withAuditInfo(- AuditInfo.builder()- .withCreator(schema.auditInfo().creator())- .withCreateTime(schema.auditInfo().createTime())- .withLastModifier(schema.auditInfo().lastModifier())- .withLastModifiedTime(schema.auditInfo().lastModifiedTime())- .build())+ .withAuditInfo(audit).build();try {if (previousEntity == null) {@@ -793,6 +830,9 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements ScLOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", identifier, e);throw new RuntimeException("Failed to import schema entity to the store", e);}+ return EntityCombinedSchema.of(schema.schema(), schemaEntity)+ .withHiddenProperties(schema.hiddenProperties())+ .withImported(true);}private EntityCombinedSchema internalLoadSchema(NameIdentifier ident) {diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableDispatcher.javaindex 88bddad679..d37441c28c 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableDispatcher.java@@ -19,6 +19,10 @@package org.apache.gravitino.catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;/**@@ -27,4 +31,18 @@ import org.apache.gravitino.rel.TableCatalog;* dispatching or handling table-related events or actions that are not covered by the standard* {@code TableCatalog} operations.*/-public interface TableDispatcher extends TableCatalog {}+public interface TableDispatcher extends TableCatalog {+ /**+ * Imports an externally created table into Gravitino, or returns the already imported entity.+ * Catalog-reported audit fields take precedence over the supplied audit. Existing nonempty+ * creation fields are preserved; missing creation fields may be filled after a competing import.+ * Loading also refreshes changed columns and their modification audit. This operation does not+ * create the table in the underlying catalog.+ *+ * @param ident the identifier of the existing external table+ * @param auditInfo fallback creation audit used when the catalog reports no creator+ * @return the imported table+ * @throws NoSuchTableException if the external table does not exist+ */+ Table importTable(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchTableException;+}diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableNormalizeDispatcher.javaindex 2f766588eb..bb359c6874 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableNormalizeDispatcher.java@@ -32,6 +32,7 @@ import org.apache.gravitino.connector.capability.CapabilityResult;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;@@ -53,6 +54,13 @@ public class TableNormalizeDispatcher implements TableDispatcher {this.dispatcher = dispatcher;}+ /** {@inheritDoc} */+ @Override+ public Table importTable(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchTableException {+ return dispatcher.importTable(+ resolvePhysicalTableName(normalizeCaseSensitive(ident), catalogManager), auditInfo);+ }+@Overridepublic NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {// The constraints of the name spec may be more strict than underlying catalog,diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.javaindex 091170ab09..866d77dd2e 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java@@ -46,6 +46,7 @@ import java.util.stream.Collectors;import java.util.stream.IntStream;import javax.annotation.Nullable;import org.apache.commons.lang3.tuple.Pair;+import org.apache.gravitino.Audit;import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;@@ -181,55 +182,14 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab*/@Overridepublic Table loadTable(NameIdentifier ident) throws NoSuchTableException {- EntityCombinedTable entityCombinedTable =- TreeLockUtils.doWithTreeLock(- ident,- LockType.READ,- () -> {- // A cold external table will be loaded under its own WRITE lock below. Do not- // fetch it here only to discard the snapshot and fetch it again during import.- // Managed catalogs do not need the external import path, even without a store row.- if (getEntity(ident, TABLE, TableEntity.class) == null- && !isManagedEntity(getCatalogIdentifier(ident), Capability.Scope.TABLE)) {- return null;- }- return internalLoadTable(ident);- });-- if (entityCombinedTable == null || !entityCombinedTable.imported()) {- // Load the schema to make sure the schema is imported.- SchemaDispatcher schemaDispatcher = getSchemaDispatcher();- NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());- schemaDispatcher.loadSchema(schemaIdent);-- // Import under the table lock: the source snapshot and store write exclude local changes- // to this table, while sibling tables remain available. Ancestor READ locks still exclude- // schema drop/rename. Never reuse a snapshot read before acquiring this lock.- try {- entityCombinedTable =- TreeLockUtils.doWithTreeLock(ident, LockType.WRITE, () -> importTable(ident));- } catch (EntityAlreadyExistsException e) {- // HA race: another Gravitino node concurrently imported this table. Reload from the- // entity store to pick up the entity stored by the winning node.- LOG.info(- "Table {} was concurrently imported by another node; reloading from store.", ident);- entityCombinedTable =- TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadTable(ident));- if (!entityCombinedTable.imported()) {- throw new UnsupportedOperationException(- "Table managed by multiple catalogs. This may cause unexpected issues such as privilege conflicts. "- + "To resolve: Remove all catalogs managing this table, then recreate one catalog to ensure single-catalog management.");- }- }- }-- // Update the column entities in Gravitino store if the columns are different from the ones- // fetching from the underlying source.- TableEntity updatedEntity = updateColumnsIfNecessaryWhenLoad(ident, entityCombinedTable);+ return loadAndImportTable(ident, AuditInfo.EMPTY);+ }- return EntityCombinedTable.of(entityCombinedTable.tableFromCatalog(), updatedEntity)- .withHiddenProperties(entityCombinedTable.hiddenProperties())- .withImported(entityCombinedTable.imported());+ /** {@inheritDoc} */+ @Override+ public Table importTable(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchTableException {+ Preconditions.checkArgument(auditInfo != null, "auditInfo must not be null");+ return loadAndImportTable(ident, auditInfo);}/**@@ -608,7 +568,118 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab}}- private EntityCombinedTable importTable(NameIdentifier identifier) {+ private Table loadAndImportTable(NameIdentifier ident, AuditInfo importAudit)+ throws NoSuchTableException {+ EntityCombinedTable entityCombinedTable =+ TreeLockUtils.doWithTreeLock(+ ident,+ LockType.READ,+ () -> {+ // A cold external table will be loaded under its own WRITE lock below. Do not+ // fetch it here only to discard the snapshot and fetch it again during import.+ // Managed catalogs do not need the external import path, even without a store row.+ if (getEntity(ident, TABLE, TableEntity.class) == null+ && !isManagedEntity(getCatalogIdentifier(ident), Capability.Scope.TABLE)) {+ return null;+ }+ return internalLoadTable(ident);+ });++ if (entityCombinedTable == null || !entityCombinedTable.imported()) {+ // Load the schema to make sure the schema is imported.+ SchemaDispatcher schemaDispatcher = getSchemaDispatcher();+ NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());+ schemaDispatcher.loadSchema(schemaIdent);++ // Import under the table lock: the source snapshot and store write exclude local changes+ // to this table, while sibling tables remain available. Ancestor READ locks still exclude+ // schema drop/rename. Never reuse a snapshot read before acquiring this lock.+ try {+ entityCombinedTable =+ TreeLockUtils.doWithTreeLock(+ ident, LockType.WRITE, () -> importTableFromCatalog(ident, importAudit));+ } catch (EntityAlreadyExistsException e) {+ // HA race: another Gravitino node concurrently imported this table. Reload from the+ // entity store to pick up the entity stored by the winning node.+ LOG.info(+ "Table {} was concurrently imported by another node; reloading from store.", ident);+ entityCombinedTable =+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadTable(ident));+ if (!entityCombinedTable.imported()) {+ throw new UnsupportedOperationException(+ "Table managed by multiple catalogs. This may cause unexpected issues such as "+ + "privilege conflicts. To resolve: Remove all catalogs managing this table, "+ + "then recreate one catalog to ensure single-catalog management.");+ }+ }+ }++ // Update the column entities in Gravitino store if the columns are different from the ones+ // fetching from the underlying source.+ TableEntity updatedEntity = updateColumnsIfNecessaryWhenLoad(ident, entityCombinedTable);+ updatedEntity =+ fillMissingCreationAudit(+ updatedEntity,+ TableEntity.class,+ entityCombinedTable.tableFromCatalog().auditInfo(),+ importAudit,+ (current, audit) ->+ TableEntity.builder()+ .withId(current.id())+ .withName(current.name())+ .withNamespace(current.namespace())+ .withComment(current.comment())+ .withProperties(current.properties())+ .withColumns(fillMissingColumnCreationAudit(current.columns(), audit))+ .withPartitioning(current.partitioning())+ .withDistribution(current.distribution())+ .withSortOrders(current.sortOrders())+ .withIndexes(current.indexes())+ .withAuditInfo(audit)+ .build());++ return EntityCombinedTable.of(entityCombinedTable.tableFromCatalog(), updatedEntity)+ .withHiddenProperties(entityCombinedTable.hiddenProperties())+ .withImported(+ entityCombinedTable.imported()+ && (entityCombinedTable.tableFromGravitino() == null || updatedEntity != null));+ }++ private static List<ColumnEntity> fillMissingColumnCreationAudit(+ List<ColumnEntity> columns, AuditInfo tableAudit) {+ return columns.stream()+ .map(+ column -> {+ Audit audit = column.auditInfo();+ if (audit.creator() != null) {+ return column;+ }+ return ColumnEntity.builder()+ .withId(column.id())+ .withName(column.name())+ .withPosition(column.position())+ .withDataType(column.dataType())+ .withComment(column.comment())+ .withNullable(column.nullable())+ .withAutoIncrement(column.autoIncrement())+ .withDefaultValue(column.defaultValue())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator(tableAudit.creator())+ .withCreateTime(+ audit.createTime() == null+ ? tableAudit.createTime()+ : audit.createTime())+ .withLastModifier(audit.lastModifier())+ .withLastModifiedTime(audit.lastModifiedTime())+ .build())+ .build();+ })+ .collect(Collectors.toList());+ }++ private EntityCombinedTable importTableFromCatalog(+ NameIdentifier identifier, AuditInfo importAudit) {EntityCombinedTable table = internalLoadTable(identifier);if (table.imported()) {@@ -644,6 +715,9 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab.withLastModifier(table.auditInfo().lastModifier()).withLastModifiedTime(table.auditInfo().lastModifiedTime()).build();+ if (audit.creator() == null) {+ audit = audit.merge(importAudit, false /* overwrite */);+ }List<ColumnEntity> columnEntityList =toColumnEntities(table.tableFromCatalog().columns(), audit);TableEntity tableEntity =diff --git a/core/src/main/java/org/apache/gravitino/catalog/ViewDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ViewDispatcher.javaindex 2961ca7890..a243279b88 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ViewDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ViewDispatcher.java@@ -18,6 +18,10 @@*/package org.apache.gravitino.catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.exceptions.NoSuchViewException;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.rel.View;import org.apache.gravitino.rel.ViewCatalog;/**@@ -26,4 +30,17 @@ import org.apache.gravitino.rel.ViewCatalog;* dispatching or handling view-related events or actions that are not covered by the standard* {@code ViewCatalog} operations.*/-public interface ViewDispatcher extends ViewCatalog {}+public interface ViewDispatcher extends ViewCatalog {+ /**+ * Imports an externally created view into Gravitino, or returns the already imported entity.+ * Catalog-reported audit fields take precedence over the supplied audit. Existing nonempty+ * creation fields are preserved; missing creation fields may be filled after a competing import.+ * This operation does not create the view in the underlying catalog.+ *+ * @param ident the identifier of the existing external view+ * @param auditInfo fallback creation audit used when the catalog reports no creator+ * @return the imported view+ * @throws NoSuchViewException if the external view does not exist+ */+ View importView(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchViewException;+}diff --git a/core/src/main/java/org/apache/gravitino/catalog/ViewNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ViewNormalizeDispatcher.javaindex 9ab5f85b1d..f3c124904e 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ViewNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ViewNormalizeDispatcher.java@@ -32,6 +32,7 @@ import org.apache.gravitino.connector.capability.Capability;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.exceptions.ViewAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;@@ -51,6 +52,12 @@ public class ViewNormalizeDispatcher implements ViewDispatcher {this.catalogManager = catalogManager;}+ /** {@inheritDoc} */+ @Override+ public View importView(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchViewException {+ return dispatcher.importView(normalizeCaseSensitive(ident), auditInfo);+ }+@Overridepublic NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {// The constraints of the name spec may be more strict than underlying catalog,diff --git a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.javaindex 141e370e5c..22c31b333f 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java@@ -139,21 +139,14 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View*/@Overridepublic View loadView(NameIdentifier ident) throws NoSuchViewException {- LOG.info("Loading view: {}", ident);-- EntityCombinedView entityCombinedView =- TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadView(ident));-- if (!entityCombinedView.imported()) {- SchemaDispatcher schemaDispatcher = getSchemaDispatcher();- NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());- schemaDispatcher.loadSchema(schemaIdent);-- entityCombinedView =- TreeLockUtils.doWithTreeLock(schemaIdent, LockType.WRITE, () -> importView(ident));- }+ return loadAndImportView(ident, AuditInfo.EMPTY);+ }- return entityCombinedView;+ /** {@inheritDoc} */+ @Override+ public View importView(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchViewException {+ Preconditions.checkArgument(auditInfo != null, "auditInfo must not be null");+ return loadAndImportView(ident, auditInfo);}/**@@ -538,7 +531,51 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View.withImported(viewEntity != null);}- private EntityCombinedView importView(NameIdentifier ident) throws NoSuchViewException {+ private View loadAndImportView(NameIdentifier ident, AuditInfo importAudit)+ throws NoSuchViewException {+ LOG.info("Loading view: {}", ident);++ EntityCombinedView entityCombinedView =+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadView(ident));++ if (!entityCombinedView.imported()) {+ SchemaDispatcher schemaDispatcher = getSchemaDispatcher();+ NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());+ schemaDispatcher.loadSchema(schemaIdent);++ entityCombinedView =+ TreeLockUtils.doWithTreeLock(+ schemaIdent, LockType.WRITE, () -> importViewFromCatalog(ident, importAudit));+ }++ ViewEntity entity =+ fillMissingCreationAudit(+ entityCombinedView.viewEntity(),+ ViewEntity.class,+ entityCombinedView.viewFromCatalog().auditInfo(),+ importAudit,+ (current, audit) ->+ ViewEntity.builder()+ .withId(current.id())+ .withName(current.name())+ .withNamespace(current.namespace())+ .withComment(current.comment())+ .withColumns(current.columns())+ .withRepresentations(current.representations())+ .withDefaultCatalog(current.defaultCatalog())+ .withDefaultSchema(current.defaultSchema())+ .withProperties(current.properties())+ .withAuditInfo(audit)+ .build());+ return EntityCombinedView.of(entityCombinedView.viewFromCatalog(), entity)+ .withHiddenProperties(entityCombinedView.hiddenProperties())+ .withImported(+ entityCombinedView.imported()+ && (entityCombinedView.viewEntity() == null || entity != null));+ }++ private EntityCombinedView importViewFromCatalog(NameIdentifier ident, AuditInfo importAudit)+ throws NoSuchViewException {EntityCombinedView entityCombinedView = internalLoadView(ident);if (entityCombinedView.imported()) {@@ -571,6 +608,9 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View.withLastModifier(catalogView.auditInfo().lastModifier()).withLastModifiedTime(catalogView.auditInfo().lastModifiedTime()).build();+ if (audit.creator() == null) {+ audit = audit.merge(importAudit, false /* overwrite */);+ }ViewEntity viewEntity =ViewEntity.builder().withId(uid)@@ -603,11 +643,7 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View}return EntityCombinedView.of(catalogView, viewEntity)- .withHiddenProperties(- getMaskAndOmitKeys(- getCatalogIdentifier(ident),- HasPropertyMetadata::tablePropertiesMetadata,- catalogView.properties()))+ .withHiddenProperties(entityCombinedView.hiddenProperties()).withImported(true);}diff --git a/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.javaindex 8d2ce75b7b..7b20b0e635 100644--- a/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/SchemaHookDispatcher.java@@ -39,6 +39,7 @@ import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.HierarchicalSchemaUtil;@@ -57,6 +58,13 @@ public class SchemaHookDispatcher implements SchemaDispatcher {this.dispatcher = dispatcher;}+ /** {@inheritDoc} */+ @Override+ public Schema importSchema(NameIdentifier ident, AuditInfo auditInfo)+ throws NoSuchSchemaException {+ return dispatcher.importSchema(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {return dispatcher.listSchemas(namespace);diff --git a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.javaindex 5f472804aa..5bca74f82a 100644--- a/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/TableHookDispatcher.java@@ -32,6 +32,7 @@ import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;@@ -68,6 +69,12 @@ public class TableHookDispatcher implements TableDispatcher {this.ownerDispatcher = ownerDispatcher;}+ /** {@inheritDoc} */+ @Override+ public Table importTable(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchTableException {+ return dispatcher.importTable(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {return dispatcher.listTables(namespace);diff --git a/core/src/main/java/org/apache/gravitino/hook/ViewHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/ViewHookDispatcher.javaindex c24117ef5f..c074ae7b45 100644--- a/core/src/main/java/org/apache/gravitino/hook/ViewHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/ViewHookDispatcher.java@@ -31,6 +31,7 @@ import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.exceptions.ViewAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;@@ -58,6 +59,12 @@ public class ViewHookDispatcher implements ViewDispatcher {this.ownerDispatcher = ownerDispatcher;}+ /** {@inheritDoc} */+ @Override+ public View importView(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchViewException {+ return dispatcher.importView(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {return dispatcher.listViews(namespace);diff --git a/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.javaindex e5ad603ebc..2da98277d8 100644--- a/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/SchemaEventDispatcher.java@@ -47,6 +47,7 @@ import org.apache.gravitino.listener.api.event.LoadSchemaEvent;import org.apache.gravitino.listener.api.event.LoadSchemaFailureEvent;import org.apache.gravitino.listener.api.event.LoadSchemaPreEvent;import org.apache.gravitino.listener.api.info.SchemaInfo;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.PrincipalUtils;@@ -73,6 +74,13 @@ public class SchemaEventDispatcher implements SchemaDispatcher {this.dispatcher = dispatcher;}+ /** {@inheritDoc} */+ @Override+ public Schema importSchema(NameIdentifier ident, AuditInfo auditInfo)+ throws NoSuchSchemaException {+ return dispatcher.importSchema(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {eventBus.dispatchEvent(new ListSchemaPreEvent(PrincipalUtils.getCurrentUserName(), namespace));diff --git a/core/src/main/java/org/apache/gravitino/listener/TableEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/TableEventDispatcher.javaindex fd235bb508..ecffcdbb50 100644--- a/core/src/main/java/org/apache/gravitino/listener/TableEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/TableEventDispatcher.java@@ -46,6 +46,7 @@ import org.apache.gravitino.listener.api.event.PurgeTableEvent;import org.apache.gravitino.listener.api.event.PurgeTableFailureEvent;import org.apache.gravitino.listener.api.event.PurgeTablePreEvent;import org.apache.gravitino.listener.api.info.TableInfo;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;@@ -83,6 +84,12 @@ public class TableEventDispatcher implements TableDispatcher {this.dispatcher = dispatcher;}+ /** {@inheritDoc} */+ @Override+ public Table importTable(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchTableException {+ return dispatcher.importTable(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {eventBus.dispatchEvent(new ListTablePreEvent(PrincipalUtils.getCurrentUserName(), namespace));diff --git a/core/src/main/java/org/apache/gravitino/listener/ViewEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/ViewEventDispatcher.javaindex 49e277cc36..bbe74f1dd1 100644--- a/core/src/main/java/org/apache/gravitino/listener/ViewEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/ViewEventDispatcher.java@@ -44,6 +44,7 @@ import org.apache.gravitino.listener.api.event.view.LoadViewEvent;import org.apache.gravitino.listener.api.event.view.LoadViewFailureEvent;import org.apache.gravitino.listener.api.event.view.LoadViewPreEvent;import org.apache.gravitino.listener.api.info.ViewInfo;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;@@ -69,6 +70,12 @@ public class ViewEventDispatcher implements ViewDispatcher {this.dispatcher = dispatcher;}+ /** {@inheritDoc} */+ @Override+ public View importView(NameIdentifier ident, AuditInfo auditInfo) throws NoSuchViewException {+ return dispatcher.importView(ident, auditInfo);+ }+@Overridepublic NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {eventBus.dispatchEvent(new ListViewPreEvent(PrincipalUtils.getCurrentUserName(), namespace));diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestImportAuditRecovery.java b/core/src/test/java/org/apache/gravitino/catalog/TestImportAuditRecovery.javanew file mode 100644index 0000000000..dd8d884148--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/catalog/TestImportAuditRecovery.java@@ -0,0 +1,222 @@+/*+ * 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.catalog;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.verifyNoMoreInteractions;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.time.Instant;+import java.util.Map;+import java.util.function.Function;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.exceptions.OptimisticLockException;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.SchemaEntity;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++/** Verifies the store-side conditions used to recover creation audit after competing imports. */+public class TestImportAuditRecovery {+ private static final AuditInfo ALICE =+ AuditInfo.builder().withCreator("alice").withCreateTime(Instant.EPOCH).build();++ private final EntityStore store = mock(EntityStore.class);+ private final OperationDispatcher dispatcher =+ new OperationDispatcher(null, store, null, null) {};++ @Test+ void testNoUpdateForColdImportOrEmptyFallback() {+ SchemaEntity imported = schema(1L, ALICE);+ Assertions.assertSame(imported, fill(imported, ALICE));+ SchemaEntity empty = schema(1L, AuditInfo.EMPTY);+ Assertions.assertSame(empty, fill(empty, AuditInfo.EMPTY));+ Assertions.assertNull(fill(null, ALICE));+ verifyNoInteractions(store);+ }++ @Test+ void testConcurrentCreatorWins() throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ SchemaEntity current = schema(1L, AuditInfo.builder().withCreator("bob").build());+ currentAtUpdate(observed, current);+ Assertions.assertSame(current, fill(observed, ALICE));+ }++ @Test+ void testRecreatedNameIsNotAttributedToOldCreate() throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ SchemaEntity recreated = schema(2L, AuditInfo.EMPTY);+ currentAtUpdate(observed, recreated);+ when(store.get(observed.nameIdentifier(), Entity.EntityType.SCHEMA, SchemaEntity.class))+ .thenReturn(recreated);+ Assertions.assertSame(recreated, fill(observed, ALICE));+ Assertions.assertNull(recreated.auditInfo().creator());+ Assertions.assertNull(recreated.auditInfo().createTime());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testConflictReturnsCurrentRegistration(boolean knownCreator) throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ SchemaEntity current =+ schema(1L, knownCreator ? AuditInfo.builder().withCreator("bob").build() : AuditInfo.EMPTY);+ when(store.update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any()))+ .thenThrow(new OptimisticLockException("concurrent update"));+ when(store.get(observed.nameIdentifier(), Entity.EntityType.SCHEMA, SchemaEntity.class))+ .thenReturn(current);+ Assertions.assertSame(current, fill(observed, ALICE));+ verify(store)+ .update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any());+ }++ @Test+ void testDisappearedRegistrationIsNotRecoveredFromObservedSnapshot() throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ when(store.update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any()))+ .thenThrow(new NoSuchEntityException("Registration was renamed or dropped"));+ Assertions.assertNull(fill(observed, ALICE));+ verify(store)+ .update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any());+ verifyNoMoreInteractions(store);+ }++ @Test+ void testFillKeepsModificationFieldsAndExistingCreateTime() throws Exception {+ AuditInfo existing =+ AuditInfo.builder()+ .withCreateTime(Instant.EPOCH.plusSeconds(1))+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.EPOCH.plusSeconds(2))+ .build();+ SchemaEntity observed = schema(1L, existing);+ currentAtUpdate(observed, observed);+ SchemaEntity updated = fill(observed, ALICE);+ Assertions.assertEquals("alice", updated.auditInfo().creator());+ Assertions.assertEquals(existing.createTime(), updated.auditInfo().createTime());+ Assertions.assertEquals(existing.lastModifier(), updated.auditInfo().lastModifier());+ Assertions.assertEquals(existing.lastModifiedTime(), updated.auditInfo().lastModifiedTime());+ Assertions.assertEquals(observed.properties(), updated.properties());+ Assertions.assertEquals(observed.comment(), updated.comment());+ Assertions.assertNull(observed.auditInfo().creator());+ }++ @Test+ void testCatalogCreationAuditTakesPrecedence() throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ currentAtUpdate(observed, observed);+ AuditInfo reported =+ AuditInfo.builder()+ .withCreator("source")+ .withCreateTime(Instant.EPOCH.plusSeconds(3))+ .build();+ SchemaEntity updated =+ dispatcher.fillMissingCreationAudit(+ observed, SchemaEntity.class, reported, ALICE, TestImportAuditRecovery::withAudit);+ Assertions.assertEquals("source", updated.auditInfo().creator());+ Assertions.assertEquals(reported.createTime(), updated.auditInfo().createTime());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testStoreFailureReturnsObservedEntity(boolean checkedException) throws Exception {+ SchemaEntity observed = schema(1L, AuditInfo.EMPTY);+ Exception failure =+ checkedException+ ? new IOException("unavailable")+ : new IllegalStateException("unavailable");+ when(store.update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any()))+ .thenThrow(failure);+ Assertions.assertSame(observed, fill(observed, ALICE));+ }++ private void currentAtUpdate(SchemaEntity observed, SchemaEntity current) throws Exception {+ when(store.update(+ eq(observed.nameIdentifier()),+ eq(SchemaEntity.class),+ eq(Entity.EntityType.SCHEMA),+ any()))+ .thenAnswer(+ call -> {+ Function<SchemaEntity, SchemaEntity> updater = call.getArgument(3);+ return updater.apply(current);+ });+ }++ private SchemaEntity fill(SchemaEntity observed, AuditInfo requested) {+ return dispatcher.fillMissingCreationAudit(+ observed,+ SchemaEntity.class,+ AuditInfo.EMPTY,+ requested,+ TestImportAuditRecovery::withAudit);+ }++ private static SchemaEntity schema(long id, AuditInfo audit) {+ return SchemaEntity.builder()+ .withId(id)+ .withName("schema")+ .withNamespace(Namespace.of("metalake", "catalog"))+ .withComment("comment")+ .withProperties(Map.of("key", "value"))+ .withAuditInfo(audit)+ .build();+ }++ private static SchemaEntity withAudit(SchemaEntity current, AuditInfo audit) {+ return SchemaEntity.builder()+ .withId(current.id())+ .withName(current.name())+ .withNamespace(current.namespace())+ .withComment(current.comment())+ .withProperties(current.properties())+ .withAuditInfo(audit)+ .build();+ }+}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestImportDispatcherDelegation.java b/core/src/test/java/org/apache/gravitino/catalog/TestImportDispatcherDelegation.javanew file mode 100644index 0000000000..f956eef2a4--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/catalog/TestImportDispatcherDelegation.java@@ -0,0 +1,101 @@+/*+ * 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.catalog;++import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Schema;+import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.hook.SchemaHookDispatcher;+import org.apache.gravitino.hook.TableHookDispatcher;+import org.apache.gravitino.hook.ViewHookDispatcher;+import org.apache.gravitino.listener.EventBus;+import org.apache.gravitino.listener.SchemaEventDispatcher;+import org.apache.gravitino.listener.TableEventDispatcher;+import org.apache.gravitino.listener.ViewEventDispatcher;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.View;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Tests that internal imports preserve audit information through dispatcher decorators. */+public class TestImportDispatcherDelegation {++ private static final NameIdentifier IDENTIFIER =+ NameIdentifier.of("metalake", "catalog", "schema", "object");+ private static final AuditInfo AUDIT = AuditInfo.builder().withCreator("creator").build();++ /** Internal table imports do not invent load/create events or change ownership. */+ @Test+ public void testImportTablePreservesAuditWithoutExtraOperations() {+ TableDispatcher delegate = mock(TableDispatcher.class);+ Table imported = mock(Table.class);+ EventBus events = mock(EventBus.class);+ OwnerDispatcher owner = mock(OwnerDispatcher.class);+ when(delegate.importTable(IDENTIFIER, AUDIT)).thenReturn(imported);+ TableDispatcher dispatcher =+ new TableHookDispatcher(new TableEventDispatcher(events, delegate), () -> owner);++ Assertions.assertSame(imported, dispatcher.importTable(IDENTIFIER, AUDIT));++ verify(delegate).importTable(IDENTIFIER, AUDIT);+ verifyNoInteractions(events, owner);+ }++ /** Internal schema imports do not invent load/create events or change ownership. */+ @Test+ public void testImportSchemaPreservesAuditWithoutExtraOperations() {+ NameIdentifier identifier = NameIdentifier.of("metalake", "catalog", "schema");+ SchemaDispatcher delegate = mock(SchemaDispatcher.class);+ Schema imported = mock(Schema.class);+ EventBus events = mock(EventBus.class);+ OwnerDispatcher owner = mock(OwnerDispatcher.class);+ when(delegate.importSchema(identifier, AUDIT)).thenReturn(imported);+ SchemaDispatcher dispatcher =+ new SchemaHookDispatcher(new SchemaEventDispatcher(events, delegate));++ Assertions.assertSame(imported, dispatcher.importSchema(identifier, AUDIT));++ verify(delegate).importSchema(identifier, AUDIT);+ verifyNoInteractions(events, owner);+ }++ /** Internal view imports do not invent load/create events or change ownership. */+ @Test+ public void testImportViewPreservesAuditWithoutExtraOperations() {+ ViewDispatcher delegate = mock(ViewDispatcher.class);+ View imported = mock(View.class);+ EventBus events = mock(EventBus.class);+ OwnerDispatcher owner = mock(OwnerDispatcher.class);+ when(delegate.importView(IDENTIFIER, AUDIT)).thenReturn(imported);+ ViewDispatcher dispatcher =+ new ViewHookDispatcher(new ViewEventDispatcher(events, delegate), () -> owner);++ Assertions.assertSame(imported, dispatcher.importView(IDENTIFIER, AUDIT));++ verify(delegate).importView(IDENTIFIER, AUDIT);+ verifyNoInteractions(events, owner);+ }+}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaNormalizeDispatcher.javaindex ec79cc6d04..c0e1458191 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaNormalizeDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaNormalizeDispatcher.java@@ -26,6 +26,7 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.Schema;import org.apache.gravitino.SchemaChange;+import org.apache.gravitino.meta.AuditInfo;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;@@ -77,6 +78,19 @@ public class TestSchemaNormalizeDispatcher extends TestOperationDispatcher {new SchemaNormalizeDispatcher(TestSchemaOperationDispatcher.dispatcher, catalogManager);}+ /** Explicit imports normalize names while preserving their audit arguments. */+ @Test+ public void testImportNormalizesIdentifierAndPassesAudit() {+ SchemaDispatcher delegate = Mockito.mock(SchemaDispatcher.class);+ SchemaNormalizeDispatcher normalizer = new SchemaNormalizeDispatcher(delegate, catalogManager);+ AuditInfo audit = AuditInfo.builder().withCreator("creator").build();+ NameIdentifier requested = NameIdentifier.of(metalake, catalog, "MiXeD");+ normalizer.importSchema(requested, audit);+ Mockito.verify(delegate)+ .importSchema(+ Mockito.eq(NameIdentifier.of(metalake, catalog, "mixed")), Mockito.same(audit));+ }+@Testpublic void testNameCaseInsensitive() {// test case-insensitive in creationdiff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.javaindex 7f9c9c4878..1ae5ed1140 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java@@ -24,6 +24,8 @@ import static org.apache.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;@@ -52,6 +54,7 @@ import org.apache.gravitino.Schema;import org.apache.gravitino.SchemaChange;import org.apache.gravitino.StringIdentifier;import org.apache.gravitino.TestCatalog;+import org.apache.gravitino.TestSchema;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.connector.HiddenPropertyMaskUtils;import org.apache.gravitino.connector.TestCatalogOperations;@@ -93,6 +96,117 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);}+ /**+ * Imports write creation audit once and recover safely after competing imports or deletion.+ *+ * @param scenario the source audit and competing-import ordering to exercise+ */+ @ParameterizedTest+ @ValueSource(strings = {"missing", "reported", "modified", "load", "raced", "deleted"})+ public void testImportCreationAudit(String scenario) throws Exception {+ Instant importTime = Instant.EPOCH.plusSeconds(60);+ AuditInfo importAudit =+ AuditInfo.builder().withCreator("alice").withCreateTime(importTime).build();+ AuditInfo catalogAudit =+ "reported".equals(scenario)+ ? AuditInfo.builder().withCreator("catalog_user").withCreateTime(Instant.EPOCH).build()+ : "modified".equals(scenario)+ ? AuditInfo.builder()+ .withCreateTime(Instant.EPOCH)+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.EPOCH)+ .build()+ : AuditInfo.EMPTY;+ String expectedCreator =+ "reported".equals(scenario) ? "catalog_user" : "load".equals(scenario) ? null : "alice";+ Instant expectedTime =+ "reported".equals(scenario) || "modified".equals(scenario)+ ? Instant.EPOCH+ : "load".equals(scenario) ? null : importTime;+ NameIdentifier schemaIdent =+ NameIdentifier.of(metalake, catalog, "schema_import_audit_schema_" + scenario);+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ dispatcher.createSchema(schemaIdent, "comment", props);+ TestCatalog testCatalog =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations operations = (TestCatalogOperations) testCatalog.ops();+ NameIdentifier identifier = schemaIdent;+ TestSchema catalogSchema = (TestSchema) operations.loadSchema(identifier);+ FieldUtils.writeField(catalogSchema, "auditInfo", catalogAudit, true);+ entityStore.delete(identifier, SCHEMA);+ clearInvocations(entityStore);++ if ("raced".equals(scenario) || "deleted".equals(scenario)) {+ dispatcher.loadSchema(identifier);+ clearInvocations(entityStore);+ }+ if ("deleted".equals(scenario)) {+ doAnswer(+ call -> {+ entityStore.delete(identifier, SCHEMA);+ throw new OptimisticLockException("Registration deleted during audit recovery");+ })+ .when(entityStore)+ .update(eq(identifier), eq(SchemaEntity.class), eq(SCHEMA), any());+ }+ Schema loaded =+ "load".equals(scenario)+ ? dispatcher.loadSchema(identifier)+ : dispatcher.importSchema(identifier, importAudit);++ if ("deleted".equals(scenario)) {+ EntityCombinedSchema combined = (EntityCombinedSchema) loaded;+ Assertions.assertFalse(combined.imported());+ Assertions.assertNull(combined.schemaEntity());+ Assertions.assertNull(loaded.auditInfo().creator());+ Assertions.assertEquals(identifier.name(), loaded.name());+ Assertions.assertEquals(props, loaded.properties());+ verify(entityStore, never()).put(any(SchemaEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(SchemaEntity.class), eq(SCHEMA), any());+ reset(entityStore);+ dispatcher.loadSchema(identifier);+ Assertions.assertNull(+ entityStore.get(identifier, SCHEMA, SchemaEntity.class).auditInfo().creator());+ return;+ }++ SchemaEntity imported = entityStore.get(identifier, SCHEMA, SchemaEntity.class);+ Assertions.assertEquals(expectedCreator, imported.auditInfo().creator());+ Assertions.assertEquals(expectedCreator, loaded.auditInfo().creator());+ Assertions.assertEquals(expectedTime, loaded.auditInfo().createTime());+ Assertions.assertEquals(+ "modified".equals(scenario) ? "modifier" : null, imported.auditInfo().lastModifier());+ Assertions.assertEquals(+ "modified".equals(scenario) ? Instant.EPOCH : null,+ imported.auditInfo().lastModifiedTime());+ Assertions.assertEquals(expectedTime, imported.auditInfo().createTime());+ if ("raced".equals(scenario)) {+ verify(entityStore, never()).put(any(SchemaEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(SchemaEntity.class), eq(SCHEMA), any());+ } else {+ verify(entityStore).put(any(SchemaEntity.class), anyBoolean());+ verify(entityStore, never()).update(any(), any(), any(), any());+ }++ clearInvocations(entityStore);+ dispatcher.importSchema(+ identifier,+ AuditInfo.builder().withCreator("bob").withCreateTime(importTime.plusSeconds(60)).build());+ Assertions.assertEquals(+ "load".equals(scenario) ? "bob" : expectedCreator,+ entityStore.get(identifier, SCHEMA, SchemaEntity.class).auditInfo().creator());+ Assertions.assertEquals(+ "load".equals(scenario) ? importTime.plusSeconds(60) : expectedTime,+ entityStore.get(identifier, SCHEMA, SchemaEntity.class).auditInfo().createTime());+ verify(entityStore, never()).put(any(), anyBoolean());+ if ("load".equals(scenario)) {+ verify(entityStore).update(eq(identifier), eq(SchemaEntity.class), eq(SCHEMA), any());+ } else {+ verify(entityStore, never()).update(any(), any(), any(), any());+ }+ }+@Testvoid testExternalRenamePreservesSchemaIdentity() throws Exception {NameIdentifier original = NameIdentifier.of(metalake, catalog, "external_rename_original");@@ -193,6 +307,14 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {entityStore.get(original, SCHEMA, SchemaEntity.class).properties());}+ /** Explicit imports require audit information. */+ @Test+ public void testImportRejectsNullAudit() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> dispatcher.importSchema(NameIdentifier.of(metalake, catalog, "missing"), null));+ }+@Testpublic void testCreateAndListSchemas() throws Exception {Namespace ns = Namespace.of(metalake, catalog);@@ -780,20 +902,31 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {}}- @Test- void testImportRetainsExternalSecretReference() throws Exception {+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testImportRetainsExternalSecretReference(boolean explicitImport) throws Exception {NameIdentifier ident = NameIdentifier.of(metalake, catalog, "external_secret_reference");String reference = "urn:gravitino-secret:external:credential:k2";- catalogManager.doWithCatalogWrapper(- NameIdentifier.of(metalake, catalog),- c ->- c.doWithSchemaOps(- ops -> ops.createSchema(ident, "external", Map.of("k1", "v1", "k2", reference))));-- Schema imported = dispatcher.loadSchema(ident);+ Schema source =+ catalogManager.doWithCatalogWrapper(+ NameIdentifier.of(metalake, catalog),+ c ->+ c.doWithSchemaOps(+ ops ->+ ops.createSchema(ident, "external", Map.of("k1", "v1", "k2", reference))));+ FieldUtils.writeField(source, "auditInfo", AuditInfo.EMPTY, true);++ AuditInfo importAudit =+ AuditInfo.builder().withCreator("alice").withCreateTime(Instant.EPOCH).build();+ Schema imported =+ explicitImport ? dispatcher.importSchema(ident, importAudit) : dispatcher.loadSchema(ident);Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, imported.properties().get("k2"));Assertions.assertEquals(reference, entityStore.get(ident, SCHEMA, SchemaEntity.class).properties().get("k2"));+ Assertions.assertEquals(explicitImport ? "alice" : null, imported.auditInfo().creator());+ Assertions.assertEquals(+ explicitImport ? "alice" : null,+ entityStore.get(ident, SCHEMA, SchemaEntity.class).auditInfo().creator());Assertions.assertTrue(dispatcher.dropSchema(ident, false));}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.javaindex 35610eb8ee..0bad036098 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableNormalizeDispatcher.java@@ -36,6 +36,7 @@ import org.apache.gravitino.connector.capability.Capability;import org.apache.gravitino.connector.capability.CapabilityResult;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;@@ -668,6 +669,10 @@ public class TestTableNormalizeDispatcher extends TestOperationDispatcher {TableNormalizeDispatcher dispatcher =newResolvingDispatcher(mockDispatcher, resolvingCatalogOps(resolver));+ AuditInfo audit = AuditInfo.builder().withCreator("creator").build();+ dispatcher.importTable(requested, audit);+ Mockito.verify(mockDispatcher).importTable(Mockito.eq(resolved), Mockito.same(audit));+dispatcher.loadTable(requested);dispatcher.alterTable(requested, TableChange.rename("x"));dispatcher.dropTable(requested);diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.javaindex a64b6d3557..0e6c237547 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java@@ -140,6 +140,136 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {GravitinoEnv.getInstance(), "internalSchemaDispatcher", schemaOperationDispatcher, true);}+ /**+ * Imports write creation audit once and recover safely after competing imports or deletion.+ *+ * @param scenario the source audit and competing-import ordering to exercise+ */+ @ParameterizedTest+ @ValueSource(strings = {"missing", "reported", "modified", "load", "raced", "deleted"})+ public void testImportCreationAudit(String scenario) throws Exception {+ Instant importTime = Instant.EPOCH.plusSeconds(60);+ AuditInfo importAudit =+ AuditInfo.builder().withCreator("alice").withCreateTime(importTime).build();+ AuditInfo catalogAudit =+ "reported".equals(scenario)+ ? AuditInfo.builder().withCreator("catalog_user").withCreateTime(Instant.EPOCH).build()+ : "modified".equals(scenario)+ ? AuditInfo.builder()+ .withCreateTime(Instant.EPOCH)+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.EPOCH)+ .build()+ : AuditInfo.EMPTY;+ String expectedCreator =+ "reported".equals(scenario) ? "catalog_user" : "load".equals(scenario) ? null : "alice";+ Instant expectedTime =+ "reported".equals(scenario) || "modified".equals(scenario)+ ? Instant.EPOCH+ : "load".equals(scenario) ? null : importTime;+ NameIdentifier schemaIdent =+ NameIdentifier.of(metalake, catalog, "schema_import_audit_table_" + scenario);+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", props);+ TestCatalog testCatalog =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations operations = (TestCatalogOperations) testCatalog.ops();+ NameIdentifier identifier =+ NameIdentifier.of(metalake, catalog, schemaIdent.name(), "table_import_audit");+ Column[] columns = {+ TestColumn.builder().withName("col").withPosition(0).withType(Types.StringType.get()).build()+ };+ tableOperationDispatcher.createTable(identifier, columns, "comment", props, new Transform[0]);+ TestTable catalogTable = (TestTable) operations.loadTable(identifier);+ FieldUtils.writeField(catalogTable, "auditInfo", catalogAudit, true);+ entityStore.delete(identifier, TABLE);+ clearInvocations(entityStore);++ if ("raced".equals(scenario) || "deleted".equals(scenario)) {+ tableOperationDispatcher.loadTable(identifier);+ clearInvocations(entityStore);+ }+ if ("deleted".equals(scenario)) {+ doAnswer(+ call -> {+ entityStore.delete(identifier, TABLE);+ throw new OptimisticLockException("Registration deleted during audit recovery");+ })+ .when(entityStore)+ .update(eq(identifier), eq(TableEntity.class), eq(TABLE), any());+ }+ Table loaded =+ "load".equals(scenario)+ ? tableOperationDispatcher.loadTable(identifier)+ : tableOperationDispatcher.importTable(identifier, importAudit);++ if ("deleted".equals(scenario)) {+ EntityCombinedTable combined = (EntityCombinedTable) loaded;+ Assertions.assertFalse(combined.imported());+ Assertions.assertNull(combined.tableFromGravitino());+ Assertions.assertNull(loaded.auditInfo().creator());+ Assertions.assertEquals(identifier.name(), loaded.name());+ Assertions.assertEquals("col", loaded.columns()[0].name());+ verify(entityStore, never()).put(any(TableEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(TableEntity.class), eq(TABLE), any());+ reset(entityStore);+ tableOperationDispatcher.loadTable(identifier);+ Assertions.assertNull(+ entityStore.get(identifier, TABLE, TableEntity.class).auditInfo().creator());+ return;+ }++ TableEntity imported = entityStore.get(identifier, TABLE, TableEntity.class);+ Assertions.assertEquals(expectedCreator, imported.auditInfo().creator());+ Assertions.assertEquals(expectedCreator, loaded.auditInfo().creator());+ Assertions.assertEquals(expectedTime, loaded.auditInfo().createTime());+ Assertions.assertEquals(+ "modified".equals(scenario) ? "modifier" : null, imported.auditInfo().lastModifier());+ Assertions.assertEquals(+ "modified".equals(scenario) ? Instant.EPOCH : null,+ imported.auditInfo().lastModifiedTime());+ Assertions.assertEquals(expectedTime, imported.auditInfo().createTime());+ for (ColumnEntity column : imported.columns()) {+ Assertions.assertEquals(expectedCreator, column.auditInfo().creator());+ Assertions.assertEquals(expectedTime, column.auditInfo().createTime());+ }+ if ("raced".equals(scenario)) {+ verify(entityStore, never()).put(any(TableEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(TableEntity.class), eq(TABLE), any());+ } else {+ verify(entityStore).put(any(TableEntity.class), anyBoolean());+ verify(entityStore, never()).update(any(), any(), any(), any());+ }++ clearInvocations(entityStore);+ tableOperationDispatcher.importTable(+ identifier,+ AuditInfo.builder().withCreator("bob").withCreateTime(importTime.plusSeconds(60)).build());+ Assertions.assertEquals(+ "load".equals(scenario) ? "bob" : expectedCreator,+ entityStore.get(identifier, TABLE, TableEntity.class).auditInfo().creator());+ Assertions.assertEquals(+ "load".equals(scenario) ? importTime.plusSeconds(60) : expectedTime,+ entityStore.get(identifier, TABLE, TableEntity.class).auditInfo().createTime());+ verify(entityStore, never()).put(any(), anyBoolean());+ if ("load".equals(scenario)) {+ verify(entityStore).update(eq(identifier), eq(TableEntity.class), eq(TABLE), any());+ } else {+ verify(entityStore, never()).update(any(), any(), any(), any());+ }+ }++ /** Explicit imports require audit information. */+ @Test+ public void testImportRejectsNullAudit() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ tableOperationDispatcher.importTable(+ NameIdentifier.of(metalake, catalog, "schema", "missing"), null));+ }+/** Checks blocked source DDL permits warm sibling metadata reads. */@Testpublic void testBlockedSourceDropDoesNotBlockSiblingMetadataReads() throws Exception {@@ -709,11 +839,13 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {/*** Verifies a native table is imported from one source read and keeps its identity on warm loads.*+ * @param explicitImport whether to import with caller-provided audit information* @throws Exception if fixture setup or concurrent verification fails*/- @Test- public void testNativeTableImportLoadsSourceOnce() throws Exception {- Namespace ns = Namespace.of(metalake, catalog, "schema_import_once");+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ public void testNativeTableImportLoadsSourceOnce(boolean explicitImport) throws Exception {+ Namespace ns = Namespace.of(metalake, catalog, "schema_import_once_" + explicitImport);schemaOperationDispatcher.createSchema(NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));NameIdentifier ident = NameIdentifier.of(ns, "native_table");@@ -730,12 +862,22 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {Distributions.NONE,new SortOrder[0],Indexes.EMPTY_INDEXES);+ FieldUtils.writeField(original.loadTable(ident), "auditInfo", AuditInfo.EMPTY, true);TestCatalogOperations operations = spy(original);FieldUtils.writeField(source, "ops", operations, true);try {- Table loaded = tableOperationDispatcher.loadTable(ident);+ AuditInfo importAudit =+ AuditInfo.builder().withCreator("alice").withCreateTime(Instant.EPOCH).build();+ Table loaded =+ explicitImport+ ? tableOperationDispatcher.importTable(ident, importAudit)+ : tableOperationDispatcher.loadTable(ident);Assertions.assertEquals("native", loaded.comment());Assertions.assertTrue(entityStore.exists(ident, TABLE));+ Assertions.assertEquals(explicitImport ? "alice" : null, loaded.auditInfo().creator());+ Assertions.assertEquals(+ explicitImport ? "alice" : null,+ entityStore.get(ident, TABLE, TableEntity.class).auditInfo().creator());verify(operations, times(1)).loadTable(ident);long importedId = entityStore.get(ident, TABLE, TableEntity.class).id();clearInvocations(entityStore);@@ -744,6 +886,9 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {verify(entityStore, times(2)).get(ident, TABLE, TableEntity.class);verify(operations, times(2)).loadTable(ident);Assertions.assertEquals(importedId, entityStore.get(ident, TABLE, TableEntity.class).id());+ Assertions.assertEquals(+ explicitImport ? "alice" : null,+ entityStore.get(ident, TABLE, TableEntity.class).auditInfo().creator());} finally {FieldUtils.writeField(source, "ops", original, true);}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestViewNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestViewNormalizeDispatcher.javaindex 4bb8825aaf..58d86209e2 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestViewNormalizeDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestViewNormalizeDispatcher.java@@ -26,6 +26,7 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.EntityFieldLimits;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.SQLRepresentation;@@ -34,6 +35,7 @@ import org.apache.gravitino.rel.ViewChange;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.mockito.Mockito;public class TestViewNormalizeDispatcher extends TestOperationDispatcher {private static ViewNormalizeDispatcher viewNormalizeDispatcher;@@ -50,6 +52,20 @@ public class TestViewNormalizeDispatcher extends TestOperationDispatcher {TestViewOperationDispatcher.schemaOperationDispatcher, catalogManager);}+ /** Explicit imports normalize names while preserving their audit arguments. */+ @Test+ public void testImportNormalizesIdentifierAndPassesAudit() {+ ViewDispatcher delegate = Mockito.mock(ViewDispatcher.class);+ ViewNormalizeDispatcher normalizer = new ViewNormalizeDispatcher(delegate, catalogManager);+ AuditInfo audit = AuditInfo.builder().withCreator("creator").build();+ NameIdentifier requested = NameIdentifier.of(metalake, catalog, "schema", "MiXeD");+ normalizer.importView(requested, audit);+ Mockito.verify(delegate)+ .importView(+ Mockito.eq(NameIdentifier.of(metalake, catalog, "schema", "mixed")),+ Mockito.same(audit));+ }+@Testpublic void testNameCaseInsensitive() {Namespace viewNs = Namespace.of(metalake, catalog, "schemaVIEW_NORMALIZE_1");diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.javaindex b23ddad349..2a8bbaee02 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java@@ -28,10 +28,14 @@ import static org.apache.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.reset;+import static org.mockito.Mockito.verify;import com.google.common.collect.ImmutableMap;import java.io.IOException;@@ -72,6 +76,8 @@ import org.apache.gravitino.rel.ViewChange;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;public class TestViewOperationDispatcher extends TestOperationDispatcher {static ViewOperationDispatcher viewOperationDispatcher;@@ -149,6 +155,127 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {};}+ /**+ * Imports write creation audit once and recover safely after competing imports or deletion.+ *+ * @param scenario the source audit and competing-import ordering to exercise+ */+ @ParameterizedTest+ @ValueSource(strings = {"missing", "reported", "modified", "load", "raced", "deleted"})+ public void testImportCreationAudit(String scenario) throws Exception {+ Instant importTime = Instant.EPOCH.plusSeconds(60);+ AuditInfo importAudit =+ AuditInfo.builder().withCreator("alice").withCreateTime(importTime).build();+ AuditInfo catalogAudit =+ "reported".equals(scenario)+ ? AuditInfo.builder().withCreator("catalog_user").withCreateTime(Instant.EPOCH).build()+ : "modified".equals(scenario)+ ? AuditInfo.builder()+ .withCreateTime(Instant.EPOCH)+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.EPOCH)+ .build()+ : AuditInfo.EMPTY;+ String expectedCreator =+ "reported".equals(scenario) ? "catalog_user" : "load".equals(scenario) ? null : "alice";+ Instant expectedTime =+ "reported".equals(scenario) || "modified".equals(scenario)+ ? Instant.EPOCH+ : "load".equals(scenario) ? null : importTime;+ NameIdentifier schemaIdent =+ NameIdentifier.of(metalake, catalog, "schema_import_audit_view_" + scenario);+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", props);+ TestCatalog testCatalog =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations operations = (TestCatalogOperations) testCatalog.ops();+ NameIdentifier identifier =+ NameIdentifier.of(metalake, catalog, schemaIdent.name(), "view_import_audit");+ operations.views.put(identifier, createMockView(identifier.name(), props, catalogAudit));+ entityStore.delete(identifier, VIEW);+ clearInvocations(entityStore);++ if ("raced".equals(scenario) || "deleted".equals(scenario)) {+ viewOperationDispatcher.loadView(identifier);+ clearInvocations(entityStore);+ }+ if ("deleted".equals(scenario)) {+ doAnswer(+ call -> {+ entityStore.delete(identifier, VIEW);+ throw new OptimisticLockException("Registration deleted during audit recovery");+ })+ .when(entityStore)+ .update(eq(identifier), eq(ViewEntity.class), eq(VIEW), any());+ }+ View loaded =+ "load".equals(scenario)+ ? viewOperationDispatcher.loadView(identifier)+ : viewOperationDispatcher.importView(identifier, importAudit);++ if ("deleted".equals(scenario)) {+ EntityCombinedView combined = (EntityCombinedView) loaded;+ Assertions.assertFalse(combined.imported());+ Assertions.assertNull(combined.viewEntity());+ Assertions.assertNull(loaded.auditInfo().creator());+ Assertions.assertEquals(identifier.name(), loaded.name());+ Assertions.assertEquals(props, loaded.properties());+ verify(entityStore, never()).put(any(ViewEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(ViewEntity.class), eq(VIEW), any());+ reset(entityStore);+ viewOperationDispatcher.loadView(identifier);+ Assertions.assertNull(+ entityStore.get(identifier, VIEW, ViewEntity.class).auditInfo().creator());+ return;+ }++ ViewEntity imported = entityStore.get(identifier, VIEW, ViewEntity.class);+ Assertions.assertEquals(expectedCreator, imported.auditInfo().creator());+ Assertions.assertEquals(expectedCreator, loaded.auditInfo().creator());+ Assertions.assertEquals(expectedTime, loaded.auditInfo().createTime());+ Assertions.assertEquals(+ "modified".equals(scenario) ? "modifier" : null, imported.auditInfo().lastModifier());+ Assertions.assertEquals(+ "modified".equals(scenario) ? Instant.EPOCH : null,+ imported.auditInfo().lastModifiedTime());+ Assertions.assertEquals(expectedTime, imported.auditInfo().createTime());+ if ("raced".equals(scenario)) {+ verify(entityStore, never()).put(any(ViewEntity.class), anyBoolean());+ verify(entityStore).update(eq(identifier), eq(ViewEntity.class), eq(VIEW), any());+ } else {+ verify(entityStore).put(any(ViewEntity.class), eq(true));+ verify(entityStore, never()).update(any(), any(), any(), any());+ }++ clearInvocations(entityStore);+ viewOperationDispatcher.importView(+ identifier,+ AuditInfo.builder().withCreator("bob").withCreateTime(importTime.plusSeconds(60)).build());+ Assertions.assertEquals(+ "load".equals(scenario) ? "bob" : expectedCreator,+ entityStore.get(identifier, VIEW, ViewEntity.class).auditInfo().creator());+ Assertions.assertEquals(+ "load".equals(scenario) ? importTime.plusSeconds(60) : expectedTime,+ entityStore.get(identifier, VIEW, ViewEntity.class).auditInfo().createTime());+ verify(entityStore, never()).put(any(), anyBoolean());+ if ("load".equals(scenario)) {+ verify(entityStore).update(eq(identifier), eq(ViewEntity.class), eq(VIEW), any());+ } else {+ verify(entityStore, never()).update(any(), any(), any(), any());+ }+ }++ /** Explicit imports require audit information. */+ @Test+ public void testImportRejectsNullAudit() {+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ viewOperationDispatcher.importView(+ NameIdentifier.of(metalake, catalog, "schema", "missing"), null));+ }+@Testpublic void testLoadView() throws IOException {Namespace viewNs = Namespace.of(metalake, catalog, "schema61");diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.javadeleted file mode 100644index 76a668c9e6..0000000000--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergEntityAuditUtils.java+++ /dev/null@@ -1,146 +0,0 @@-/*- * 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.iceberg.service.dispatcher;--import com.google.common.annotations.VisibleForTesting;-import java.time.Instant;-import org.apache.gravitino.Entity;-import org.apache.gravitino.EntityStore;-import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.NameIdentifier;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.SchemaEntity;-import org.apache.gravitino.meta.TableEntity;-import org.apache.gravitino.meta.ViewEntity;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * Records who created an object through the Iceberg REST catalog. The Iceberg catalog reports no- * creator or create time, so an object imported into Gravitino after an IRC create would otherwise- * have an empty audit.- */-final class IcebergEntityAuditUtils {-- private static final Logger LOG = LoggerFactory.getLogger(IcebergEntityAuditUtils.class);-- private IcebergEntityAuditUtils() {}-- /**- * Sets the creator and create time of an imported schema, table or view whose stored audit has no- * creator. A creator the catalog already reported is kept. The object already exists when this is- * called, so a failure to record the audit is logged rather than failing the request.- *- * @param identifier the Gravitino identifier of the object- * @param type {@link Entity.EntityType#SCHEMA}, {@link Entity.EntityType#TABLE} or {@link- * Entity.EntityType#VIEW}- * @param user the authenticated user who created the object- */- static void recordCreator(NameIdentifier identifier, Entity.EntityType type, String user) {- EntityStore store = GravitinoEnv.getInstance().entityStore();- if (store == null) {- return;- }- Instant createTime = Instant.now();- try {- switch (type) {- case SCHEMA:- store.update(- identifier,- SchemaEntity.class,- type,- schema -> withCreator(schema, withCreator(schema.auditInfo(), user, createTime)));- break;- case TABLE:- store.update(- identifier,- TableEntity.class,- type,- table -> withCreator(table, withCreator(table.auditInfo(), user, createTime)));- break;- case VIEW:- store.update(- identifier,- ViewEntity.class,- type,- view -> withCreator(view, withCreator(view.auditInfo(), user, createTime)));- break;- default:- throw new IllegalArgumentException("Unsupported entity type: " + type);- }- } catch (Exception e) {- LOG.warn("Failed to record the creator of {} {} created by {}", type, identifier, user, e);- }- }-- @VisibleForTesting- static AuditInfo withCreator(AuditInfo audit, String user, Instant createTime) {- if (audit != null && audit.creator() != null) {- return audit;- }- return AuditInfo.builder()- .withCreator(user)- .withCreateTime(createTime)- .withLastModifier(audit == null ? null : audit.lastModifier())- .withLastModifiedTime(audit == null ? null : audit.lastModifiedTime())- .build();- }-- private static SchemaEntity withCreator(SchemaEntity schema, AuditInfo audit) {- return SchemaEntity.builder()- .withId(schema.id())- .withName(schema.name())- .withNamespace(schema.namespace())- .withComment(schema.comment())- .withProperties(schema.properties())- .withAuditInfo(audit)- .build();- }-- private static TableEntity withCreator(TableEntity table, AuditInfo audit) {- return TableEntity.builder()- .withId(table.id())- .withName(table.name())- .withNamespace(table.namespace())- .withComment(table.comment())- .withProperties(table.properties())- .withColumns(table.columns())- .withPartitioning(table.partitioning())- .withDistribution(table.distribution())- .withSortOrders(table.sortOrders())- .withIndexes(table.indexes())- .withAuditInfo(audit)- .build();- }-- private static ViewEntity withCreator(ViewEntity view, AuditInfo audit) {- return ViewEntity.builder()- .withId(view.id())- .withName(view.name())- .withNamespace(view.namespace())- .withComment(view.comment())- .withColumns(view.columns())- .withRepresentations(view.representations())- .withDefaultCatalog(view.defaultCatalog())- .withDefaultSchema(view.defaultSchema())- .withProperties(view.properties())- .withAuditInfo(audit)- .build();- }-}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.javaindex 2a520098b0..8ba01b9a52 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java@@ -20,7 +20,9 @@ package org.apache.gravitino.iceberg.service.dispatcher;import com.google.common.annotations.VisibleForTesting;import java.io.IOException;+import java.time.Instant;import java.util.ArrayList;+import java.util.Arrays;import java.util.Collections;import java.util.List;import org.apache.gravitino.Entity;@@ -37,6 +39,7 @@ import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerConteimport org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;@@ -88,23 +91,24 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationnewlyOwned.addAll(getMissingAncestors(context, leaf));return dispatcher.createNamespace(context, createRequest);});- // SchemaMetaService.insertSchema splits the leaf's logical name and auto-creates a- // Gravitino entity row for each ancestor, so a single leaf import covers the branch.+ // Import ancestors from outermost to innermost before the leaf. Only namespaces this+ // request actually created receive its audit; pre-existing external ancestors retain+ // their source audit or unknown creation fields. An ordinary load may already have+ // registered a newly created ancestor, in which case importSchema fills its missing audit.// Failures propagate intentionally: swallowing would leave a namespace in Iceberg// that Gravitino doesn't know about. Do not drop the namespace on import failure: another// client may already have created objects in it.- importSchema(catalogName, leaf);+ AuditInfo audit =+ AuditInfo.builder().withCreator(context.userName()).withCreateTime(Instant.now()).build();+ for (int level = 1; level < leaf.length(); level++) {+ Namespace ancestor = Namespace.of(Arrays.copyOf(leaf.levels(), level));+ importSchema(catalogName, ancestor, newlyOwned.contains(ancestor) ? audit : AuditInfo.EMPTY);+ }+ importSchema(catalogName, leaf, audit);// getMissingAncestors() only returns the not-yet-existing ancestors; append the leaf so that// every newly-created namespace in this request gets an owner assigned.newlyOwned.add(leaf);- for (Namespace created : newlyOwned) {- IcebergEntityAuditUtils.recordCreator(- IcebergIdentifierUtils.toGravitinoSchemaIdentifier(- metalake, catalogName, created, HierarchicalSchemaUtil.schemaSeparator()),- Entity.EntityType.SCHEMA,- context.userName());- }IcebergOwnershipUtils.setSchemaOwners(metalake,catalogName,@@ -231,15 +235,11 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation// Import is intentionally NOT wrapped in try-catch: if it fails the table exists in Iceberg// but not in Gravitino, and silently swallowing that would mislead callers into thinking the// entity is registered. Surface the failure so the caller can react.- importTable(context.catalogName(), namespace, registerTableRequest.name());- IcebergEntityAuditUtils.recordCreator(- IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake,- context.catalogName(),- TableIdentifier.of(namespace, registerTableRequest.name()),- HierarchicalSchemaUtil.schemaSeparator()),- Entity.EntityType.TABLE,- context.userName());+ importTable(+ context.catalogName(),+ namespace,+ registerTableRequest.name(),+ AuditInfo.builder().withCreator(context.userName()).withCreateTime(Instant.now()).build());IcebergOwnershipUtils.setTableOwner(metalake,@@ -266,15 +266,11 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation// Import is intentionally NOT wrapped in try-catch: if it fails the view exists in Iceberg// but not in Gravitino, and silently swallowing that would mislead callers into thinking the// entity is registered. Surface the failure so the caller can react.- importView(context.catalogName(), namespace, registerViewRequest.name());- IcebergEntityAuditUtils.recordCreator(- IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake,- context.catalogName(),- TableIdentifier.of(namespace, registerViewRequest.name()),- HierarchicalSchemaUtil.schemaSeparator()),- Entity.EntityType.VIEW,- context.userName());+ importView(+ context.catalogName(),+ namespace,+ registerViewRequest.name(),+ AuditInfo.builder().withCreator(context.userName()).withCreateTime(Instant.now()).build());IcebergOwnershipUtils.setViewOwner(metalake,@@ -287,15 +283,17 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationreturn response;}- private void importView(String catalogName, Namespace namespace, String viewName) {+ private void importView(+ String catalogName, Namespace namespace, String viewName, AuditInfo auditInfo) {ViewDispatcher viewDispatcher = GravitinoEnv.getInstance().internalViewDispatcher();if (viewDispatcher != null) {- viewDispatcher.loadView(+ viewDispatcher.importView(IcebergIdentifierUtils.toGravitinoTableIdentifier(metalake,catalogName,TableIdentifier.of(namespace, viewName),- HierarchicalSchemaUtil.schemaSeparator()));+ HierarchicalSchemaUtil.schemaSeparator()),+ auditInfo);}}@@ -337,24 +335,27 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperation}}- private void importTable(String catalogName, Namespace namespace, String tableName) {+ private void importTable(+ String catalogName, Namespace namespace, String tableName, AuditInfo auditInfo) {TableDispatcher tableDispatcher = GravitinoEnv.getInstance().internalTableDispatcher();if (tableDispatcher != null) {- tableDispatcher.loadTable(+ tableDispatcher.importTable(IcebergIdentifierUtils.toGravitinoTableIdentifier(metalake,catalogName,TableIdentifier.of(namespace, tableName),- HierarchicalSchemaUtil.schemaSeparator()));+ HierarchicalSchemaUtil.schemaSeparator()),+ auditInfo);}}- private void importSchema(String catalogName, Namespace namespace) {+ private void importSchema(String catalogName, Namespace namespace, AuditInfo auditInfo) {SchemaDispatcher schemaDispatcher = GravitinoEnv.getInstance().internalSchemaDispatcher();if (schemaDispatcher != null) {- schemaDispatcher.loadSchema(+ schemaDispatcher.importSchema(IcebergIdentifierUtils.toGravitinoSchemaIdentifier(- metalake, catalogName, namespace, HierarchicalSchemaUtil.schemaSeparator()));+ metalake, catalogName, namespace, HierarchicalSchemaUtil.schemaSeparator()),+ auditInfo);}}}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.javaindex 7e5c39c066..4c346449ce 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergTableHookDispatcher.java@@ -256,15 +256,11 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatchIcebergRequestContext context, Namespace namespace, String tableName) {// Validate request metadata before the backend operation. An unexpected import failure must// propagate without deleting a table that another client may already have updated or recreated.- importTableEntity(context.catalogName(), namespace, tableName);- IcebergEntityAuditUtils.recordCreator(- IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake,- context.catalogName(),- TableIdentifier.of(namespace, tableName),- HierarchicalSchemaUtil.schemaSeparator()),- Entity.EntityType.TABLE,- context.userName());+ importTableEntity(+ context.catalogName(),+ namespace,+ tableName,+ AuditInfo.builder().withCreator(context.userName()).withCreateTime(Instant.now()).build());IcebergOwnershipUtils.setTableOwner(metalake,context.catalogName(),@@ -275,14 +271,20 @@ public class IcebergTableHookDispatcher implements IcebergTableOperationDispatch}private void importTableEntity(String catalogName, Namespace namespace, String tableName) {+ importTableEntity(catalogName, namespace, tableName, AuditInfo.EMPTY);+ }++ private void importTableEntity(+ String catalogName, Namespace namespace, String tableName, AuditInfo auditInfo) {TableDispatcher tableDispatcher = GravitinoEnv.getInstance().internalTableDispatcher();if (tableDispatcher != null) {- tableDispatcher.loadTable(+ tableDispatcher.importTable(IcebergIdentifierUtils.toGravitinoTableIdentifier(metalake,catalogName,TableIdentifier.of(namespace, tableName),- HierarchicalSchemaUtil.schemaSeparator()));+ HierarchicalSchemaUtil.schemaSeparator()),+ auditInfo);}}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.javaindex 650276d8eb..cc8336205e 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java@@ -19,6 +19,7 @@package org.apache.gravitino.iceberg.service.dispatcher;import java.io.IOException;+import java.time.Instant;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;@@ -27,6 +28,7 @@ import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.listener.api.event.IcebergRequestContext;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.utils.HierarchicalSchemaUtil;import org.apache.iceberg.catalog.Namespace;@@ -46,7 +48,8 @@ import org.slf4j.LoggerFactory;** <p>This is the key integration point between Iceberg REST views and Gravitino's view management* system. When a view is created or loaded through Iceberg REST, this dispatcher ensures that- * Gravitino is aware of the view by calling {@link ViewDispatcher#loadView}.+ * Gravitino is aware of the view by calling {@link ViewDispatcher#importView(NameIdentifier,+ * AuditInfo)}.*/public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcher {@@ -72,15 +75,11 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcherLoadViewResponse response = dispatcher.createView(context, namespace, createViewRequest);// Then import it into Gravitino so Gravitino is aware of the view- importView(context.catalogName(), namespace, createViewRequest.name());- IcebergEntityAuditUtils.recordCreator(- IcebergIdentifierUtils.toGravitinoTableIdentifier(- metalake,- context.catalogName(),- TableIdentifier.of(namespace, createViewRequest.name()),- HierarchicalSchemaUtil.schemaSeparator()),- Entity.EntityType.VIEW,- context.userName());+ importView(+ context.catalogName(),+ namespace,+ createViewRequest.name(),+ AuditInfo.builder().withCreator(context.userName()).withCreateTime(Instant.now()).build());// Set ownership for the newly created view.IcebergOwnershipUtils.setViewOwner(@@ -184,9 +183,9 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcher/*** Import a view into Gravitino's metadata catalog by loading it through the ViewDispatcher.*- * <p>This method calls {@link ViewDispatcher#loadView} which delegates to the underlying- * catalog's ViewCatalog implementation. This ensures Gravitino is aware of the view and can apply- * authorization policies to it.+ * <p>This method calls {@link ViewDispatcher#importView(NameIdentifier, AuditInfo)} which loads+ * the existing view and registers it in Gravitino's entity store so authorization policies can+ * apply to it.** <p>This is a best-effort operation - if it fails, we log a warning but don't fail the Iceberg* REST operation, as the view was successfully created in the underlying catalog.@@ -196,15 +195,21 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcher* @param viewName The name of the view.*/private void importView(String catalogName, Namespace namespace, String viewName) {+ importView(catalogName, namespace, viewName, AuditInfo.EMPTY);+ }++ private void importView(+ String catalogName, Namespace namespace, String viewName, AuditInfo auditInfo) {ViewDispatcher viewDispatcher = GravitinoEnv.getInstance().internalViewDispatcher();if (viewDispatcher != null) {try {- viewDispatcher.loadView(+ viewDispatcher.importView(IcebergIdentifierUtils.toGravitinoTableIdentifier(metalake,catalogName,TableIdentifier.of(namespace, viewName),- HierarchicalSchemaUtil.schemaSeparator()));+ HierarchicalSchemaUtil.schemaSeparator()),+ auditInfo);LOG.info("Successfully imported view into Gravitino: {}.{}.{}.{}",metalake,diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.javadeleted file mode 100644index 52abb08efd..0000000000--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergEntityAuditUtils.java+++ /dev/null@@ -1,47 +0,0 @@-/*- * 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.iceberg.service.dispatcher;--import java.time.Instant;-import org.apache.gravitino.meta.AuditInfo;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--public class TestIcebergEntityAuditUtils {-- @Test- public void testCreatorIsSetOnlyWhenMissing() {- Instant now = Instant.now();- AuditInfo empty = IcebergEntityAuditUtils.withCreator(AuditInfo.EMPTY, "alice", now);- Assertions.assertEquals("alice", empty.creator());- Assertions.assertEquals(now, empty.createTime());- Assertions.assertNull(empty.lastModifier());-- AuditInfo modifiedOnly =- AuditInfo.builder().withLastModifier("bob").withLastModifiedTime(now).build();- AuditInfo filled = IcebergEntityAuditUtils.withCreator(modifiedOnly, "alice", now);- Assertions.assertEquals("alice", filled.creator());- Assertions.assertEquals("bob", filled.lastModifier());-- AuditInfo reported =- AuditInfo.builder().withCreator("carol").withCreateTime(Instant.EPOCH).build();- Assertions.assertSame(- reported, IcebergEntityAuditUtils.withCreator(reported, "alice", Instant.now()));- }-}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergImportAuditPersistence.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergImportAuditPersistence.javanew file mode 100644index 0000000000..fd5478b646--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergImportAuditPersistence.java@@ -0,0 +1,522 @@+/*+ * 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.iceberg.service.dispatcher;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.when;++import java.time.Instant;+import java.util.Arrays;+import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.stream.Collectors;+import javax.annotation.Nullable;+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.NameIdentifier;+import org.apache.gravitino.TestCatalog;+import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.cache.NoOpsCache;+import org.apache.gravitino.catalog.CatalogManager;+import org.apache.gravitino.catalog.EntityCombinedTable;+import org.apache.gravitino.catalog.SchemaOperationDispatcher;+import org.apache.gravitino.catalog.TableOperationDispatcher;+import org.apache.gravitino.catalog.ViewOperationDispatcher;+import org.apache.gravitino.connector.TestCatalogOperations;+import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;+import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;+import org.apache.gravitino.listener.api.event.IcebergRequestContext;+import org.apache.gravitino.lock.LockManager;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.ColumnEntity;+import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;+import org.apache.gravitino.rel.View;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Indexes;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.EntityChangeLogPoller;+import org.apache.gravitino.storage.relational.RelationalEntityStore;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.service.EntityIdService;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.rest.requests.CreateNamespaceRequest;+import org.apache.iceberg.rest.requests.CreateTableRequest;+import org.apache.iceberg.rest.requests.CreateViewRequest;+import org.apache.iceberg.rest.responses.CreateNamespaceResponse;+import org.apache.iceberg.rest.responses.LoadTableResponse;+import org.apache.iceberg.rest.responses.LoadViewResponse;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.TestTemplate;++/** Exercises IRC hooks, core imports and real database writes together. */+public class TestIcebergImportAuditPersistence extends TestJDBCBackend {+ private static final String METALAKE = "audit_metalake";+ private static final String CATALOG = "audit_catalog";+ private static final AuditInfo ALICE =+ AuditInfo.builder().withCreator("alice").withCreateTime(Instant.EPOCH).build();++ @Nullable private static Object previousConfig;+ @Nullable private static Object previousIdGenerator;+ @Nullable private static Object previousIdResolver;++ @BeforeAll+ static void saveBackendExtensionGlobals() throws IllegalAccessException {+ previousConfig = FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);+ previousIdGenerator = FieldUtils.readField(GravitinoEnv.getInstance(), "idGenerator", true);+ previousIdResolver =+ FieldUtils.readStaticField(EntityIdService.class, "entityIdResolver", true);+ }++ @AfterAll+ static void restoreBackendExtensionGlobals() throws IllegalAccessException {+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previousConfig, true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "idGenerator", previousIdGenerator, true);+ FieldUtils.writeStaticField(+ EntityIdService.class, "entityIdResolver", previousIdResolver, true);+ }++ @TestTemplate+ void testTableHookFillsAuditAfterOrdinaryLoad() throws Exception {+ try (Fixture f = new Fixture()) {+ NameIdentifier schema = f.ident("table_schema");+ f.schemas.createSchema(schema, "", Map.of("k1", "v1", "k2", "v2"));+ NameIdentifier table = NameIdentifier.of(METALAKE, CATALOG, schema.name(), "table");+ IcebergTableOperationDispatcher backendDispatcher =+ mock(IcebergTableOperationDispatcher.class);+ CreateTableRequest request = mock(CreateTableRequest.class);+ when(request.name()).thenReturn(table.name());+ Namespace namespace = Namespace.of(schema.name());+ when(backendDispatcher.createTable(f.context, namespace, request))+ .thenAnswer(+ call -> {+ f.source.createTable(+ table,+ new Column[] {Column.of("col", Types.StringType.get())},+ "",+ Map.of(),+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ Indexes.EMPTY_INDEXES);+ FieldUtils.writeField(+ f.source.loadTable(table), "auditInfo", AuditInfo.EMPTY, true);+ f.tables.loadTable(table);+ Assertions.assertNull(+ f.store+ .get(table, Entity.EntityType.TABLE, TableEntity.class)+ .auditInfo()+ .creator());+ return mock(LoadTableResponse.class);+ });+ new IcebergTableHookDispatcher(+ backendDispatcher, mock(IcebergNamespaceOperationDispatcher.class))+ .createTable(f.context, namespace, request);+ TableEntity stored = f.store.get(table, Entity.EntityType.TABLE, TableEntity.class);+ Assertions.assertEquals("alice", stored.auditInfo().creator());+ Assertions.assertEquals(+ stored.auditInfo().creator(), stored.columns().get(0).auditInfo().creator());+ Assertions.assertEquals(+ stored.auditInfo().createTime(), stored.columns().get(0).auditInfo().createTime());+ }+ }++ @TestTemplate+ void testTableAuditRecoveryPreservesColumnFields() throws Exception {+ try (Fixture f = new Fixture()) {+ NameIdentifier schema = f.ident("column_audit_schema");+ f.schemas.createSchema(schema, "", Map.of("k1", "v1", "k2", "v2"));+ NameIdentifier table = NameIdentifier.of(METALAKE, CATALOG, schema.name(), "table");+ Column[] columns = {+ Column.of(+ "missing",+ Types.StringType.get(),+ "comment",+ false,+ false,+ Column.DEFAULT_VALUE_NOT_SET),+ Column.of("modified", Types.StringType.get()),+ Column.of("owned", Types.StringType.get())+ };+ f.source.createTable(+ table,+ columns,+ "",+ Map.of(),+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ Indexes.EMPTY_INDEXES);+ FieldUtils.writeField(f.source.loadTable(table), "auditInfo", AuditInfo.EMPTY, true);+ f.tables.loadTable(table);+ AuditInfo modified =+ AuditInfo.builder()+ .withCreateTime(Instant.EPOCH.plusSeconds(1))+ .withLastModifier("modifier")+ .withLastModifiedTime(Instant.EPOCH.plusSeconds(2))+ .build();+ AuditInfo owned =+ AuditInfo.builder()+ .withCreator("bob")+ .withCreateTime(Instant.EPOCH.plusSeconds(3))+ .withLastModifier("editor")+ .withLastModifiedTime(Instant.EPOCH.plusSeconds(4))+ .build();+ TableEntity before =+ f.store.update(+ table,+ TableEntity.class,+ Entity.EntityType.TABLE,+ current ->+ TableEntity.builder()+ .withId(current.id())+ .withName(current.name())+ .withNamespace(current.namespace())+ .withComment(current.comment())+ .withProperties(current.properties())+ .withAuditInfo(current.auditInfo())+ .withColumns(+ current.columns().stream()+ .map(+ column ->+ ColumnEntity.toColumnEntity(+ columns[column.position()],+ column.position(),+ column.id(),+ "modified".equals(column.name())+ ? modified+ : "owned".equals(column.name())+ ? owned+ : AuditInfo.EMPTY))+ .collect(Collectors.toList()))+ .build());+ f.tables.importTable(table, ALICE);+ TableEntity stored = f.store.get(table, Entity.EntityType.TABLE, TableEntity.class);+ Map<String, ColumnEntity> storedColumns =+ stored.columns().stream().collect(Collectors.toMap(ColumnEntity::name, column -> column));+ Assertions.assertEquals("alice", stored.auditInfo().creator());+ Assertions.assertEquals("alice", storedColumns.get("missing").auditInfo().creator());+ Assertions.assertEquals(Instant.EPOCH, storedColumns.get("missing").auditInfo().createTime());+ Assertions.assertEquals("alice", storedColumns.get("modified").auditInfo().creator());+ Assertions.assertEquals(+ modified.createTime(), storedColumns.get("modified").auditInfo().createTime());+ Assertions.assertEquals(+ modified.lastModifier(), storedColumns.get("modified").auditInfo().lastModifier());+ Assertions.assertEquals(+ modified.lastModifiedTime(),+ storedColumns.get("modified").auditInfo().lastModifiedTime());+ Assertions.assertEquals(columns.length, storedColumns.size());+ for (ColumnEntity expected : before.columns()) {+ ColumnEntity actual = storedColumns.get(expected.name());+ if ("owned".equals(expected.name())) {+ Assertions.assertEquals(expected, actual);+ }+ Assertions.assertEquals(expected.id(), actual.id());+ Assertions.assertEquals(expected.name(), actual.name());+ Assertions.assertEquals(expected.position(), actual.position());+ Assertions.assertEquals(expected.dataType(), actual.dataType());+ Assertions.assertEquals(expected.comment(), actual.comment());+ Assertions.assertEquals(expected.nullable(), actual.nullable());+ Assertions.assertEquals(expected.autoIncrement(), actual.autoIncrement());+ Assertions.assertEquals(expected.defaultValue(), actual.defaultValue());+ }+ }+ }++ @TestTemplate+ void testTableImportReturnsRecreatedEntityWithoutOldAudit() throws Exception {+ try (Fixture f = new Fixture()) {+ NameIdentifier schema = f.ident("recreated_table_schema");+ f.schemas.createSchema(schema, "", Map.of("k1", "v1", "k2", "v2"));+ NameIdentifier table = NameIdentifier.of(METALAKE, CATALOG, schema.name(), "table");+ f.source.createTable(+ table,+ new Column[] {Column.of("col", Types.StringType.get())},+ "",+ Map.of(),+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ Indexes.EMPTY_INDEXES);+ FieldUtils.writeField(f.source.loadTable(table), "auditInfo", AuditInfo.EMPTY, true);+ f.tables.loadTable(table);+ TableEntity observed = f.store.get(table, Entity.EntityType.TABLE, TableEntity.class);+ AtomicBoolean replaced = new AtomicBoolean();+ doAnswer(+ call -> {+ if (replaced.compareAndSet(false, true)) {+ f.store.delete(table, Entity.EntityType.TABLE);+ TableEntity recreated =+ TableEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName(observed.name())+ .withNamespace(observed.namespace())+ .withColumns(+ Arrays.asList(+ ColumnEntity.toColumnEntity(+ Column.of("col", Types.StringType.get()),+ 0,+ RandomIdGenerator.INSTANCE.nextId(),+ AuditInfo.EMPTY)))+ .withAuditInfo(AuditInfo.EMPTY)+ .build();+ f.store.put(recreated, false);+ }+ return call.callRealMethod();+ })+ .when(f.store)+ .update(eq(table), eq(TableEntity.class), eq(Entity.EntityType.TABLE), any());+ EntityCombinedTable imported = (EntityCombinedTable) f.tables.importTable(table, ALICE);+ Assertions.assertNull(imported.auditInfo().creator());+ TableEntity stored = f.store.get(table, Entity.EntityType.TABLE, TableEntity.class);+ Assertions.assertTrue(replaced.get());+ Assertions.assertNotEquals(observed.id(), stored.id());+ Assertions.assertEquals(stored.id(), imported.tableFromGravitino().id());+ Assertions.assertNull(stored.auditInfo().creator());+ Assertions.assertNull(stored.auditInfo().createTime());+ Assertions.assertNull(stored.columns().get(0).auditInfo().creator());+ Assertions.assertNull(f.tables.loadTable(table).auditInfo().creator());+ }+ }++ @TestTemplate+ void testViewHookFillsAuditAfterOrdinaryLoad() throws Exception {+ try (Fixture f = new Fixture()) {+ NameIdentifier schema = f.ident("view_schema");+ f.schemas.createSchema(schema, "", Map.of("k1", "v1", "k2", "v2"));+ NameIdentifier view = NameIdentifier.of(METALAKE, CATALOG, schema.name(), "view");+ IcebergViewOperationDispatcher backendDispatcher = mock(IcebergViewOperationDispatcher.class);+ CreateViewRequest request = mock(CreateViewRequest.class);+ when(request.name()).thenReturn(view.name());+ Namespace namespace = Namespace.of(schema.name());+ when(backendDispatcher.createView(f.context, namespace, request))+ .thenAnswer(+ call -> {+ f.source.views.put(view, sourceView(view.name(), Map.of()));+ f.views.loadView(view);+ return mock(LoadViewResponse.class);+ });+ new IcebergViewHookDispatcher(+ backendDispatcher, mock(IcebergNamespaceOperationDispatcher.class), METALAKE)+ .createView(f.context, namespace, request);+ Assertions.assertEquals(+ "alice",+ f.store.get(view, Entity.EntityType.VIEW, ViewEntity.class).auditInfo().creator());+ }+ }++ @TestTemplate+ void testNamespaceHookAuditsOnlyCreatedNamespaces() throws Exception {+ try (Fixture f = new Fixture()) {+ for (int scenario = 0; scenario < 3; scenario++) {+ boolean parentExists = scenario != 0;+ boolean knownAudit = scenario == 1;+ String root = "parent_" + scenario;+ Namespace parent = Namespace.of(root);+ Namespace leaf = Namespace.of(root, "leaf");+ if (parentExists) {+ f.createSourceSchema(+ root,+ knownAudit+ ? AuditInfo.builder()+ .withCreator("original")+ .withCreateTime(Instant.EPOCH)+ .build()+ : AuditInfo.EMPTY);+ }+ IcebergNamespaceOperationDispatcher backendDispatcher =+ mock(IcebergNamespaceOperationDispatcher.class);+ when(backendDispatcher.namespaceExists(f.context, parent)).thenReturn(parentExists);+ CreateNamespaceRequest request =+ CreateNamespaceRequest.builder().withNamespace(leaf).build();+ when(backendDispatcher.createNamespace(f.context, request))+ .thenAnswer(+ call -> {+ if (!parentExists) {+ f.createSourceSchema(root, AuditInfo.EMPTY);+ }+ f.createSourceSchema(root + ":leaf", AuditInfo.EMPTY);+ return mock(CreateNamespaceResponse.class);+ });+ AtomicBoolean ordinaryLoadWon = new AtomicBoolean();+ doAnswer(+ call -> {+ // The backend branch lock has been released, but the hook has not imported yet.+ if (ordinaryLoadWon.compareAndSet(false, true)) {+ f.schemas.loadSchema(f.ident(root));+ f.schemas.loadSchema(f.ident(root + ":leaf"));+ }+ return call.callRealMethod();+ })+ .when(f.schemas)+ .importSchema(any(), any());+ new IcebergNamespaceHookDispatcher(backendDispatcher).createNamespace(f.context, request);+ SchemaEntity parentEntity =+ f.store.get(f.ident(root), Entity.EntityType.SCHEMA, SchemaEntity.class);+ SchemaEntity leafEntity =+ f.store.get(f.ident(root + ":leaf"), Entity.EntityType.SCHEMA, SchemaEntity.class);+ Assertions.assertEquals(+ parentExists ? knownAudit ? "original" : null : "alice",+ parentEntity.auditInfo().creator());+ Assertions.assertEquals("alice", leafEntity.auditInfo().creator());+ Assertions.assertNotNull(leafEntity.auditInfo().createTime());+ if (parentExists) {+ Assertions.assertEquals(+ knownAudit ? Instant.EPOCH : null, parentEntity.auditInfo().createTime());+ }+ }+ }+ }++ private static View sourceView(String name, Map<String, String> properties) {+ View view = mock(View.class);+ when(view.name()).thenReturn(name);+ when(view.properties()).thenReturn(properties);+ when(view.auditInfo()).thenReturn(AuditInfo.EMPTY);+ when(view.columns()).thenReturn(new Column[0]);+ when(view.representations())+ .thenReturn(+ new Representation[] {+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT 1").build()+ });+ return view;+ }++ private class Fixture implements AutoCloseable {+ private final Map<String, Object> previous = new HashMap<>();+ private final RelationalEntityStore store;+ private final CatalogManager catalogs;+ private final SecretManager secrets;+ private final SchemaOperationDispatcher schemas;+ private final TableOperationDispatcher tables;+ private final ViewOperationDispatcher views;+ private final TestCatalogOperations source;+ private final IcebergRequestContext context;+ private final Class<?> contextHolder;+ private final Object previousContext;++ private Fixture() throws Exception {+ Config config = new Config(false) {};+ config.set(Configs.CATALOG_LOAD_ISOLATED, false);+ config.set(Configs.CACHE_ENABLED, false);+ config.set(Configs.SCHEMA_SEPARATOR, ":");+ install("config", config);+ install("idGenerator", RandomIdGenerator.INSTANCE);+ install("lockManager", new LockManager(config));+ store = spy(new RelationalEntityStore());+ FieldUtils.writeField(store, "backend", backend, true);+ FieldUtils.writeField(store, "cache", new NoOpsCache(config), true);+ // The extension owns the real backend; background cache polling is outside these tests.+ FieldUtils.writeField(+ store, "entityChangeLogPoller", mock(EntityChangeLogPoller.class), true);+ createAndInsertMakeLake(METALAKE);+ secrets = new SecretManager(config);+ catalogs = new CatalogManager(config, store, RandomIdGenerator.INSTANCE, secrets);+ install("catalogManager", catalogs);+ install("entityStore", store);+ catalogs.createCatalog(+ NameIdentifier.of(METALAKE, CATALOG),+ Catalog.Type.RELATIONAL,+ "test",+ "",+ Map.of(+ TestCatalog.PROPERTY_KEY1,+ "v1",+ TestCatalog.PROPERTY_KEY2,+ "v2",+ TestCatalog.PROPERTY_KEY5_PREFIX + "1",+ "v3"));+ source =+ catalogs.doWithCatalog(+ NameIdentifier.of(METALAKE, CATALOG),+ c -> (TestCatalogOperations) ((TestCatalog) c).ops());+ schemas =+ spy(new SchemaOperationDispatcher(catalogs, store, RandomIdGenerator.INSTANCE, secrets));+ tables =+ new TableOperationDispatcher(+ catalogs, store, RandomIdGenerator.INSTANCE, () -> schemas, secrets);+ views =+ new ViewOperationDispatcher(+ catalogs, store, RandomIdGenerator.INSTANCE, () -> schemas, secrets);+ install("internalSchemaDispatcher", schemas);+ install("internalTableDispatcher", tables);+ install("internalViewDispatcher", views);+ install("internalOwnerDispatcher", mock(OwnerDispatcher.class));+ contextHolder =+ Arrays.stream(IcebergRESTServerContext.class.getDeclaredClasses())+ .filter(c -> c.getSimpleName().equals("InstanceHolder"))+ .findFirst()+ .orElseThrow();+ previousContext = FieldUtils.readStaticField(contextHolder, "INSTANCE", true);+ IcebergConfigProvider provider = mock(IcebergConfigProvider.class);+ when(provider.getMetalakeName()).thenReturn(METALAKE);+ when(provider.getDefaultCatalogName()).thenReturn(CATALOG);+ IcebergRESTServerContext.create(provider, false, false, true, null);+ context = mock(IcebergRequestContext.class);+ when(context.catalogName()).thenReturn(CATALOG);+ when(context.userName()).thenReturn("alice");+ }++ private void install(String field, Object value) throws IllegalAccessException {+ if (!previous.containsKey(field)) {+ previous.put(field, FieldUtils.readField(GravitinoEnv.getInstance(), field, true));+ }+ FieldUtils.writeField(GravitinoEnv.getInstance(), field, value, true);+ }++ private NameIdentifier ident(String schema) {+ return NameIdentifier.of(METALAKE, CATALOG, schema);+ }++ private void createSourceSchema(String name, AuditInfo audit) throws Exception {+ Object schema = source.createSchema(ident(name), "", Map.of("k1", "v1", "k2", "v2"));+ FieldUtils.writeField(schema, "auditInfo", audit, true);+ }++ /** {@inheritDoc} */+ @Override+ public void close() throws Exception {+ catalogs.close();+ secrets.close();+ FieldUtils.writeStaticField(contextHolder, "INSTANCE", previousContext, true);+ for (Map.Entry<String, Object> entry : previous.entrySet()) {+ FieldUtils.writeField(GravitinoEnv.getInstance(), entry.getKey(), entry.getValue(), true);+ }+ }+ }+}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.javaindex f5f4ef801b..2227665017 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java@@ -50,7 +50,7 @@ import org.apache.gravitino.iceberg.service.provider.IcebergConfigProvider;import org.apache.gravitino.listener.api.event.IcebergRequestContext;import org.apache.gravitino.lock.LockManager;import org.apache.gravitino.lock.TreeLock;-import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.meta.AuditInfo;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.exceptions.BadRequestException;import org.apache.iceberg.rest.requests.CreateNamespaceRequest;@@ -262,7 +262,7 @@ public class TestIcebergNamespaceHookDispatcher {.thenReturn(mock(CreateNamespaceResponse.class));RuntimeException importFailure =new RuntimeException("Failed to import schema entity to the store");- when(mockInternalSchemaDispatcher.loadSchema(any())).thenThrow(importFailure);+ when(mockInternalSchemaDispatcher.importSchema(any(), any())).thenThrow(importFailure);RuntimeException thrown =Assertions.assertThrows(@@ -311,11 +311,21 @@ public class TestIcebergNamespaceHookDispatcher {NameIdentifier.of(TEST_METALAKE, TEST_CATALOG, "test_schema", "test_view");when(mockEntityStore.exists(eq(expectedIdent), eq(Entity.EntityType.VIEW))).thenReturn(false);+ when(mockInternalViewDispatcher.importView(any(), any()))+ .thenAnswer(+ invocation -> {+ AuditInfo audit = invocation.getArgument(1);+ Assertions.assertEquals(TEST_USER, audit.creator());+ Assertions.assertNotNull(audit.createTime());+ return null;+ });+LoadViewResponse response = hookDispatcher.registerView(mockContext, namespace, request);+ verify(mockEntityStore, never()).update(any(), any(), any(), any());verify(mockDispatcher).registerView(mockContext, namespace, request);- verify(mockInternalViewDispatcher).loadView(eq(expectedIdent));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher).importView(eq(expectedIdent), any());+ verify(mockViewDispatcher, never()).importView(any(), any());verify(mockInternalOwnerDispatcher).setOwner(any(), any(), eq(TEST_USER), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());Assertions.assertEquals(mockResponse, response);@@ -341,7 +351,7 @@ public class TestIcebergNamespaceHookDispatcher {verify(mockDispatcher).registerView(mockContext, namespace, request);// Import and setOwner are both skipped since the entity already exists- verify(mockInternalViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, never()).importView(any(), any());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());Assertions.assertEquals(mockResponse, response);}@@ -362,9 +372,11 @@ public class TestIcebergNamespaceHookDispatcher {NameIdentifier.of(TEST_METALAKE, TEST_CATALOG, "test_schema", "test_view");when(mockEntityStore.exists(eq(expectedIdent), eq(Entity.EntityType.VIEW))).thenReturn(false);- // View import (loadView) throwing must propagate so the caller learns the view exists in+ // View import (importView) throwing must propagate so the caller learns the view exists in// Iceberg but is not registered in Gravitino. setOwner is therefore unreachable.- doThrow(new RuntimeException("Import failed")).when(mockInternalViewDispatcher).loadView(any());+ doThrow(new RuntimeException("Import failed"))+ .when(mockInternalViewDispatcher)+ .importView(any(), any());RuntimeException thrown =Assertions.assertThrows(@@ -399,7 +411,7 @@ public class TestIcebergNamespaceHookDispatcher {() -> hookDispatcher.registerView(mockContext, namespace, request));Assertions.assertEquals(IOException.class, thrown.getCause().getClass());verify(mockDispatcher).registerView(mockContext, namespace, request);- verify(mockInternalViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, never()).importView(any(), any());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@@ -412,11 +424,11 @@ public class TestIcebergNamespaceHookDispatcher {CreateNamespaceResponse mockResponse = mock(CreateNamespaceResponse.class);when(mockDispatcher.createNamespace(mockContext, mockRequest)).thenReturn(mockResponse);- // Schema import (loadSchema) throwing must propagate so the caller learns the namespace+ // Schema import (importSchema) throwing must propagate so the caller learns the namespace// exists in Iceberg but is not registered in Gravitino. setOwner is therefore unreachable.doThrow(new RuntimeException("Import failed")).when(mockInternalSchemaDispatcher)- .loadSchema(any());+ .importSchema(any(), any());RuntimeException thrown =Assertions.assertThrows(@@ -425,7 +437,7 @@ public class TestIcebergNamespaceHookDispatcher {Assertions.assertEquals("Import failed", thrown.getMessage());verify(mockInternalOwnerDispatcher, never()).setOwners(any(), any(), any(), any());verify(mockOwnerDispatcher, never()).setOwners(any(), any(), any(), any());- verify(mockSchemaDispatcher, never()).loadSchema(any());+ verify(mockSchemaDispatcher, never()).importSchema(any(), any());}@Test@@ -442,7 +454,7 @@ public class TestIcebergNamespaceHookDispatcher {LoadTableResponse response = hookDispatcher.registerTable(mockContext, namespace, mockRequest);Assertions.assertSame(mockResponse, response);- verify(mockInternalTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher, never()).importTable(any(), any());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@@ -458,11 +470,21 @@ public class TestIcebergNamespaceHookDispatcher {when(mockDispatcher.registerTable(mockContext, namespace, mockRequest)).thenReturn(mockResponse);+ when(mockInternalTableDispatcher.importTable(any(), any()))+ .thenAnswer(+ invocation -> {+ AuditInfo audit = invocation.getArgument(1);+ Assertions.assertEquals(TEST_USER, audit.creator());+ Assertions.assertNotNull(audit.createTime());+ return null;+ });+LoadTableResponse response = hookDispatcher.registerTable(mockContext, namespace, mockRequest);+ verify(mockEntityStore, never()).update(any(), any(), any(), any());Assertions.assertSame(mockResponse, response);verify(mockDispatcher).registerTable(mockContext, namespace, mockRequest);- verify(mockInternalTableDispatcher).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(any(), any());verify(mockInternalOwnerDispatcher).setOwner(any(), any(), any(), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@@ -477,11 +499,11 @@ public class TestIcebergNamespaceHookDispatcher {when(mockDispatcher.registerTable(mockContext, namespace, mockRequest)).thenReturn(mockResponse);- // Table import (loadTable) throwing must propagate so the caller learns the table exists in+ // Table import (importTable) throwing must propagate so the caller learns the table exists in// Iceberg but is not registered in Gravitino. setOwner is therefore unreachable.doThrow(new RuntimeException("Import failed")).when(mockInternalTableDispatcher)- .loadTable(any());+ .importTable(any(), any());RuntimeException thrown =Assertions.assertThrows(@@ -491,7 +513,7 @@ public class TestIcebergNamespaceHookDispatcher {Assertions.assertEquals("Import failed", thrown.getMessage());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockTableDispatcher, never()).importTable(any(), any());}@Test@@ -531,6 +553,21 @@ public class TestIcebergNamespaceHookDispatcher {when(mockDispatcher.createNamespace(mockContext, request)).thenReturn(mock(CreateNamespaceResponse.class));+ when(mockInternalSchemaDispatcher.importSchema(any(), any()))+ .thenAnswer(+ invocation -> {+ NameIdentifier identifier = invocation.getArgument(0);+ AuditInfo audit = invocation.getArgument(1);+ if (identifier.name().equals("A")) {+ Assertions.assertNull(audit.creator());+ Assertions.assertNull(audit.createTime());+ } else {+ Assertions.assertEquals(TEST_USER, audit.creator());+ Assertions.assertNotNull(audit.createTime());+ }+ return null;+ });+hookDispatcher.createNamespace(mockContext, request);@SuppressWarnings("unchecked")@@ -544,13 +581,7 @@ public class TestIcebergNamespaceHookDispatcher {Arrays.asList(TEST_CATALOG + ".A:B", TEST_CATALOG + ".A:B:C", TEST_CATALOG + ".A:B:C:D"),names);- // Each namespace the request created gets its creator recorded; the existing A does not.- ArgumentCaptor<NameIdentifier> recorded = ArgumentCaptor.forClass(NameIdentifier.class);- verify(mockEntityStore, times(3))- .update(recorded.capture(), eq(SchemaEntity.class), eq(Entity.EntityType.SCHEMA), any());- Assertions.assertEquals(- Arrays.asList("A:B", "A:B:C", "A:B:C:D"),- recorded.getAllValues().stream().map(NameIdentifier::name).collect(Collectors.toList()));+ verify(mockEntityStore, never()).update(any(), any(), any(), any());}@Testdiff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.javaindex 9b873c47ce..2f43c04a92 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableHookDispatcher.java@@ -34,7 +34,6 @@ import java.time.Instant;import java.util.Arrays;import java.util.Collections;import java.util.List;-import java.util.function.Function;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;@@ -251,8 +250,8 @@ public class TestIcebergTableHookDispatcher {NameIdentifier expectedIdentifier =IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, TableIdentifier.of(namespace, "test_table"), ":");- verify(mockInternalTableDispatcher).loadTable(expectedIdentifier);- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(eq(expectedIdentifier), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());// Verify ownership was setArgumentCaptor<String> userCaptor = ArgumentCaptor.forClass(String.class);@@ -270,7 +269,7 @@ public class TestIcebergTableHookDispatcher {when(mockDispatcher.createTable(mockContext, namespace, request)).thenReturn(mock(LoadTableResponse.class));RuntimeException importFailure = new RuntimeException("Failed to import table entity");- when(mockInternalTableDispatcher.loadTable(any())).thenThrow(importFailure);+ when(mockInternalTableDispatcher.importTable(any(), any())).thenThrow(importFailure);RuntimeException thrown =Assertions.assertThrows(@@ -292,7 +291,7 @@ public class TestIcebergTableHookDispatcher {when(mockDispatcher.updateTable(mockContext, tableId, request)).thenReturn(mock(LoadTableResponse.class));RuntimeException importFailure = new RuntimeException("Failed to import table entity");- when(mockInternalTableDispatcher.loadTable(any())).thenThrow(importFailure);+ when(mockInternalTableDispatcher.importTable(any(), any())).thenThrow(importFailure);RuntimeException thrown =Assertions.assertThrows(@@ -329,8 +328,8 @@ public class TestIcebergTableHookDispatcher {IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId, ":");verify(mockEntityStore, never()).delete(expectedIdentifier, Entity.EntityType.TABLE);- verify(mockInternalTableDispatcher).loadTable(expectedIdentifier);- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(eq(expectedIdentifier), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());}@Test@@ -345,8 +344,8 @@ public class TestIcebergTableHookDispatcher {IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId, ":");verify(mockEntityStore).delete(expectedIdentifier, Entity.EntityType.TABLE);- verify(mockInternalTableDispatcher).loadTable(expectedIdentifier);- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(eq(expectedIdentifier), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());}@Test@@ -443,8 +442,8 @@ public class TestIcebergTableHookDispatcher {NameIdentifier destIdentifier =IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, dest, ":");verify(mockEntityStore).delete(sourceIdentifier, Entity.EntityType.TABLE);- verify(mockInternalTableDispatcher).loadTable(destIdentifier);- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(eq(destIdentifier), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());}@Test@@ -465,13 +464,13 @@ public class TestIcebergTableHookDispatcher {when(mockDispatcher.tableExists(mockContext, dest)).thenReturn(true);doThrow(new RuntimeException("import failed")).when(mockInternalTableDispatcher)- .loadTable(any());+ .importTable(any(), any());Assertions.assertDoesNotThrow(() -> hookDispatcher.renameTable(mockContext, request));verify(mockDispatcher).renameTable(mockContext, request);- verify(mockInternalTableDispatcher).loadTable(any());- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(any(), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());}@Test@@ -549,8 +548,8 @@ public class TestIcebergTableHookDispatcher {verify(mockDispatcher).createTable(mockContext, namespace, request);// Verify table import was NOT called for staged create- verify(mockInternalTableDispatcher, never()).loadTable(any());- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher, never()).importTable(any(), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());// Verify ownership was NOT set for staged createverify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());@@ -576,8 +575,8 @@ public class TestIcebergTableHookDispatcher {NameIdentifier gravitinoTableId =IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, tableId, ":");- verify(mockInternalTableDispatcher).loadTable(gravitinoTableId);- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(eq(gravitinoTableId), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());ArgumentCaptor<String> userCaptor = ArgumentCaptor.forClass(String.class);verify(mockInternalOwnerDispatcher)@@ -586,37 +585,28 @@ public class TestIcebergTableHookDispatcher {Assertions.assertEquals(TEST_USER, userCaptor.getValue());}+ /** The creator is available during import without a separate audit update. */@Test- @SuppressWarnings("unchecked")- public void testCreateTableRecordsTheCreator() throws IOException {+ public void testCreateTableRecordsTheCreatorDuringImport() throws IOException {Namespace namespace = Namespace.of("test_schema");CreateTableRequest request =CreateTableRequest.builder().withName("test_table").withSchema(TABLE_SCHEMA).build();- when(mockDispatcher.createTable(mockContext, namespace, request))- .thenReturn(mock(LoadTableResponse.class));-- hookDispatcher.createTable(mockContext, namespace, request);-NameIdentifier identifier =IcebergIdentifierUtils.toGravitinoTableIdentifier(TEST_METALAKE, TEST_CATALOG, TableIdentifier.of(namespace, "test_table"), ":");- ArgumentCaptor<Function<TableEntity, TableEntity>> updater =- ArgumentCaptor.forClass(Function.class);- verify(mockEntityStore)- .update(- eq(identifier), eq(TableEntity.class), eq(Entity.EntityType.TABLE), updater.capture());- TableEntity imported =- TableEntity.builder()- .withId(1L)- .withName("test_table")- .withNamespace(identifier.namespace())- .withColumns(Collections.emptyList())- .withAuditInfo(AuditInfo.EMPTY)- .build();- TableEntity recorded = updater.getValue().apply(imported);- Assertions.assertEquals(TEST_USER, recorded.auditInfo().creator());- Assertions.assertNotNull(recorded.auditInfo().createTime());- Assertions.assertEquals(imported.id(), recorded.id());+ when(mockInternalTableDispatcher.importTable(eq(identifier), any()))+ .thenAnswer(+ invocation -> {+ AuditInfo audit = invocation.getArgument(1);+ Assertions.assertEquals(TEST_USER, audit.creator());+ Assertions.assertNotNull(audit.createTime());+ return null;+ });++ hookDispatcher.createTable(mockContext, namespace, request);++ verify(mockInternalTableDispatcher).importTable(eq(identifier), any());+ verify(mockEntityStore, never()).update(any(), any(), any(), any());}@Test@@ -638,9 +628,11 @@ public class TestIcebergTableHookDispatcher {hookDispatcher.updateTable(mockContext, tableId, request);verify(mockInternalTableDispatcher)- .loadTable(- IcebergIdentifierUtils.toGravitinoTableIdentifier(- TEST_METALAKE, TEST_CATALOG, tableId, ":"));+ .importTable(+ eq(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ TEST_METALAKE, TEST_CATALOG, tableId, ":")),+ any());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@@ -676,8 +668,8 @@ public class TestIcebergTableHookDispatcher {verify(mockDispatcher).updateTable(mockContext, tableId, request);// Verify table import was NOT called for a regular update- verify(mockInternalTableDispatcher, never()).loadTable(any());- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher, never()).importTable(any(), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());// Verify ownership was NOT setverify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());@@ -706,11 +698,11 @@ public class TestIcebergTableHookDispatcher {LoadTableResponse mockResponse = mock(LoadTableResponse.class);when(mockDispatcher.createTable(mockContext, namespace, request)).thenReturn(mockResponse);- // Import failure (the loadTable call) must propagate so the caller learns the table exists in+ // Import failure (the importTable call) must propagate so the caller learns the table exists in// Iceberg but is not registered in Gravitino. setOwner is therefore unreachable.doThrow(new RuntimeException("Import failed")).when(mockInternalTableDispatcher)- .loadTable(any());+ .importTable(any(), any());RuntimeException thrown =Assertions.assertThrows(@@ -719,8 +711,8 @@ public class TestIcebergTableHookDispatcher {Assertions.assertEquals("Import failed", thrown.getMessage());verify(mockDispatcher).createTable(mockContext, namespace, request);- verify(mockInternalTableDispatcher).loadTable(any());- verify(mockTableDispatcher, never()).loadTable(any());+ verify(mockInternalTableDispatcher).importTable(any(), any());+ verify(mockTableDispatcher, never()).importTable(any(), any());verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.javaindex bec9071dc1..b2d338abee 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java@@ -42,6 +42,7 @@ import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.listener.api.event.IcebergRequestContext;+import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.ViewEntity;import org.apache.iceberg.Schema;import org.apache.iceberg.catalog.Namespace;@@ -56,6 +57,7 @@ import org.apache.iceberg.types.Types;import org.apache.iceberg.view.ImmutableSQLViewRepresentation;import org.apache.iceberg.view.ImmutableViewVersion;import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -174,6 +176,15 @@ public class TestIcebergViewHookDispatcher {LoadViewResponse mockResponse = mock(LoadViewResponse.class);when(mockExecutor.createView(mockContext, namespace, createRequest)).thenReturn(mockResponse);+ when(mockInternalViewDispatcher.importView(any(), any()))+ .thenAnswer(+ invocation -> {+ AuditInfo audit = invocation.getArgument(1);+ Assertions.assertEquals(USER, audit.creator());+ Assertions.assertNotNull(audit.createTime());+ return null;+ });+LoadViewResponse response = hookDispatcher.createView(mockContext, namespace, createRequest);// Verify view was created in underlying catalog@@ -181,12 +192,10 @@ public class TestIcebergViewHookDispatcher {// Verify view was imported into GravitinoNameIdentifier expectedIdent = NameIdentifier.of(METALAKE, CATALOG, SCHEMA_NAME, VIEW_NAME);- verify(mockInternalViewDispatcher, times(1)).loadView(eq(expectedIdent));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, times(1)).importView(eq(expectedIdent), any());+ verify(mockViewDispatcher, never()).importView(any(), any());- // Verify the creator was recorded on the imported view- verify(mockEntityStore)- .update(eq(expectedIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any());+ verify(mockEntityStore, never()).update(any(), any(), any(), any());// Verify ownership was setverify(mockInternalOwnerDispatcher, times(1)).setOwner(any(), any(), eq(USER), any());@@ -222,7 +231,7 @@ public class TestIcebergViewHookDispatcher {// Simulate import failuredoThrow(new RuntimeException("Import failed")).when(mockInternalViewDispatcher)- .loadView(any(NameIdentifier.class));+ .importView(any(NameIdentifier.class), any());// Should not throw - import is best-effortLoadViewResponse response = hookDispatcher.createView(mockContext, namespace, createRequest);@@ -265,8 +274,8 @@ public class TestIcebergViewHookDispatcher {() -> hookDispatcher.createView(mockContext, namespace, createRequest));assertEquals("Set owner failed", thrown.getMessage());verify(mockExecutor, times(1)).createView(mockContext, namespace, createRequest);- verify(mockInternalViewDispatcher, times(1)).loadView(any(NameIdentifier.class));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, times(1)).importView(any(NameIdentifier.class), any());+ verify(mockViewDispatcher, never()).importView(any(), any());verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@@ -296,8 +305,8 @@ public class TestIcebergViewHookDispatcher {NameIdentifier expectedIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent, ":");verify(mockEntityStore, never()).delete(eq(expectedIdent), eq(Entity.EntityType.VIEW));- verify(mockInternalViewDispatcher, times(1)).loadView(eq(expectedIdent));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, times(1)).importView(eq(expectedIdent), any());+ verify(mockViewDispatcher, never()).importView(any(), any());}@Test@@ -311,8 +320,8 @@ public class TestIcebergViewHookDispatcher {NameIdentifier expectedIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, viewIdent, ":");verify(mockEntityStore, times(1)).delete(eq(expectedIdent), eq(Entity.EntityType.VIEW));- verify(mockInternalViewDispatcher, times(1)).loadView(eq(expectedIdent));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, times(1)).importView(eq(expectedIdent), any());+ verify(mockViewDispatcher, never()).importView(any(), any());}@Test@@ -399,8 +408,8 @@ public class TestIcebergViewHookDispatcher {NameIdentifier destGravitinoIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, destIdent, ":");verify(mockEntityStore, times(1)).delete(eq(sourceGravitinoIdent), eq(Entity.EntityType.VIEW));- verify(mockInternalViewDispatcher, times(1)).loadView(eq(destGravitinoIdent));- verify(mockViewDispatcher, never()).loadView(any());+ verify(mockInternalViewDispatcher, times(1)).importView(eq(destGravitinoIdent), any());+ verify(mockViewDispatcher, never()).importView(any(), any());}@Test