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

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new b4243b13f5 [#14333] fix(iceberg): Propagate async purge deletion 
failures (#14951)
b4243b13f5 is described below

commit b4243b13f5220f7392ea3b345092d5d625b808ce
Author: roryqi <[email protected]>
AuthorDate: Fri Nov 13 10:07:33 2026 +0800

    [#14333] fix(iceberg): Propagate async purge deletion failures (#14951)
    
    ### What changes were proposed in this pull request?
    
    Propagate bulk and per-file deletion failures to async cleanup jobs and
    preserve the deletion cause in `last_error`. Wait for all submitted
    batches on deletion failures, and document that interruption can still
    end the wait before batches finish. Continue tolerating missing files
    and preserve parent metadata for retries.
    
    ### Why are the changes needed?
    
    `CatalogUtil.deleteFiles` suppresses deletion errors, causing async
    purge jobs to report `SUCCEEDED` while files remain on storage.
    
    Fixes #14333
    
    ### Does this PR introduce _any_ user-facing change?
    
    Async purge now retries failed deletions and marks the job `FAILED` when
    the configured attempt limit is reached. Deletion errors remain visible
    in `last_error`.
    
    ### How was this patch tested?
    
    Added regression coverage for deletion failures, missing files,
    concurrent batches, retry exhaustion, and recovery. Confirmed two
    regression tests fail against the original implementation.
    
    - 723 module unit tests passed.
    - 51 cleanup tests passed across H2, MySQL, and PostgreSQL.
    - Spotless formatting and git diff checks passed.
---
 .../service/cleanup/IcebergCleanupManager.java     |  67 +++++---
 .../service/cleanup/TestIcebergCleanupManager.java | 187 +++++++++++++++++++++
 2 files changed, 234 insertions(+), 20 deletions(-)

diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupManager.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupManager.java
index f46b3c337d..1a348cf767 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupManager.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/cleanup/IcebergCleanupManager.java
@@ -19,8 +19,8 @@
 
 package org.apache.gravitino.iceberg.service.cleanup;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Iterators;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.LinkedHashSet;
@@ -54,6 +54,8 @@ import org.apache.iceberg.TableMetadataParser;
 import org.apache.iceberg.exceptions.NotFoundException;
 import org.apache.iceberg.io.CloseableIterable;
 import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.SupportsBulkOperations;
+import org.apache.iceberg.util.Tasks;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -231,25 +233,26 @@ public class IcebergCleanupManager implements 
AutoCloseable {
     List<Future<?>> futures = new ArrayList<>();
     Iterators.partition(files.iterator(), deleteBatchSize)
         .forEachRemaining(
-            batch ->
-                futures.add(
-                    deleteExecutor.submit(
-                        () -> CatalogUtil.deleteFiles(io, batch, "cleanup", 
true))));
+            batch -> futures.add(deleteExecutor.submit(() -> deleteBatch(io, 
batch))));
 
-    for (Future<?> future : futures) {
-      try {
-        future.get();
-      } catch (InterruptedException e) {
-        Thread.currentThread().interrupt();
-        throw new RuntimeException("Interrupted during bulk delete", e);
-      } catch (ExecutionException e) {
-        if 
(Throwables.getCausalChain(e).stream().anyMatch(NotFoundException.class::isInstance))
 {
-          LOG.debug("Ignoring already-deleted file during async cleanup", e);
-          continue;
-        }
-        throw new RuntimeException("Bulk delete batch failed", e);
-      }
-    }
+    // On deletion failures, wait for every submitted batch before propagating 
the error and closing
+    // the FileIO. Interruption is an exception: restoring the interrupt flag 
prevents further
+    // blocking waits, so runJob may close the FileIO while unfinished batches 
are still running.
+    Tasks.foreach(futures)
+        .noRetry()
+        .throwFailureWhenFinished()
+        .run(
+            future -> {
+              try {
+                future.get();
+              } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                throw new RuntimeException("Interrupted during bulk delete", 
e);
+              } catch (ExecutionException e) {
+                throw new RuntimeException(
+                    "Failed to delete cleanup files: " + 
e.getCause().getMessage(), e.getCause());
+              }
+            });
   }
 
   private void workerLoop() {
@@ -356,13 +359,37 @@ public class IcebergCleanupManager implements 
AutoCloseable {
         } catch (NotFoundException manifestGone) {
           // Manifests are deleted after their data files, so a missing one 
has no data files left.
           LOG.debug("Manifest {} already gone; skipping", manifest.path());
-        } catch (Exception e) {
+        } catch (IOException e) {
           throw new RuntimeException("Failed to read manifest " + 
manifest.path(), e);
         }
       }
     }
   }
 
+  // CatalogUtil.deleteFiles suppresses failures, but async cleanup must retry 
or fail the job.
+  private static void deleteBatch(FileIO io, List<String> batch) {
+    if (io instanceof SupportsBulkOperations) {
+      try {
+        ((SupportsBulkOperations) io).deleteFiles(batch);
+      } catch (NotFoundException alreadyGone) {
+        LOG.debug("Ignoring already-deleted files during async cleanup", 
alreadyGone);
+      }
+      return;
+    }
+
+    Tasks.foreach(batch)
+        .noRetry()
+        .throwFailureWhenFinished()
+        .run(
+            file -> {
+              try {
+                io.deleteFile(file);
+              } catch (NotFoundException alreadyGone) {
+                LOG.debug("Ignoring already-deleted file {} during async 
cleanup", file);
+              }
+            });
+  }
+
   private static void awaitTermination(ExecutorService pool) {
     try {
       pool.awaitTermination(5, TimeUnit.SECONDS);
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestIcebergCleanupManager.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestIcebergCleanupManager.java
index 0029a89b1e..f7e67e34b1 100644
--- 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestIcebergCleanupManager.java
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestIcebergCleanupManager.java
@@ -25,6 +25,8 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -46,8 +48,10 @@ import org.apache.iceberg.Table;
 import org.apache.iceberg.catalog.Namespace;
 import org.apache.iceberg.catalog.TableIdentifier;
 import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.exceptions.RuntimeIOException;
 import org.apache.iceberg.inmemory.InMemoryCatalog;
 import org.apache.iceberg.inmemory.InMemoryFileIO;
+import org.apache.iceberg.io.BulkDeletionFailureException;
 import org.apache.iceberg.io.FileIO;
 import org.apache.iceberg.io.InputFile;
 import org.apache.iceberg.io.OutputFile;
@@ -59,6 +63,8 @@ import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.TestTemplate;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
 
 /**
  * Exercises {@link IcebergCleanupManager} against the same relational backend 
matrix as the cleanup
@@ -175,6 +181,119 @@ class TestIcebergCleanupManager extends TestJDBCBackend {
     }
   }
 
+  @TestTemplate
+  void testDeleteAllPropagatesBulkFailure() {
+    SupportsBulkOperations io = Mockito.mock(SupportsBulkOperations.class);
+    BulkDeletionFailureException failure = new BulkDeletionFailureException(1);
+    Mockito.doThrow(failure).when(io).deleteFiles(Mockito.any());
+    try (IcebergCleanupManager svc = new IcebergCleanupManager(store, 
fastPollConfig())) {
+      RuntimeException error =
+          Assertions.assertThrows(
+              RuntimeException.class, () -> svc.deleteAll(io, 
Arrays.asList("denied")));
+      Assertions.assertTrue(error.getMessage().contains(failure.getMessage()));
+    }
+  }
+
+  @TestTemplate
+  void testDeleteAllPropagatesBulkRuntimeFailure() {
+    SupportsBulkOperations io = Mockito.mock(SupportsBulkOperations.class);
+    Mockito.doThrow(new RuntimeIOException("Access 
denied")).when(io).deleteFiles(Mockito.any());
+    try (IcebergCleanupManager svc = new IcebergCleanupManager(store, 
fastPollConfig())) {
+      RuntimeException error =
+          Assertions.assertThrows(
+              RuntimeException.class, () -> svc.deleteAll(io, 
Arrays.asList("denied")));
+      Assertions.assertTrue(error.getMessage().contains("Access denied"));
+    }
+  }
+
+  @TestTemplate
+  void testDeleteAllContinuesAfterMissingAndFailedFiles() {
+    FileIO io = Mockito.mock(FileIO.class);
+    Mockito.doThrow(new NotFoundException("Already 
gone")).when(io).deleteFile("missing");
+    Mockito.doThrow(new RuntimeIOException("Access 
denied")).when(io).deleteFile("denied");
+    try (IcebergCleanupManager svc = new IcebergCleanupManager(store, 
fastPollConfig())) {
+      RuntimeException error =
+          Assertions.assertThrows(
+              RuntimeException.class,
+              () -> svc.deleteAll(io, Arrays.asList("missing", "denied", 
"deletable")));
+      Assertions.assertTrue(error.getMessage().contains("Access denied"));
+      Mockito.verify(io).deleteFile("missing");
+      Mockito.verify(io).deleteFile("denied");
+      Mockito.verify(io).deleteFile("deletable");
+    }
+  }
+
+  @TestTemplate
+  void testDeleteAllWaitsForOtherBatchesAfterFailure() throws Exception {
+    FileIO io = Mockito.mock(FileIO.class);
+    Mockito.doThrow(new RuntimeIOException("Access 
denied")).when(io).deleteFile("denied");
+    CountDownLatch batchStarted = new CountDownLatch(1);
+    CountDownLatch releaseBatch = new CountDownLatch(1);
+    Mockito.doAnswer(
+            invocation -> {
+              batchStarted.countDown();
+              Assertions.assertTrue(releaseBatch.await(5, TimeUnit.SECONDS));
+              return null;
+            })
+        .when(io)
+        .deleteFile("blocked");
+    Map<String, String> config = new HashMap<>();
+    config.put("async-cleanup.delete-batch-size", "1");
+    config.put("async-cleanup.delete-threads", "2");
+    try (IcebergCleanupManager svc = new IcebergCleanupManager(store, new 
IcebergConfig(config))) {
+      CompletableFuture<Void> cleanup =
+          CompletableFuture.runAsync(() -> svc.deleteAll(io, 
Arrays.asList("denied", "blocked")));
+      try {
+        Assertions.assertTrue(batchStarted.await(5, TimeUnit.SECONDS));
+        Awaitility.await()
+            .during(100, TimeUnit.MILLISECONDS)
+            .atMost(2, TimeUnit.SECONDS)
+            .until(() -> !cleanup.isDone());
+      } finally {
+        releaseBatch.countDown();
+      }
+      Assertions.assertThrows(CompletionException.class, cleanup::join);
+    }
+  }
+
+  @TestTemplate
+  void testCleanupRetriesAfterDataFileDeleteFailure() {
+    BaseTable base = tableWithDataFile();
+    InMemoryFileIO io = Mockito.spy((InMemoryFileIO) base.io());
+    String metadataLocation = 
base.operations().current().metadataFileLocation();
+    String manifestList = base.currentSnapshot().manifestListLocation();
+    String manifest = base.currentSnapshot().allManifests(io).get(0).path();
+    Mockito.doThrow(new RuntimeIOException("Access denied"))
+        .doCallRealMethod()
+        .when(io)
+        .deleteFile(DATA_FILE);
+
+    try (IcebergCleanupManager svc = new IcebergCleanupManager(store, 
fastPollConfig())) {
+      RuntimeException error =
+          Assertions.assertThrows(
+              RuntimeException.class, () -> svc.cleanupFiles(io, 
metadataLocation));
+      Assertions.assertTrue(error.getMessage().contains("Access denied"));
+      for (String file : Arrays.asList(DATA_FILE, manifest, manifestList, 
metadataLocation)) {
+        Assertions.assertTrue(io.fileExists(file), file);
+      }
+
+      svc.cleanupFiles(io, metadataLocation);
+      for (String file : Arrays.asList(DATA_FILE, manifest, manifestList, 
metadataLocation)) {
+        Assertions.assertFalse(io.fileExists(file), file);
+      }
+    }
+  }
+
+  @TestTemplate
+  void testWorkerFailsAfterBulkDeleteRetries() {
+    assertWorkerHandlesBulkDeleteFailure(false);
+  }
+
+  @TestTemplate
+  void testWorkerSucceedsAfterBulkDeleteRecovers() {
+    assertWorkerHandlesBulkDeleteFailure(true);
+  }
+
   @TestTemplate
   void testCleanupDeletesAllFiles() {
     BaseTable base = tableWithDataFile();
@@ -312,6 +431,74 @@ class TestIcebergCleanupManager extends TestJDBCBackend {
     }
   }
 
+  private void assertWorkerHandlesBulkDeleteFailure(boolean recovers) {
+    BaseTable base = tableWithDataFile();
+    InMemoryFileIO delegate = (InMemoryFileIO) base.io();
+    String metadataLocation = 
base.operations().current().metadataFileLocation();
+    SupportsBulkOperations io =
+        Mockito.mock(SupportsBulkOperations.class, Mockito.CALLS_REAL_METHODS);
+    Mockito.when(io.newInputFile(Mockito.anyString()))
+        .thenAnswer(invocation -> 
delegate.newInputFile(invocation.getArgument(0, String.class)));
+    AtomicInteger deleteCalls = new AtomicInteger();
+    Mockito.doAnswer(
+            invocation -> {
+              if (!recovers || deleteCalls.getAndIncrement() == 0) {
+                Assertions.assertTrue(delegate.fileExists(metadataLocation));
+                throw new BulkDeletionFailureException(1);
+              }
+              Iterable<String> paths = invocation.getArgument(0);
+              paths.forEach(delegate::deleteFile);
+              return null;
+            })
+        .when(io)
+        .deleteFiles(Mockito.any());
+
+    Map<String, String> config = new HashMap<>();
+    config.put("async-cleanup.worker-threads", "1");
+    config.put("async-cleanup.poll-interval-secs", "1");
+    config.put("async-cleanup.max-attempts", "2");
+    IcebergCleanupJobStore trackedStore = Mockito.spy(store);
+    try (IcebergCleanupManager svc =
+        new IcebergCleanupManager(trackedStore, new IcebergConfig(config)) {
+          @Override
+          void cleanupFiles(FileIO unused, String location) {
+            super.cleanupFiles(io, location);
+          }
+        }) {
+      long id =
+          svc.addJob(
+              new IcebergCleanupJob(
+                  0L,
+                  CATALOG_ID,
+                  "db",
+                  "t",
+                  metadataLocation,
+                  NoopFileIO.class.getName(),
+                  ImmutableMap.of(),
+                  "alice"));
+      svc.start();
+      Awaitility.await()
+          .atMost(10, TimeUnit.SECONDS)
+          .until(
+              () ->
+                  store.stateOf(id)
+                      == (recovers
+                          ? IcebergCleanupJob.State.SUCCEEDED
+                          : IcebergCleanupJob.State.FAILED));
+      ArgumentCaptor<String> reasons = ArgumentCaptor.forClass(String.class);
+      Mockito.verify(trackedStore, Mockito.times(recovers ? 1 : 2))
+          .recordFailure(Mockito.eq(id), reasons.capture(), Mockito.eq(2), 
Mockito.anyLong());
+      reasons
+          .getAllValues()
+          .forEach(
+              reason ->
+                  Assertions.assertTrue(
+                      reason.contains(new 
BulkDeletionFailureException(1).getMessage()), reason));
+      Assertions.assertEquals(!recovers, delegate.fileExists(DATA_FILE));
+      Assertions.assertEquals(!recovers, 
delegate.fileExists(metadataLocation));
+    }
+  }
+
   static class RecordingFileIO implements SupportsBulkOperations {
     private final CopyOnWriteArrayList<String> deleted;
 

Reply via email to