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

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new cedf868a29 [filesystem][s3] Recover S3A filesystem after connection 
pool shutdown (#11037)
cedf868a29 is described below

commit cedf868a295ae29fdb0b688ee64f873894f84ae8
Author: AuroraVoyage <[email protected]>
AuthorDate: Fri Nov 13 18:56:39 2026 +0800

    [filesystem][s3] Recover S3A filesystem after connection pool shutdown 
(#11037)
---
 .../apache/paimon/s3/RecoverableS3AFileSystem.java | 129 +++++
 .../main/java/org/apache/paimon/s3/S3FileIO.java   | 197 +++++++-
 .../paimon/s3/S3FileIOCacheRecoveryTest.java       | 541 +++++++++++++++++++++
 .../java/org/apache/paimon/s3/S3ASchemeTest.java   |  15 +-
 4 files changed, 854 insertions(+), 28 deletions(-)

diff --git 
a/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/RecoverableS3AFileSystem.java
 
b/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/RecoverableS3AFileSystem.java
new file mode 100644
index 0000000000..42d703c170
--- /dev/null
+++ 
b/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/RecoverableS3AFileSystem.java
@@ -0,0 +1,129 @@
+/*
+ * 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.paimon.s3;
+
+import org.apache.hadoop.fs.s3a.S3AFileSystem;
+import org.apache.hadoop.fs.s3a.S3ClientFactory;
+import org.apache.hadoop.fs.s3a.impl.ClientManager;
+import org.apache.hadoop.fs.statistics.DurationTrackerFactory;
+import software.amazon.awssdk.core.interceptor.Context;
+import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
+import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * {@link S3AFileSystem} that evicts itself from {@link S3FileIO}'s cache when 
the sync Apache HTTP
+ * connection pool has been shut down.
+ *
+ * <p>Only handles {@code IllegalStateException("Connection pool shut down")} 
from the Apache HTTP
+ * client. Netty async failures are out of scope. Failed requests are not 
retried automatically;
+ * callers must retry and obtain a recovered filesystem through {@link 
S3FileIO}.
+ *
+ * <p>Instances are published into {@link S3FileIO}'s static CACHE and may be 
shared by multiple
+ * {@code S3FileIO} instances (and their per-instance {@code fsMap} entries). 
Recovery eviction only
+ * marks this instance unusable and removes it from CACHE when the mapping 
still points at {@code
+ * this}; it does not {@code close()} a previously published filesystem. 
Closing a shared published
+ * instance requires additional cache-level lifecycle coordination (for 
example reference counting)
+ * and is out of scope for this recovery path.
+ */
+class RecoverableS3AFileSystem extends S3AFileSystem {
+
+    private static final String CONNECTION_POOL_SHUT_DOWN = "Connection pool 
shut down";
+
+    private final AtomicBoolean usable = new AtomicBoolean(true);
+
+    private Runnable evictFromCache;
+
+    void bind(Runnable evictFromCache) {
+        this.evictFromCache = evictFromCache;
+    }
+
+    boolean isUsable() {
+        return usable.get();
+    }
+
+    /**
+     * Marks this instance unusable and removes it from the shared cache only 
when the cache still
+     * points at {@code this}.
+     */
+    void markUnusableAndEvict() {
+        if (usable.compareAndSet(true, false) && evictFromCache != null) {
+            evictFromCache.run();
+        }
+    }
+
+    void handleExecutionFailure(Throwable failure) {
+        if (isApachePoolShutdown(failure)) {
+            markUnusableAndEvict();
+        }
+    }
+
+    static boolean isApachePoolShutdown(Throwable failure) {
+        Set<Throwable> visited =
+                Collections.newSetFromMap(new IdentityHashMap<Throwable, 
Boolean>());
+        for (Throwable t = failure; t != null && visited.add(t); t = 
t.getCause()) {
+            if (t instanceof IllegalStateException
+                    && CONNECTION_POOL_SHUT_DOWN.equals(t.getMessage())) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    protected ClientManager createClientManager(
+            S3ClientFactory clientFactory,
+            S3ClientFactory unencryptedClientFactory,
+            S3ClientFactory.S3ClientCreationParameters 
clientCreationParameters,
+            DurationTrackerFactory durationTrackerFactory) {
+        List<ExecutionInterceptor> merged = new ArrayList<>();
+        List<ExecutionInterceptor> existing = 
clientCreationParameters.getExecutionInterceptors();
+        if (existing != null) {
+            merged.addAll(existing);
+        }
+        merged.add(new PoolShutdownInterceptor(this));
+        clientCreationParameters.withExecutionInterceptors(merged);
+        return super.createClientManager(
+                clientFactory,
+                unencryptedClientFactory,
+                clientCreationParameters,
+                durationTrackerFactory);
+    }
+
+    private static final class PoolShutdownInterceptor implements 
ExecutionInterceptor {
+
+        private final RecoverableS3AFileSystem owner;
+
+        private PoolShutdownInterceptor(RecoverableS3AFileSystem owner) {
+            this.owner = owner;
+        }
+
+        @Override
+        public void onExecutionFailure(
+                Context.FailedExecution context, ExecutionAttributes 
executionAttributes) {
+            owner.handleExecutionFailure(context.exception());
+        }
+    }
+}
diff --git 
a/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/S3FileIO.java
 
b/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/S3FileIO.java
index 339d81d822..2924b17259 100644
--- 
a/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/S3FileIO.java
+++ 
b/paimon-filesystems/paimon-s3-impl/src/main/java/org/apache/paimon/s3/S3FileIO.java
@@ -23,6 +23,7 @@ import org.apache.paimon.fs.FileIO;
 import org.apache.paimon.fs.Path;
 import org.apache.paimon.fs.TwoPhaseOutputStream;
 import org.apache.paimon.options.Options;
+import org.apache.paimon.utils.Pair;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileSystem;
@@ -31,7 +32,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
-import java.io.UncheckedIOException;
 import java.net.URI;
 import java.util.Map;
 import java.util.Objects;
@@ -57,11 +57,23 @@ public class S3FileIO extends HadoopCompliantFileIO {
     };
 
     /**
-     * Cache S3AFileSystem, at present, there is no good mechanism to ensure 
that the file system
-     * will be shut down, so here the fs cache is used to avoid resource 
leakage.
+     * Shared cache of {@link S3AFileSystem} instances across {@link S3FileIO} 
objects. Sharing
+     * instances avoids creating duplicate filesystem instances for the same 
cache key. There is
+     * currently no reference-counted shutdown for published entries. 
Pool-shutdown recovery only
+     * evicts an unusable mapping from this cache; it does not close a 
previously published
+     * filesystem that may still be referenced by other {@code S3FileIO} 
{@code fsMap} entries or
+     * in-flight streams.
      */
     private static final Map<CacheKey, S3AFileSystem> CACHE = new 
ConcurrentHashMap<>();
 
+    /**
+     * Fixed striped locks for create/replace. Same {@link CacheKey} always 
maps to the same lock;
+     * different keys may share a stripe. Invalidation stays lock-free.
+     */
+    private static final int CACHE_LOCK_COUNT = 128;
+
+    private static final Object[] CACHE_LOCKS = createCacheLocks();
+
     private Options hadoopOptions;
 
     @Override
@@ -115,34 +127,165 @@ public class S3FileIO extends HadoopCompliantFileIO {
         return hadoopConfig;
     }
 
+    /**
+     * Overrides parent to refresh {@link #fsMap} when a cached {@link 
RecoverableS3AFileSystem} has
+     * been invalidated. Avoids introducing a generic health hook on {@link 
HadoopCompliantFileIO}.
+     */
     @Override
-    protected FileSystem createFileSystem(org.apache.hadoop.fs.Path path) {
+    protected FileSystem getFileSystem(org.apache.hadoop.fs.Path path) throws 
IOException {
+        if (fsMap == null) {
+            synchronized (this) {
+                if (fsMap == null) {
+                    fsMap = new ConcurrentHashMap<>();
+                }
+            }
+        }
+
+        final Map<Pair<String, String>, FileSystem> map = fsMap;
+        URI uri = path.toUri();
+        Pair<String, String> key = Pair.of(uri.getScheme(), 
uri.getAuthority());
+
+        // Create outside fsMap's ConcurrentHashMap compute lock.
+        while (true) {
+            FileSystem current = map.get(key);
+            if (isUsableFileSystem(current)) {
+                return current;
+            }
+
+            FileSystem created = createFileSystem(path);
+            if (!isUsableFileSystem(created)) {
+                continue;
+            }
+
+            if (current == null) {
+                FileSystem existing = map.putIfAbsent(key, created);
+                if (existing == null) {
+                    if (isUsableFileSystem(created)) {
+                        return created;
+                    }
+                    map.remove(key, created);
+                    continue;
+                }
+                if (isUsableFileSystem(existing)) {
+                    return existing;
+                }
+                current = existing;
+            }
+
+            if (isUsableFileSystem(current)) {
+                return current;
+            }
+            if (!map.replace(key, current, created)) {
+                continue;
+            }
+            if (isUsableFileSystem(created)) {
+                return created;
+            }
+            map.remove(key, created);
+        }
+    }
+
+    @Override
+    protected FileSystem createFileSystem(org.apache.hadoop.fs.Path path) 
throws IOException {
         final String scheme = path.toUri().getScheme();
         final String authority = path.toUri().getAuthority();
-        return CACHE.computeIfAbsent(
-                new CacheKey(hadoopOptions, scheme, authority),
-                key -> {
-                    Configuration hadoopConf = new Configuration();
-                    key.options.toMap().forEach(hadoopConf::set);
-                    URI fsUri = path.toUri();
-                    if (scheme == null && authority == null) {
-                        fsUri = FileSystem.getDefaultUri(hadoopConf);
-                    } else if (scheme != null && authority == null) {
-                        URI defaultUri = FileSystem.getDefaultUri(hadoopConf);
-                        if (scheme.equals(defaultUri.getScheme())
-                                && defaultUri.getAuthority() != null) {
-                            fsUri = defaultUri;
-                        }
-                    }
+        final CacheKey cacheKey = new CacheKey(hadoopOptions, scheme, 
authority);
 
-                    S3AFileSystem fs = new S3AFileSystem();
-                    try {
-                        fs.initialize(fsUri, hadoopConf);
-                    } catch (IOException e) {
-                        throw new UncheckedIOException(e);
-                    }
-                    return fs;
-                });
+        S3AFileSystem cached = CACHE.get(cacheKey);
+        if (isUsableFileSystem(cached)) {
+            return cached;
+        }
+
+        Object lock = getCacheLock(cacheKey);
+        synchronized (lock) {
+            cached = CACHE.get(cacheKey);
+            if (isUsableFileSystem(cached)) {
+                return cached;
+            }
+
+            // Only this confirmed mapping may be removed if initialize fails.
+            final S3AFileSystem expectedOld = cached;
+
+            Configuration hadoopConf = new Configuration();
+            cacheKey.options.toMap().forEach(hadoopConf::set);
+            URI fsUri = path.toUri();
+            if (scheme == null && authority == null) {
+                fsUri = FileSystem.getDefaultUri(hadoopConf);
+            } else if (scheme != null && authority == null) {
+                URI defaultUri = FileSystem.getDefaultUri(hadoopConf);
+                if (scheme.equals(defaultUri.getScheme()) && 
defaultUri.getAuthority() != null) {
+                    fsUri = defaultUri;
+                }
+            }
+
+            RecoverableS3AFileSystem fs = newRecoverableFileSystem();
+            fs.bind(() -> CACHE.remove(cacheKey, fs));
+            try {
+                fs.initialize(fsUri, hadoopConf);
+                if (!fs.isUsable()) {
+                    throw new IOException("S3A filesystem became unusable 
during initialize");
+                }
+            } catch (IOException | RuntimeException | Error e) {
+                discardFailedCreate(cacheKey, expectedOld, fs);
+                throw e;
+            }
+
+            // Once put returns, other threads may already observe this 
instance via CACHE.get.
+            // Evict on post-publish failure, but do not close: a borrower may 
still be using it.
+            CACHE.put(cacheKey, fs);
+            if (!fs.isUsable()) {
+                CACHE.remove(cacheKey, fs);
+                throw new IOException(
+                        "S3A filesystem became unusable before cache publish 
completed");
+            }
+            return fs;
+        }
+    }
+
+    RecoverableS3AFileSystem newRecoverableFileSystem() {
+        return new RecoverableS3AFileSystem();
+    }
+
+    /**
+     * Cleans up after a failed create: remove only {@code expectedOld} if it 
is still cached, and
+     * close the unpublished filesystem. Never removes a newer published 
instance.
+     */
+    private static void discardFailedCreate(
+            CacheKey cacheKey, S3AFileSystem expectedOld, S3AFileSystem 
unpublished) {
+        if (expectedOld != null) {
+            CACHE.remove(cacheKey, expectedOld);
+        }
+        try {
+            unpublished.close();
+        } catch (Throwable t) {
+            LOG.warn("Failed to close unpublished S3AFileSystem after 
initialize failure", t);
+        }
+    }
+
+    private static Object[] createCacheLocks() {
+        Object[] locks = new Object[CACHE_LOCK_COUNT];
+        for (int i = 0; i < locks.length; i++) {
+            locks[i] = new Object();
+        }
+        return locks;
+    }
+
+    private static Object getCacheLock(CacheKey key) {
+        return CACHE_LOCKS[Math.floorMod(key.hashCode(), CACHE_LOCK_COUNT)];
+    }
+
+    static boolean isUsableFileSystem(FileSystem fs) {
+        if (fs == null) {
+            return false;
+        }
+        if (fs instanceof RecoverableS3AFileSystem) {
+            return ((RecoverableS3AFileSystem) fs).isUsable();
+        }
+        return true;
+    }
+
+    static void clearCache() {
+        CACHE.clear();
     }
 
     private static class CacheKey {
diff --git 
a/paimon-filesystems/paimon-s3-impl/src/test/java/org/apache/paimon/s3/S3FileIOCacheRecoveryTest.java
 
b/paimon-filesystems/paimon-s3-impl/src/test/java/org/apache/paimon/s3/S3FileIOCacheRecoveryTest.java
new file mode 100644
index 0000000000..5e45a3f441
--- /dev/null
+++ 
b/paimon-filesystems/paimon-s3-impl/src/test/java/org/apache/paimon/s3/S3FileIOCacheRecoveryTest.java
@@ -0,0 +1,541 @@
+/*
+ * 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.paimon.s3;
+
+import org.apache.paimon.catalog.CatalogContext;
+import org.apache.paimon.options.Options;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests cache recovery after Apache HTTP pool shutdown without contacting a 
real S3 endpoint. */
+class S3FileIOCacheRecoveryTest {
+
+    private static final String BUCKET = "paimon-cache-recovery-bucket";
+
+    @BeforeEach
+    @AfterEach
+    void clearCache() {
+        S3FileIO.clearCache();
+    }
+
+    @Test
+    void testPoolShutdownEvictsAndReplacesFileSystem() throws Exception {
+        S3FileIO fileIO = newFileIO("opts-replace");
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem first = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        first.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        assertThat(first.isUsable()).isFalse();
+
+        RecoverableS3AFileSystem second = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        assertThat(second).isNotSameAs(first);
+        assertThat(second.isUsable()).isTrue();
+        assertThat(fileIO.getFileSystem(path)).isSameAs(second);
+    }
+
+    @Test
+    void testLateCallbackFromOldInstanceDoesNotDropNewInstance() throws 
Exception {
+        S3FileIO fileIO = newFileIO("opts-late");
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem oldFs = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        oldFs.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        RecoverableS3AFileSystem newFs = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        assertThat(newFs).isNotSameAs(oldFs);
+
+        oldFs.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        assertThat(newFs.isUsable()).isTrue();
+        assertThat(fileIO.getFileSystem(path)).isSameAs(newFs);
+    }
+
+    @Test
+    void testUnrelatedFailureDoesNotEvict() throws Exception {
+        S3FileIO fileIO = newFileIO("opts-unrelated");
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem fs = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        fs.handleExecutionFailure(new IOException("timeout"));
+        fs.handleExecutionFailure(new IllegalStateException("other illegal 
state"));
+        fs.handleExecutionFailure(
+                new IllegalStateException("Connection pool shut down while 
requesting"));
+
+        assertThat(fs.isUsable()).isTrue();
+        assertThat(fileIO.getFileSystem(path)).isSameAs(fs);
+    }
+
+    @Test
+    void testCauseChainPoolShutdownIsDetected() {
+        Throwable nested =
+                new IOException("wrap", new IllegalStateException("Connection 
pool shut down"));
+        
assertThat(RecoverableS3AFileSystem.isApachePoolShutdown(nested)).isTrue();
+        assertThat(RecoverableS3AFileSystem.isApachePoolShutdown(new 
IOException("x"))).isFalse();
+
+        IOException first = new IOException("first");
+        IOException second = new IOException("second");
+        first.initCause(second);
+        second.initCause(first);
+        
assertThat(RecoverableS3AFileSystem.isApachePoolShutdown(first)).isFalse();
+    }
+
+    @Test
+    void testInitIOExceptionClosesUnpublishedAndPropagates() throws Exception {
+        IOException failure = new IOException("forced initialize failure");
+        verifyInitFailure(failure, failure, "opts-io-fail");
+    }
+
+    @Test
+    void testInitRuntimeExceptionClosesUnpublishedAndPropagates() throws 
Exception {
+        RuntimeException failure = new IllegalStateException("runtime 
initialize failure");
+        verifyInitFailure(failure, failure, "opts-runtime-fail");
+    }
+
+    @Test
+    void testInitErrorClosesUnpublishedAndPropagates() throws Exception {
+        Error failure = new AssertionError("error initialize failure");
+        verifyInitFailure(failure, failure, "opts-error-fail");
+    }
+
+    @Test
+    void testInitFailureDoesNotAffectDifferentCacheKey() throws Exception {
+        Path path = path("s3a", "warehouse/a");
+        S3FileIO publishedIO = newFileIO("opts-published");
+        RecoverableS3AFileSystem published =
+                (RecoverableS3AFileSystem) publishedIO.getFileSystem(path);
+        assertThat(published.isUsable()).isTrue();
+
+        AtomicReference<CloseTrackingFileSystem> created = new 
AtomicReference<>();
+        S3FileIO failingIO =
+                newFileIO(
+                        "opts-init-identity",
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    public void initialize(URI uri, 
Configuration conf)
+                                            throws IOException {
+                                        created.set(this);
+                                        throw new IOException("forced 
initialize failure");
+                                    }
+                                });
+
+        // Keep an unusable expectedOld in the failing CacheKey so 
discardFailedCreate has a target.
+        S3FileIO stickyIO =
+                newFileIO(
+                        "opts-init-identity",
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    void bind(Runnable evictFromCache) {
+                                        // Keep the unusable instance in CACHE 
as expectedOld.
+                                    }
+                                });
+        RecoverableS3AFileSystem oldFs = (RecoverableS3AFileSystem) 
stickyIO.getFileSystem(path);
+        oldFs.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+        assertThat(oldFs.isUsable()).isFalse();
+
+        assertThatThrownBy(() -> failingIO.getFileSystem(path))
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("forced initialize failure");
+        assertThat(created.get()).isNotNull();
+        assertThat(created.get().closed).isTrue();
+
+        // Other CacheKey's published FS must remain usable.
+        assertThat(publishedIO.getFileSystem(path)).isSameAs(published);
+        assertThat(published.isUsable()).isTrue();
+
+        RecoverableS3AFileSystem recovered =
+                (RecoverableS3AFileSystem) 
newFileIO("opts-init-identity").getFileSystem(path);
+        assertThat(recovered.isUsable()).isTrue();
+        assertThat(recovered).isNotSameAs(oldFs);
+    }
+
+    @Test
+    void testPostPublishUnusableDoesNotCloseBorrowedInstance() throws 
Exception {
+        Options options = baseOptions("opts-post-publish");
+        Path path = path("s3a", "warehouse/a");
+        CountDownLatch afterPutCheckStarted = new CountDownLatch(1);
+        CountDownLatch borrowerHasFs = new CountDownLatch(1);
+        AtomicReference<CloseTrackingFileSystem> created = new 
AtomicReference<>();
+        AtomicInteger usableChecksAfterInit = new AtomicInteger();
+
+        S3FileIO creator =
+                newFileIO(
+                        options,
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    public void initialize(URI uri, 
Configuration conf)
+                                            throws IOException {
+                                        created.set(this);
+                                        super.initialize(uri, conf);
+                                    }
+
+                                    @Override
+                                    boolean isUsable() {
+                                        if (!super.isUsable()) {
+                                            return false;
+                                        }
+                                        // 1st: pre-put health check; 2nd: 
post-put health check.
+                                        int check = 
usableChecksAfterInit.incrementAndGet();
+                                        if (check == 1) {
+                                            return true;
+                                        }
+                                        if (check == 2) {
+                                            afterPutCheckStarted.countDown();
+                                            try {
+                                                assertThat(
+                                                                
borrowerHasFs.await(
+                                                                        30, 
TimeUnit.SECONDS))
+                                                        .isTrue();
+                                            } catch (InterruptedException e) {
+                                                
Thread.currentThread().interrupt();
+                                                throw new RuntimeException(e);
+                                            }
+                                            markUnusableAndEvict();
+                                            return false;
+                                        }
+                                        return super.isUsable();
+                                    }
+                                });
+
+        S3FileIO borrower = configure(options);
+        ExecutorService executor = Executors.newSingleThreadExecutor();
+        try {
+            Future<FileSystem> borrowed =
+                    executor.submit(
+                            () -> {
+                                assertThat(afterPutCheckStarted.await(30, 
TimeUnit.SECONDS))
+                                        .isTrue();
+                                FileSystem fs = borrower.getFileSystem(path);
+                                borrowerHasFs.countDown();
+                                return fs;
+                            });
+
+            assertThatThrownBy(() -> creator.getFileSystem(path))
+                    .isInstanceOf(IOException.class)
+                    .hasMessageContaining("before cache publish completed");
+
+            FileSystem borrowedFs = borrowed.get(30, TimeUnit.SECONDS);
+            assertThat(borrowedFs).isSameAs(created.get());
+            assertThat(created.get().closed).isFalse();
+            assertThat(created.get().isUsable()).isFalse();
+
+            RecoverableS3AFileSystem recovered =
+                    (RecoverableS3AFileSystem) 
configure(options).getFileSystem(path);
+            assertThat(recovered.isUsable()).isTrue();
+            assertThat(recovered).isNotSameAs(created.get());
+        } finally {
+            borrowerHasFs.countDown();
+            executor.shutdownNow();
+        }
+    }
+
+    @Test
+    void testSameCacheKeyCreateIsSerializedByStripeLock() throws Exception {
+        Options options = baseOptions("opts-lock-mutex");
+        Path path = path("s3a", "warehouse/a");
+        AtomicInteger concurrentInitializes = new AtomicInteger();
+        AtomicInteger maxConcurrentInitializes = new AtomicInteger();
+        CountDownLatch bothEntered = new CountDownLatch(2);
+        CountDownLatch release = new CountDownLatch(1);
+
+        Supplier<RecoverableS3AFileSystem> factory =
+                () ->
+                        new CloseTrackingFileSystem() {
+                            @Override
+                            public void initialize(URI uri, Configuration 
conf) throws IOException {
+                                int active = 
concurrentInitializes.incrementAndGet();
+                                
maxConcurrentInitializes.accumulateAndGet(active, Math::max);
+                                bothEntered.countDown();
+                                try {
+                                    assertThat(release.await(30, 
TimeUnit.SECONDS)).isTrue();
+                                    super.initialize(uri, conf);
+                                } catch (InterruptedException e) {
+                                    Thread.currentThread().interrupt();
+                                    throw new IOException(e);
+                                } finally {
+                                    concurrentInitializes.decrementAndGet();
+                                }
+                            }
+                        };
+
+        S3FileIO firstIO = newFileIO(options, factory);
+        S3FileIO secondIO = newFileIO(options, factory);
+        ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            Future<FileSystem> first = executor.submit(() -> 
firstIO.getFileSystem(path));
+            Future<FileSystem> second = executor.submit(() -> 
secondIO.getFileSystem(path));
+
+            // Only one initialize can hold the stripe lock; the second waits 
outside.
+            assertThat(bothEntered.await(1, TimeUnit.SECONDS)).isFalse();
+            assertThat(maxConcurrentInitializes.get()).isEqualTo(1);
+            release.countDown();
+
+            FileSystem fs1 = first.get(30, TimeUnit.SECONDS);
+            FileSystem fs2 = second.get(30, TimeUnit.SECONDS);
+            assertThat(fs2).isSameAs(fs1);
+            assertThat(maxConcurrentInitializes.get()).isEqualTo(1);
+        } finally {
+            release.countDown();
+            executor.shutdownNow();
+        }
+    }
+
+    @Test
+    void testUnusableDuringInitializeIsNotPublishedAndIsClosed() throws 
Exception {
+        Path path = path("s3a", "warehouse/a");
+        AtomicReference<CloseTrackingFileSystem> created = new 
AtomicReference<>();
+        S3FileIO fileIO =
+                newFileIO(
+                        "opts-unusable-during-init",
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    public void initialize(URI uri, 
Configuration conf)
+                                            throws IOException {
+                                        created.set(this);
+                                        super.initialize(uri, conf);
+                                        markUnusableAndEvict();
+                                    }
+                                });
+
+        assertThatThrownBy(() -> fileIO.getFileSystem(path))
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("became unusable during initialize");
+        assertThat(created.get()).isNotNull();
+        assertThat(created.get().closed).isTrue();
+        assertThat(created.get().isUsable()).isFalse();
+
+        RecoverableS3AFileSystem recovered =
+                (RecoverableS3AFileSystem)
+                        
newFileIO("opts-unusable-during-init").getFileSystem(path);
+        assertThat(recovered.isUsable()).isTrue();
+        assertThat(recovered).isNotSameAs(created.get());
+    }
+
+    @Test
+    void testConcurrentRecoveryCreatesSingleUsableInstance() throws Exception {
+        S3FileIO fileIO = newFileIO("opts-concurrent");
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem first = (RecoverableS3AFileSystem) 
fileIO.getFileSystem(path);
+        first.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        int threads = 8;
+        ExecutorService executor = Executors.newFixedThreadPool(threads);
+        CyclicBarrier barrier = new CyclicBarrier(threads);
+        List<Future<FileSystem>> futures = new ArrayList<>();
+        try {
+            for (int i = 0; i < threads; i++) {
+                futures.add(
+                        executor.submit(
+                                () -> {
+                                    barrier.await();
+                                    return fileIO.getFileSystem(path);
+                                }));
+            }
+            FileSystem expected = futures.get(0).get(30, TimeUnit.SECONDS);
+            for (Future<FileSystem> future : futures) {
+                assertThat(future.get(30, 
TimeUnit.SECONDS)).isSameAs(expected);
+            }
+            assertThat(((RecoverableS3AFileSystem) 
expected).isUsable()).isTrue();
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test
+    void testTwoFileIOInstancesConcurrentlyRecoverToSameFileSystem() throws 
Exception {
+        Options options = baseOptions("opts-two-io-concurrent");
+        S3FileIO firstIO = configure(options);
+        S3FileIO secondIO = configure(options);
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem oldFs = (RecoverableS3AFileSystem) 
firstIO.getFileSystem(path);
+        assertThat(secondIO.getFileSystem(path)).isSameAs(oldFs);
+        oldFs.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        CyclicBarrier barrier = new CyclicBarrier(2);
+        ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            Future<FileSystem> first =
+                    executor.submit(
+                            () -> {
+                                barrier.await();
+                                return firstIO.getFileSystem(path);
+                            });
+            Future<FileSystem> second =
+                    executor.submit(
+                            () -> {
+                                barrier.await();
+                                return secondIO.getFileSystem(path);
+                            });
+
+            FileSystem recovered = first.get(30, TimeUnit.SECONDS);
+            assertThat(second.get(30, TimeUnit.SECONDS)).isSameAs(recovered);
+            assertThat(recovered).isNotSameAs(oldFs);
+            assertThat(((RecoverableS3AFileSystem) 
recovered).isUsable()).isTrue();
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    @Test
+    void testTwoFileIOInstancesShareRecoveredCache() throws Exception {
+        Options options = baseOptions("opts-shared");
+        S3FileIO firstIO = configure(options);
+        S3FileIO secondIO = configure(options);
+        Path path = path("s3a", "warehouse/a");
+
+        RecoverableS3AFileSystem first = (RecoverableS3AFileSystem) 
firstIO.getFileSystem(path);
+        first.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        RecoverableS3AFileSystem fromSecond =
+                (RecoverableS3AFileSystem) secondIO.getFileSystem(path);
+        RecoverableS3AFileSystem fromFirst = (RecoverableS3AFileSystem) 
firstIO.getFileSystem(path);
+
+        assertThat(fromSecond).isSameAs(fromFirst);
+        assertThat(fromSecond).isNotSameAs(first);
+        assertThat(fromSecond.isUsable()).isTrue();
+    }
+
+    private static void verifyInitFailure(
+            Throwable toThrow, Throwable expected, String optionMarker) throws 
Exception {
+        Path path = path("s3a", "warehouse/a");
+        AtomicReference<CloseTrackingFileSystem> created = new 
AtomicReference<>();
+
+        // Leave an unusable expectedOld in CACHE so discardFailedCreate 
exercises identity remove.
+        S3FileIO stickyIO =
+                newFileIO(
+                        optionMarker,
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    void bind(Runnable evictFromCache) {
+                                        // Keep unusable instance mapped for 
expectedOld.
+                                    }
+                                });
+        RecoverableS3AFileSystem oldFs = (RecoverableS3AFileSystem) 
stickyIO.getFileSystem(path);
+        oldFs.handleExecutionFailure(new IllegalStateException("Connection 
pool shut down"));
+
+        S3FileIO failingIO =
+                newFileIO(
+                        optionMarker,
+                        () ->
+                                new CloseTrackingFileSystem() {
+                                    @Override
+                                    public void initialize(URI uri, 
Configuration conf)
+                                            throws IOException {
+                                        created.set(this);
+                                        if (toThrow instanceof IOException) {
+                                            throw (IOException) toThrow;
+                                        }
+                                        if (toThrow instanceof 
RuntimeException) {
+                                            throw (RuntimeException) toThrow;
+                                        }
+                                        throw (Error) toThrow;
+                                    }
+                                });
+
+        assertThatThrownBy(() -> 
failingIO.getFileSystem(path)).isSameAs(expected);
+        assertThat(created.get()).isNotNull();
+        assertThat(created.get().closed).isTrue();
+
+        RecoverableS3AFileSystem recovered =
+                (RecoverableS3AFileSystem) 
newFileIO(optionMarker).getFileSystem(path);
+        assertThat(recovered.isUsable()).isTrue();
+        assertThat(recovered).isNotSameAs(oldFs);
+        assertThat(recovered).isNotSameAs(created.get());
+    }
+
+    private static S3FileIO newFileIO(String optionMarker) {
+        return configure(baseOptions(optionMarker));
+    }
+
+    private static S3FileIO newFileIO(
+            String optionMarker, Supplier<RecoverableS3AFileSystem> factory) {
+        return newFileIO(baseOptions(optionMarker), factory);
+    }
+
+    private static S3FileIO newFileIO(Options options, 
Supplier<RecoverableS3AFileSystem> factory) {
+        S3FileIO fileIO =
+                new S3FileIO() {
+                    @Override
+                    RecoverableS3AFileSystem newRecoverableFileSystem() {
+                        return factory.get();
+                    }
+                };
+        fileIO.configure(CatalogContext.create(options));
+        return fileIO;
+    }
+
+    private static S3FileIO configure(Options options) {
+        S3FileIO fileIO = new S3FileIO();
+        fileIO.configure(CatalogContext.create(options));
+        return fileIO;
+    }
+
+    private static Options baseOptions(String optionMarker) {
+        Options options = new Options();
+        options.set("s3.bucket.probe", "0");
+        options.set("s3.endpoint", "http://localhost:1";);
+        options.set("s3.endpoint.region", "us-east-1");
+        options.set("s3.access-key", "dummy-access-key-" + optionMarker);
+        options.set("s3.secret-key", "dummy-secret-key");
+        options.set("fs.s3a.user.agent.prefix", optionMarker);
+        return options;
+    }
+
+    private static Path path(String scheme, String key) {
+        return new Path(scheme + "://" + BUCKET + "/" + key);
+    }
+
+    private static class CloseTrackingFileSystem extends 
RecoverableS3AFileSystem {
+        private boolean closed;
+
+        @Override
+        public void close() {
+            closed = true;
+        }
+    }
+}
diff --git 
a/paimon-filesystems/paimon-s3/src/test/java/org/apache/paimon/s3/S3ASchemeTest.java
 
b/paimon-filesystems/paimon-s3/src/test/java/org/apache/paimon/s3/S3ASchemeTest.java
index 23394cb0fb..ebf41c7cc7 100644
--- 
a/paimon-filesystems/paimon-s3/src/test/java/org/apache/paimon/s3/S3ASchemeTest.java
+++ 
b/paimon-filesystems/paimon-s3/src/test/java/org/apache/paimon/s3/S3ASchemeTest.java
@@ -142,10 +142,23 @@ public class S3ASchemeTest {
                         + ", getUri() = "
                         + fsUri);
 
-        assertEquals("org.apache.hadoop.fs.s3a.S3AFileSystem", 
fs.getClass().getName());
+        // Plugin FileSystem may be a subclass (e.g. RecoverableS3AFileSystem) 
loaded in an
+        // isolated classloader; walk superclasses by name instead of using 
instanceof.
+        assertTrue(
+                isS3AFileSystem(fs.getClass()),
+                "expected S3AFileSystem ancestry, got " + 
fs.getClass().getName());
         assertEquals(scheme, fsUri.getScheme());
         assertEquals(bucket, fsUri.getHost());
         assertEquals("probe", fileIO.readFileUtf8(path));
         assertTrue(fileIO.delete(path, false));
     }
+
+    private static boolean isS3AFileSystem(Class<?> clazz) {
+        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
+            if ("org.apache.hadoop.fs.s3a.S3AFileSystem".equals(c.getName())) {
+                return true;
+            }
+        }
+        return false;
+    }
 }

Reply via email to