roryqi commented on code in PR #14540:
URL: https://github.com/apache/gravitino/pull/14540#discussion_r4522576478


##########
core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java:
##########
@@ -83,6 +89,64 @@ protected 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.
+   *
+   * @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 fallback creation audit
+   * @param withAudit copies the current entity with the new audit
+   * @param <E> the auditable entity type
+   * @return the current registration with its missing creation fields filled
+   */
+  @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");

Review Comment:
   Addressed in 5c05324733. Audit recovery catches OptimisticLockException, 
reloads the current registration and does not retry with the old creation 
audit. Identity changes therefore leave the replacement creator untouched. 
TestImportAuditRecovery covers identity changes and optimistic conflicts; the 
H2 test testTableImportReturnsRecreatedEntityWithoutOldAudit exercises the real 
dispatcher/store path. Revalidated with 162 core tests and 66 Iceberg hook/H2 
tests passing.



##########
core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java:
##########
@@ -587,7 +546,83 @@ private Optional<TableEntity> 
getTableEntityBeforeRename(NameIdentifier ident) {
     }
   }
 
-  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(

Review Comment:
   Addressed in 5c05324733. The table store updater also fills missing column 
creation audits in that same update, preserving existing column creators, 
creation times and modification fields. The raced import scenario checks both 
table and column creators; testTableAuditRecoveryPreservesColumnFields verifies 
preservation through the real H2 store. These tests pass on the updated head.



##########
core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java:
##########
@@ -83,6 +89,64 @@ protected 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.
+   *
+   * @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 fallback creation audit
+   * @param withAudit copies the current entity with the new audit
+   * @param <E> the auditable entity type
+   * @return the current registration with its missing creation fields filled
+   */
+  @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())

Review Comment:
   No: an ordinary load must leave an unknown source creator unknown. 
loadTable/loadSchema/loadView and reconciliation pass AuditInfo.EMPTY; only an 
explicit create import supplies the request creator as a fallback. 
Source-reported creators take precedence. The load scenarios for all three 
dispatchers assert that the persisted and returned creator/createTime remain 
null; all pass on the updated head.



##########
core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java:
##########
@@ -83,6 +89,71 @@ protected 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. If a concurrent
+   * update wins, return the current registration without applying the old 
audit.
+   *
+   * @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
+   */
+  @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 (OptimisticLockException e) {
+      // Audit recovery must not fail a read or attribute a replacement to the 
old create request.
+      // Do not retry with the requested audit: it belongs to the entity 
originally observed.
+      return getEntity(entity.nameIdentifier(), entity.type(), type);

Review Comment:
   Yes, null means the registration disappeared and the response falls back to 
the source snapshot. Fixed the imported flag in 3716af4999 so schema/table/view 
responses are then marked not imported, while managed catalog behavior is 
preserved. Added a deleted scenario for all three dispatchers: delete the 
registration during the conflicting audit update, verify a successful source 
response with no stored entity or old request audit, then verify that an 
ordinary load imports it again. All 162 core and 66 Iceberg hook/H2 tests 
passed.



##########
core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java:
##########
@@ -608,7 +568,116 @@ private Optional<TableEntity> 
getTableEntityBeforeRename(NameIdentifier ident) {
     }
   }
 
-  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 =

Review Comment:
   Addressed in 3716af4999. Added TableEntity.toBuilder() and switched audit 
recovery to override only the audit and recovered columns. The entity test 
populates every table field and the namespace, compares the copied fields, and 
verifies that replacing audit/columns leaves the original unchanged. The helper 
documents its shallow-copy behavior. Core tests and Spotless passed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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

Reply via email to