World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[MINOR] test(iceberg): stabilize async purge file assertions (#14985)
Qi Yu166db8b6dff9
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTAsyncPurgeIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTAsyncPurgeIT.javaindex 6bb400da9e..f73e6ab9b1 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTAsyncPurgeIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTAsyncPurgeIT.java@@ -32,6 +32,7 @@ import org.apache.gravitino.Catalog;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.client.GravitinoMetalake;import org.apache.gravitino.iceberg.common.IcebergConfig;+import org.apache.gravitino.iceberg.service.cleanup.FileCleanupAssertions;import org.apache.gravitino.integration.test.container.ContainerSuite;import org.apache.gravitino.integration.test.util.BaseIT;import org.apache.gravitino.integration.test.util.TestDatabaseName;@@ -183,12 +184,7 @@ public class IcebergRESTAsyncPurgeIT extends BaseIT {Awaitility.await().atMost(60, TimeUnit.SECONDS).pollInterval(500, TimeUnit.MILLISECONDS)- .untilAsserted(- () ->- Assertions.assertEquals(- 0L,- countRegularFiles(tableDir),- "Background cleanup worker should have deleted all table files"));+ .untilAsserted(() -> FileCleanupAssertions.assertNoRegularFiles(tableDir));}private void initMetalakeAndCatalog() {diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/FileCleanupAssertions.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/FileCleanupAssertions.javanew file mode 100644index 0000000000..d37e0ae771--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/FileCleanupAssertions.java@@ -0,0 +1,65 @@+/*+ * 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.cleanup;++import java.io.IOException;+import java.io.UncheckedIOException;+import java.nio.file.Files;+import java.nio.file.NoSuchFileException;+import java.nio.file.Path;+import java.util.stream.Stream;+import org.junit.jupiter.api.Assertions;++/** File assertions for tests that observe asynchronous cleanup. */+public final class FileCleanupAssertions {++ private static final String CONCURRENT_DELETION =+ "Files disappeared during the cleanup scan; retry the complete assertion";++ private FileCleanupAssertions() {}++ /**+ * Asserts that no regular files remain, allowing {@code untilAsserted} to retry an incomplete+ * scan caused by concurrent deletion. Other I/O failures propagate rather than looking empty.+ *+ * @param directory directory being cleaned asynchronously+ */+ public static void assertNoRegularFiles(Path directory) {+ if (Files.notExists(directory)) {+ return;+ }+ try (Stream<Path> paths =+ Files.find(+ directory, Integer.MAX_VALUE, (path, attributes) -> attributes.isRegularFile())) {+ Assertions.assertEquals(+ 0L, paths.count(), "Background cleanup worker should have deleted all table files");+ } catch (NoSuchFileException e) {+ // The root can disappear after notExists, before the traversal opens it.+ throw new AssertionError(CONCURRENT_DELETION, e);+ } catch (IOException e) {+ throw new UncheckedIOException("Failed to scan cleanup directory " + directory, e);+ } catch (UncheckedIOException e) {+ // A descendant can disappear while the lazy traversal reads its attributes.+ if (e.getCause() instanceof NoSuchFileException) {+ throw new AssertionError(CONCURRENT_DELETION, e);+ }+ throw e;+ }+ }+}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestFileCleanupAssertions.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestFileCleanupAssertions.javanew file mode 100644index 0000000000..25c513abad--- /dev/null+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/cleanup/TestFileCleanupAssertions.java@@ -0,0 +1,151 @@+/*+ * 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.cleanup;++import java.io.UncheckedIOException;+import java.nio.file.AccessDeniedException;+import java.nio.file.Files;+import java.nio.file.NoSuchFileException;+import java.nio.file.Path;+import java.time.Duration;+import java.util.Spliterator;+import java.util.Spliterators;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Consumer;+import java.util.stream.Stream;+import java.util.stream.StreamSupport;+import org.awaitility.Awaitility;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.RepeatedTest;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.mockito.MockedStatic;+import org.mockito.Mockito;++/** Regression tests for file observations made while asynchronous cleanup removes files. */+// Files.find calls in static-mock stubs do not open resources; the assertion closes returned+// streams.+@SuppressWarnings("StreamResourceLeak")+public class TestFileCleanupAssertions {++ @TempDir private Path tempDir;++ @Test+ void testMissingAndEmptyDirectories() throws Exception {+ FileCleanupAssertions.assertNoRegularFiles(tempDir.resolve("missing"));+ Files.createDirectories(tempDir.resolve("metadata/empty"));+ FileCleanupAssertions.assertNoRegularFiles(tempDir);+ }++ @Test+ void testRemainingFilesFailTheAssertion() throws Exception {+ Files.writeString(tempDir.resolve("remaining.avro"), "manifest");+ Assertions.assertThrows(+ AssertionError.class, () -> FileCleanupAssertions.assertNoRegularFiles(tempDir));+ }++ @RepeatedTest(20)+ void testConcurrentDeletionRetriesWithoutTreatingAnIncompleteScanAsEmpty() throws Exception {+ Path remaining = tempDir.resolve("remaining.avro");+ AtomicInteger scans = new AtomicInteger();+ AtomicInteger closed = new AtomicInteger();+ try (MockedStatic<Files> files = Mockito.mockStatic(Files.class)) {+ files+ .when(() -> Files.find(Mockito.eq(tempDir), Mockito.eq(Integer.MAX_VALUE), Mockito.any()))+ .thenAnswer(+ invocation -> {+ int scan = scans.incrementAndGet();+ if (scan == 1) {+ return failingStream(+ new UncheckedIOException(new NoSuchFileException("manifest")))+ .onClose(closed::incrementAndGet);+ }+ return (scan == 2 ? Stream.of(remaining) : Stream.<Path>empty())+ .onClose(closed::incrementAndGet);+ });++ // Static mocks are thread-local, so keep polling on this test thread.+ Awaitility.await()+ .pollInSameThread()+ .pollDelay(Duration.ZERO)+ .pollInterval(Duration.ZERO)+ .atMost(Duration.ofSeconds(1))+ .untilAsserted(() -> FileCleanupAssertions.assertNoRegularFiles(tempDir));+ }+ Assertions.assertEquals(3, scans.get(), "Both the incomplete and nonempty scans must retry");+ Assertions.assertEquals(+ 3, closed.get(), "Every traversal must be closed, including failed ones");+ }++ @Test+ void testRootDisappearingBeforeTraversalIsRetryable() throws Exception {+ NoSuchFileException missing = new NoSuchFileException(tempDir.toString());+ try (MockedStatic<Files> files = Mockito.mockStatic(Files.class)) {+ files+ .when(() -> Files.find(Mockito.eq(tempDir), Mockito.eq(Integer.MAX_VALUE), Mockito.any()))+ .thenThrow(missing);+ AssertionError error =+ Assertions.assertThrows(+ AssertionError.class, () -> FileCleanupAssertions.assertNoRegularFiles(tempDir));+ Assertions.assertSame(missing, error.getCause());+ }+ }++ @Test+ void testPermissionFailureOpeningTraversalIsNotRetryable() throws Exception {+ AccessDeniedException denied = new AccessDeniedException(tempDir.toString());+ try (MockedStatic<Files> files = Mockito.mockStatic(Files.class)) {+ files+ .when(() -> Files.find(Mockito.eq(tempDir), Mockito.eq(Integer.MAX_VALUE), Mockito.any()))+ .thenThrow(denied);+ UncheckedIOException error =+ Assertions.assertThrows(+ UncheckedIOException.class,+ () -> FileCleanupAssertions.assertNoRegularFiles(tempDir));+ Assertions.assertSame(denied, error.getCause());+ }+ }++ @Test+ void testPermissionFailureDuringTraversalIsNotRetryable() throws Exception {+ UncheckedIOException denied =+ new UncheckedIOException(new AccessDeniedException("metadata/manifest"));+ try (MockedStatic<Files> files = Mockito.mockStatic(Files.class)) {+ files+ .when(() -> Files.find(Mockito.eq(tempDir), Mockito.eq(Integer.MAX_VALUE), Mockito.any()))+ .thenReturn(failingStream(denied));+ Assertions.assertSame(+ denied,+ Assertions.assertThrows(+ UncheckedIOException.class,+ () -> FileCleanupAssertions.assertNoRegularFiles(tempDir)));+ }+ }++ private static Stream<Path> failingStream(UncheckedIOException failure) {+ Spliterator<Path> paths =+ new Spliterators.AbstractSpliterator<Path>(Long.MAX_VALUE, 0) {+ @Override+ public boolean tryAdvance(Consumer<? super Path> action) {+ throw failure;+ }+ };+ return StreamSupport.stream(paths, false);+ }+}