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

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


The following commit(s) were added to refs/heads/master by this push:
     new 6f7650e8cf8 [fix](jni) Clean up resources after JNI open and close 
failures (#71084)
6f7650e8cf8 is described below

commit 6f7650e8cf894553b33bca3cff59905c89b77229
Author: Jerry Hu <[email protected]>
AuthorDate: Wed Dec 2 14:08:32 2026 +0800

    [fix](jni) Clean up resources after JNI open and close failures (#71084)
    
    ### Background
    
    JNI reader and writer plugins acquire JDBC connections, statements,
    result sets, or local file handles. JDBC connections come from cached
    Hikari pools, which can serve multiple operations. Native writers call
    Java close to finalize output and may read statistics afterward.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Bugfix
    
    Problem Summary:
    
    Partially failed JDBC initialization can leave resources unclosed;
    cleanup exceptions can skip later closes or make subsequent close
    falsely succeed. Separate failed-open cleanup from one-shot
    finalization, preserve errors, distinguish EOF from physical abort, and
    release each borrow without shutting down shared pools. Most additions
    exercise failure paths and ownership.
    
    ### Details
    
    - **Change map:** 20 files: production +228/-92, tests +1596/-3; no
    generated files or documentation changes. Production changes group into
    JDBC acquisition, cleanup and pool ownership (+176/-77), native
    close-result handling (+17/-9), and local-file cleanup plus diagnostics
    (+35/-6).
    - **Frequency:** Always for the reproduced partial-open/cleanup failure
    paths; EOF/abort behavior depends on driver closed-state semantics, and
    pool interference requires overlapping borrowers. Physical release
    depends on the driver.
    - **Root cause:** Open handlers omitted cleanup; shared cleanup blocks
    skipped later closes and discarded errors. Native close marked
    completion before JNI environment acquisition; flush failure skipped
    file close. Physical abort was confused with returning a Hikari borrow,
    and minimum idle count with exclusive ownership.
    - **Why existing tests missed it:** `JdbcDiagnosticsTest` emphasized
    diagnostics; counting proxies omitted post-abort physical closure, and
    real-Hikari coverage had one positive-minimum borrower. SQL
    diagnostics/transaction suites did not inject failures;
    `test_insert_into_local_tvf_jni` unconditionally returns.
    - **Fix:** Attempt cleanup independently, retaining the first exception
    and suppressing later failures. Roll back failed initialization without
    committing. Track EOF; evict successfully aborted borrows before proxy
    close. Atomically publish one pool, closing only unpublished candidates.
    Retain Java finalization outcomes; retry only pre-entry environment
    acquisition. Close files despite flush failure and include suppressed
    diagnostics with existing redaction.
    - **Other paths and branches:** Legacy/V2 readers share the scanner; V2
    already cleans up failed open. Default/MySQL/Oracle statement creation
    and all three pool creators are covered. Native close serves other JNI
    writers and preserves statistics. JNI/SPI and wire formats are
    unchanged. Release branches and bug origin were not established.
    - **Behavior change:** Scanner cleanup errors propagate; repeated writer
    close retains its result without repeating finalization. Zero-minimum
    pools follow existing cached idle/lifetime cleanup, not per-operation
    shutdown. Execution/cancellation transaction policy is unchanged.
    
    ### Testing
    
    All runs were local:
    
    - Original cleanup probes: 12 failing cases and 10 passing controls
    before the fix; final cleanup tests pass. Failed flush previously
    produced `flush must not skip close ==> expected: <1> but was: <0>`.
    - `run-fe-ut.sh`: 206 passed, including 12 real-Hikari ownership tests;
    18 existing external integration cases skipped without connection
    properties.
    - ASAN native tests via `run-be-ut.sh`: 21 passed across
    `VJniFormatTransformerTest`, `JniReaderTest`, `JniTableReaderTest` and
    `JdbcJniReaderTest`.
    - ASAN BE/FE and selected plugins built with `build.sh`; final Java
    plugins rebuilt. Checkstyle, clang-format v16, header hygiene and
    whitespace checks passed.
    - `test_jdbc_error_diagnostics` and
    `test_mysql_jdbc_catalog_write_transaction` passed with MySQL
    8.0/Connector-J 8.4.0, plus a zero-minimum transaction run and actual
    zero-row JDBC read. Transaction fixtures override driver location and
    optionally pool minimum, not SQL or expected output.
    
    ### Notes for Reviewers
    
    Java close can commit/publish before throwing; failed-open cleanup must
    not commit. Real-Hikari tests use physical-connection proxies, not SQL
    Server/Oracle servers.
    
    ### Release note
    
    JDBC JNI operations attempt remaining cleanup after initialization/close
    failure and retain errors. Local-file writers close despite flush
    failure. Exhausted/aborted JDBC reads avoid unnecessary closed-state
    errors; operations no longer shut down shared zero-minimum pools.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: No
    - Pre-submission status: Partially verified: real SQL Server/Oracle
    integration, disabled LOCAL TVF SQL, multi-BE and mixed-version runs
    were not performed.
    
    ### AI Disclosure
    
    - Tool: Codex
    - Generated: Code, tests, and this description.
    - Human review: Not performed yet.
---
 be/test/format/jni/jni_reader_test.cpp             |  36 +
 .../apache/doris/writer/LocalFileJniWriter.java    |  11 +-
 .../doris/writer/LocalFileResourceCleanupTest.java | 109 +++
 .../java/org/apache/doris/jdbc/JdbcCleanup.java    |  56 ++
 .../apache/doris/jdbc/JdbcConnectionTester.java    | 111 +---
 .../java/org/apache/doris/jdbc/JdbcDataSource.java |  11 +
 .../java/org/apache/doris/jdbc/JdbcJniScanner.java |  96 ++-
 .../java/org/apache/doris/jdbc/JdbcJniWriter.java  |  84 ++-
 .../org/apache/doris/jdbc/JdbcTypeHandler.java     |   9 +-
 .../org/apache/doris/jdbc/MySQLTypeHandler.java    |   7 +-
 .../org/apache/doris/jdbc/OracleTypeHandler.java   |   3 +-
 .../apache/doris/jdbc/SQLServerTypeHandler.java    |   4 +-
 .../jdbc/JdbcConnectionLogDiagnosticsTest.java     |  37 +-
 .../doris/jdbc/JdbcConnectionTesterTest.java       | 157 +++++
 .../org/apache/doris/jdbc/JdbcDiagnosticsTest.java |  40 +-
 .../apache/doris/jdbc/JdbcPoolOwnershipTest.java   | 664 +++++++++++++++++++
 .../apache/doris/jdbc/JdbcResourceCleanupTest.java | 727 +++++++++++++++++++++
 .../doris/jni/toolkit/jdbc/JdbcExceptionUtils.java |   6 +-
 .../jni/toolkit/jdbc/JdbcExceptionUtilsTest.java   |  16 +
 19 files changed, 2004 insertions(+), 180 deletions(-)

diff --git a/be/test/format/jni/jni_reader_test.cpp 
b/be/test/format/jni/jni_reader_test.cpp
new file mode 100644
index 00000000000..bea4b12cee8
--- /dev/null
+++ b/be/test/format/jni/jni_reader_test.cpp
@@ -0,0 +1,36 @@
+// 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.
+
+#include "format/jni/jni_reader.h"
+
+#include <gtest/gtest.h>
+
+#include "util/jni_plugin_registry.h"
+
+namespace doris {
+
+TEST(JniReaderTest, PartialOpenDoesNotRunJavaFinalization) {
+    // Java open must clean its own partial acquisition: legacy close skips 
unopened scanners.
+    JniReader reader(Jni::PluginRef {.plugin = "unused", .factory = "unused"}, 
{});
+    EXPECT_FALSE(reader._scanner_opened);
+    // Leave _scanner_api null: any attempted Java cleanup would dereference 
it.
+    EXPECT_TRUE(reader.close().ok());
+    EXPECT_TRUE(reader._closed);
+    EXPECT_TRUE(reader.close().ok());
+}
+
+} // namespace doris
diff --git 
a/fe/be-java-extensions/java-writer/src/main/java/org/apache/doris/writer/LocalFileJniWriter.java
 
b/fe/be-java-extensions/java-writer/src/main/java/org/apache/doris/writer/LocalFileJniWriter.java
index 322a8165f62..818a718b6bf 100644
--- 
a/fe/be-java-extensions/java-writer/src/main/java/org/apache/doris/writer/LocalFileJniWriter.java
+++ 
b/fe/be-java-extensions/java-writer/src/main/java/org/apache/doris/writer/LocalFileJniWriter.java
@@ -91,11 +91,14 @@ public class LocalFileJniWriter extends JniWriter {
     @Override
     protected void closeInternal() throws IOException {
         if (fileWriter != null) {
-            fileWriter.flush();
-            fileWriter.close();
-            fileWriter = null;
+            try {
+                // BufferedWriter.close flushes and closes its delegate even 
if flushing fails.
+                fileWriter.close();
+            } finally {
+                fileWriter = null;
+            }
+            LOG.info(() -> "closed " + filePath + " after " + writtenRows + " 
rows, " + writtenBytes + " bytes");
         }
-        LOG.info(() -> "closed " + filePath + " after " + writtenRows + " 
rows, " + writtenBytes + " bytes");
     }
 
     @Override
diff --git 
a/fe/be-java-extensions/java-writer/src/test/java/org/apache/doris/writer/LocalFileResourceCleanupTest.java
 
b/fe/be-java-extensions/java-writer/src/test/java/org/apache/doris/writer/LocalFileResourceCleanupTest.java
new file mode 100644
index 00000000000..84fd713c829
--- /dev/null
+++ 
b/fe/be-java-extensions/java-writer/src/test/java/org/apache/doris/writer/LocalFileResourceCleanupTest.java
@@ -0,0 +1,109 @@
+// 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.doris.writer;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.reflect.Field;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+
+class LocalFileResourceCleanupTest {
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void bufferedWriteFailureStillClosesDelegate(boolean failClose) throws 
Exception {
+        IOException writeFailure = new IOException("write failed");
+        IOException closeFailure = new IOException("close failed");
+        int[] closes = {0};
+        int[] writes = {0};
+        BufferedWriter buffered = new BufferedWriter(new Writer() {
+            @Override
+            public void write(char[] chars, int offset, int length) throws 
IOException {
+                writes[0]++;
+                throw writeFailure;
+            }
+
+            @Override
+            public void flush() {
+            }
+
+            @Override
+            public void close() throws IOException {
+                closes[0]++;
+                if (failClose) {
+                    throw closeFailure;
+                }
+            }
+        });
+        buffered.write("buffered data");
+        LocalFileJniWriter writer = writerWith(buffered);
+        Assertions.assertSame(writeFailure, 
Assertions.assertThrows(IOException.class, writer::close));
+        Assertions.assertArrayEquals(failClose ? new Throwable[] 
{closeFailure} : new Throwable[0],
+                writeFailure.getSuppressed());
+        writer.close();
+        Assertions.assertEquals(1, writes[0], "close must flush the buffer 
only once");
+        Assertions.assertEquals(1, closes[0]);
+        Assertions.assertThrows(IOException.class, () -> 
buffered.write("closed"));
+    }
+
+    @Test
+    void runtimeCloseFailureStillClearsWriter() throws Exception {
+        RuntimeException failure = new IllegalStateException("close failed");
+        int[] closes = {0};
+        LocalFileJniWriter writer = writerWith(new BufferedWriter(new 
StringWriter()) {
+            @Override
+            public void close() {
+                closes[0]++;
+                throw failure;
+            }
+        });
+        Assertions.assertSame(failure, 
Assertions.assertThrows(RuntimeException.class, writer::close));
+        writer.close();
+        Assertions.assertEquals(1, closes[0]);
+    }
+
+    @Test
+    void successfulRealFileCloseCanBeRepeated(@TempDir Path directory) throws 
Exception {
+        Path file = directory.resolve("success.csv");
+        BufferedWriter underlying = Files.newBufferedWriter(file);
+        underlying.write("2,ok\n");
+        LocalFileJniWriter writer = writerWith(underlying);
+        writer.close();
+        writer.close();
+        Assertions.assertEquals("2,ok\n", Files.readString(file));
+        Assertions.assertThrows(IOException.class, () -> 
underlying.write("closed"));
+    }
+
+    private static LocalFileJniWriter writerWith(BufferedWriter fileWriter) 
throws Exception {
+        LocalFileJniWriter writer = new LocalFileJniWriter(1, 
Collections.emptyMap());
+        Field field = LocalFileJniWriter.class.getDeclaredField("fileWriter");
+        field.setAccessible(true);
+        field.set(writer, fileWriter);
+        return writer;
+    }
+
+}
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcCleanup.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcCleanup.java
new file mode 100644
index 00000000000..caaa5470dec
--- /dev/null
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcCleanup.java
@@ -0,0 +1,56 @@
+// 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.doris.jdbc;
+
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+/** Resource acquisition and cleanup boundaries shared by JDBC readers and 
writers. */
+final class JdbcCleanup {
+    private JdbcCleanup() {
+    }
+
+    @FunctionalInterface
+    interface Action {
+        void run() throws Exception;
+    }
+
+    static Exception attempt(Exception primary, Action action) {
+        try {
+            action.run();
+        } catch (Exception cleanup) {
+            if (primary == null) {
+                return cleanup;
+            }
+            if (primary != cleanup) {
+                primary.addSuppressed(cleanup);
+            }
+        }
+        return primary;
+    }
+
+    static PreparedStatement setFetchSizeOrClose(PreparedStatement statement, 
int fetchSize) throws SQLException {
+        try {
+            statement.setFetchSize(fetchSize);
+            return statement;
+        } catch (SQLException | RuntimeException failure) {
+            attempt(failure, statement::close);
+            throw failure;
+        }
+    }
+}
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcConnectionTester.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcConnectionTester.java
index 4d00cf5ee63..97ea5c48e7e 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcConnectionTester.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcConnectionTester.java
@@ -31,7 +31,6 @@ import java.io.IOException;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
-import java.sql.SQLException;
 import java.util.Collections;
 import java.util.Map;
 
@@ -40,7 +39,7 @@ import java.util.Map;
  * It extends JniScanner to reuse the JniConnector infrastructure on the C++ 
side.
  *
  * <p>Usage: C++ creates a JniConnector with this class name and connection 
params,
- * calls open() to test the connection, then close() to clean up.
+ * calls open() to test the connection. All JDBC resources are released before 
open() returns.
  *
  * <p>The getNext() method is a no-op since this class is only used for 
testing.
  *
@@ -49,8 +48,7 @@ import java.util.Map;
  *   <li>jdbc_url, jdbc_user, jdbc_password, jdbc_driver_class, 
jdbc_driver_url</li>
  *   <li>jdbc_driver_checksum — MD5 of the driver JAR; verified once per jar, 
skipped when empty</li>
  *   <li>query_sql — the test query to run</li>
- *   <li>catalog_id, connection_pool_min_size, connection_pool_max_size, 
etc.</li>
- *   <li>clean_datasource — if "true", close the datasource pool on 
close()</li>
+ *   <li>connection_pool_max_wait_time, connection_pool_max_life_time, 
connection_pool_keep_alive</li>
  * </ul>
  */
 public class JdbcConnectionTester extends JniScanner {
@@ -63,20 +61,11 @@ public class JdbcConnectionTester extends JniScanner {
     private final String jdbcDriverUrl;
     private final String jdbcDriverChecksum;
     private final String querySql;
-    private final long catalogId;
-    private final int connectionPoolMinSize;
-    private final int connectionPoolMaxSize;
     private final int connectionPoolMaxWaitTime;
     private final int connectionPoolMaxLifeTime;
     private final boolean connectionPoolKeepAlive;
-    private final boolean cleanDatasource;
     private final JdbcTypeHandler typeHandler;
 
-    private HikariDataSource hikariDataSource = null;
-    private Connection conn = null;
-    private PreparedStatement stmt = null;
-    private ClassLoader classLoader = null;
-
     public JdbcConnectionTester(int batchSize, Map<String, String> params) {
         this.jdbcUrl = params.getOrDefault("jdbc_url", "");
         this.jdbcUser = params.getOrDefault("jdbc_user", "");
@@ -85,19 +74,12 @@ public class JdbcConnectionTester extends JniScanner {
         this.jdbcDriverUrl = params.getOrDefault("jdbc_driver_url", "");
         this.jdbcDriverChecksum = params.getOrDefault("jdbc_driver_checksum", 
"");
         this.querySql = params.getOrDefault("query_sql", "SELECT 1");
-        this.catalogId = Long.parseLong(params.getOrDefault("catalog_id", 
"0"));
-        this.connectionPoolMinSize = Integer.parseInt(
-                params.getOrDefault("connection_pool_min_size", "1"));
-        this.connectionPoolMaxSize = Integer.parseInt(
-                params.getOrDefault("connection_pool_max_size", "10"));
         this.connectionPoolMaxWaitTime = Integer.parseInt(
                 params.getOrDefault("connection_pool_max_wait_time", "5000"));
         this.connectionPoolMaxLifeTime = Integer.parseInt(
                 params.getOrDefault("connection_pool_max_life_time", 
"1800000"));
         this.connectionPoolKeepAlive = "true".equalsIgnoreCase(
                 params.getOrDefault("connection_pool_keep_alive", "false"));
-        this.cleanDatasource = "true".equalsIgnoreCase(
-                params.getOrDefault("clean_datasource", "false"));
 
         // Select database-specific type handler for validation query
         String tableType = params.getOrDefault("table_type", "");
@@ -116,50 +98,39 @@ public class JdbcConnectionTester extends JniScanner {
         ClassLoader oldClassLoader = 
Thread.currentThread().getContextClassLoader();
         try {
             // Same as JdbcJniScanner: set before the driver classes load, 
since this is a
-            // connection through the same driver and pool.
+            // connection through the same driver.
             typeHandler.setSystemProperties();
             // Same verification as the scanner, so that validating a catalog 
fails on a driver jar
             // that does not match its checksum rather than reporting the 
catalog as usable.
-            this.classLoader = 
JdbcDriverUtils.driverClassLoader(jdbcDriverUrl, getClass().getClassLoader(),
+            ClassLoader classLoader = 
JdbcDriverUtils.driverClassLoader(jdbcDriverUrl, getClass().getClassLoader(),
                     JdbcDriverUtils.checksumVerifier(jdbcDriverChecksum));
             Thread.currentThread().setContextClassLoader(classLoader);
 
-            String cacheKey = createCacheKey();
-            hikariDataSource = 
JdbcDataSource.getDataSource().getSource(cacheKey);
-            if (hikariDataSource == null) {
-                synchronized (JdbcConnectionTester.class) {
-                    hikariDataSource = 
JdbcDataSource.getDataSource().getSource(cacheKey);
-                    if (hikariDataSource == null) {
-                        HikariDataSource ds = new HikariDataSource();
-                        ds.setDriverClassName(jdbcDriverClass);
-                        ds.setJdbcUrl(jdbcUrl);
-                        ds.setUsername(jdbcUser);
-                        ds.setPassword(jdbcPassword);
-                        ds.setMinimumIdle(connectionPoolMinSize);
-                        ds.setMaximumPoolSize(connectionPoolMaxSize);
-                        ds.setConnectionTimeout(connectionPoolMaxWaitTime);
-                        ds.setMaxLifetime(connectionPoolMaxLifeTime);
-                        ds.setIdleTimeout(connectionPoolMaxLifeTime / 2L);
-                        // Use type handler for database-specific validation 
query
-                        // (e.g. Oracle: "SELECT 1 FROM dual", DB2: "select 1 
from sysibm.sysdummy1")
-                        typeHandler.setValidationQuery(ds);
-                        if (connectionPoolKeepAlive) {
-                            ds.setKeepaliveTime(connectionPoolMaxLifeTime / 
5L);
-                        }
-                        hikariDataSource = ds;
-                        JdbcDataSource.getDataSource().putSource(cacheKey, 
hikariDataSource);
+            // Legacy JNI skips Java close after a failed open. Own a one-shot 
pool here,
+            // never publishing it in the shared reader/writer cache.
+            try (HikariDataSource ds = new HikariDataSource()) {
+                ds.setDriverClassName(jdbcDriverClass);
+                ds.setJdbcUrl(jdbcUrl);
+                ds.setUsername(jdbcUser);
+                ds.setPassword(jdbcPassword);
+                ds.setMinimumIdle(0);
+                ds.setMaximumPoolSize(1);
+                ds.setConnectionTimeout(connectionPoolMaxWaitTime);
+                ds.setMaxLifetime(connectionPoolMaxLifeTime);
+                ds.setIdleTimeout(connectionPoolMaxLifeTime / 2L);
+                typeHandler.setValidationQuery(ds);
+                if (connectionPoolKeepAlive) {
+                    ds.setKeepaliveTime(connectionPoolMaxLifeTime / 5L);
+                }
+                try (Connection conn = ds.getConnection();
+                        PreparedStatement stmt = 
conn.prepareStatement(querySql);
+                        ResultSet rs = stmt.executeQuery()) {
+                    if (!rs.next()) {
+                        throw new IOException(
+                                "Failed to test connection: query executed but 
returned no results.");
                     }
                 }
             }
-
-            conn = hikariDataSource.getConnection();
-            stmt = conn.prepareStatement(querySql);
-            ResultSet rs = stmt.executeQuery();
-            if (!rs.next()) {
-                throw new IOException(
-                        "Failed to test connection: query executed but 
returned no results.");
-            }
-            rs.close();
             String safeJdbcUrl = JdbcExceptionUtils.redact(jdbcUrl, 
jdbcPassword, jdbcUrl);
             LOG.info("JdbcConnectionTester: connection test succeeded for " + 
safeJdbcUrl);
         } catch (Exception e) {
@@ -178,38 +149,12 @@ public class JdbcConnectionTester extends JniScanner {
     }
 
     @Override
-    protected void closeInternal() throws IOException {
-        try {
-            if (stmt != null && !stmt.isClosed()) {
-                stmt.close();
-            }
-            if (conn != null && !conn.isClosed()) {
-                conn.close();
-            }
-        } catch (SQLException e) {
-            String diagnostic = 
JdbcExceptionUtils.format("JdbcConnectionTester close error",
-                    e, jdbcPassword, jdbcUrl);
-            LOG.warn("{}", diagnostic);
-        } finally {
-            stmt = null;
-            conn = null;
-            if (cleanDatasource && hikariDataSource != null) {
-                hikariDataSource.close();
-                
JdbcDataSource.getDataSource().getSourcesMap().remove(createCacheKey());
-                hikariDataSource = null;
-            }
-        }
+    protected void closeInternal() {
+        // openInternal owns and releases all JDBC resources, on success and 
failure.
     }
 
     @Override
     protected Map<String, String> collectStatistics() {
         return Collections.emptyMap();
     }
-
-    private String createCacheKey() {
-        // The checksum for the same reason JdbcDataSource.createCacheKey 
carries it: a pool is
-        // bound to the driver it was created with, and this one is only ever 
short-lived because
-        // BE asks for clean_datasource - the key must not be what makes that 
true.
-        return catalogId + "#" + jdbcUrl + "#" + jdbcUser + "#" + 
jdbcDriverClass + "#" + jdbcDriverChecksum;
-    }
 }
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcDataSource.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcDataSource.java
index 0352818d2c9..6ce451e39a8 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcDataSource.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcDataSource.java
@@ -65,6 +65,17 @@ public class JdbcDataSource {
         lastAccessTimeMap.put(cacheKey, System.currentTimeMillis());
     }
 
+    // Candidates have not been published or borrowed yet. Only an unpublished 
loser is ours to close.
+    HikariDataSource putSourceIfAbsent(String cacheKey, HikariDataSource 
candidate) {
+        HikariDataSource cached = sourcesMap.putIfAbsent(cacheKey, candidate);
+        lastAccessTimeMap.put(cacheKey, System.currentTimeMillis());
+        if (cached == null) {
+            return candidate;
+        }
+        candidate.close();
+        return cached;
+    }
+
     public Map<String, HikariDataSource> getSourcesMap() {
         return sourcesMap;
     }
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniScanner.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniScanner.java
index 7ed832e5ff0..a8916ba187a 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniScanner.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniScanner.java
@@ -99,6 +99,10 @@ public class JdbcJniScanner extends JniScanner {
 
     // Read state
     private boolean resultSetOpened = false;
+    private boolean abortAttempted = false;
+    private boolean connectionUnusable = false;
+    private boolean connectionAborted = false;
+    private boolean resultSetExhausted = false;
     private List<Object[]> block = null;
     // Per-column replace strings for special type handling (bitmap, hll)
     private String[] replaceStringList;
@@ -170,6 +174,10 @@ public class JdbcJniScanner extends JniScanner {
             initializeClassLoaderAndDataSource();
 
             conn = hikariDataSource.getConnection();
+            abortAttempted = false;
+            connectionAborted = false;
+            connectionUnusable = false;
+            resultSetExhausted = false;
 
             // Use type handler to create the statement with database-specific 
settings
             stmt = typeHandler.initializeStatement(conn, querySql, batchSize);
@@ -213,7 +221,7 @@ public class JdbcJniScanner extends JniScanner {
                 outputConverters[i] = typeHandler.getOutputConverter(types[i], 
replaceStr);
             }
         } catch (Exception e) {
-            throw new JdbcIOException("JdbcJniScanner open failed", e, 
jdbcPassword, jdbcUrl);
+            throw new JdbcIOException("JdbcJniScanner open failed", 
closeResources(e), jdbcPassword, jdbcUrl);
         } finally {
             Thread.currentThread().setContextClassLoader(oldClassLoader);
         }
@@ -252,6 +260,7 @@ public class JdbcJniScanner extends JniScanner {
             int curRows = 0;
             while (curRows < batchSize) {
                 if (!resultSet.next()) {
+                    resultSetExhausted = true;
                     break;
                 }
                 for (int col = 0; col < types.length; col++) {
@@ -301,40 +310,62 @@ public class JdbcJniScanner extends JniScanner {
 
     @Override
     protected void closeInternal() throws IOException {
-        try {
-            // Use type handler for database-specific connection abort
-            if (conn != null && resultSet != null) {
-                typeHandler.abortReadConnection(conn, resultSet);
-            }
-        } catch (Exception e) {
-            String diagnostic = JdbcExceptionUtils.format("JdbcJniScanner 
abort connection error",
-                    e, jdbcPassword, jdbcUrl);
-            LOG.warn("{}", diagnostic);
+        Exception failure = closeResources(null);
+        if (failure != null) {
+            throw new JdbcIOException("JdbcJniScanner close failed", failure, 
jdbcPassword, jdbcUrl);
         }
-        try {
-            if (resultSet != null && !resultSet.isClosed()) {
+    }
+
+    private Exception closeResources(Exception failure) {
+        resultSetOpened = false;
+        resultSetMetaData = null;
+        // isAfterLast() can be false even at EOF for an empty SQLServer 
result.
+        if (conn != null && resultSet != null && !resultSetExhausted && 
!abortAttempted) {
+            abortAttempted = true;
+            failure = JdbcCleanup.attempt(failure, () -> {
+                connectionAborted = typeHandler.abortReadConnection(conn, 
resultSet);
+                if (connectionAborted) {
+                    // Successful physical abort terminates its 
statements/results too.
+                    resultSet = null;
+                    stmt = null;
+                }
+            });
+        }
+        if (resultSet != null) {
+            failure = JdbcCleanup.attempt(failure, () -> {
                 resultSet.close();
-            }
-            if (stmt != null && !stmt.isClosed()) {
+                resultSet = null;
+            });
+        }
+        if (stmt != null) {
+            failure = JdbcCleanup.attempt(failure, () -> {
                 stmt.close();
-            }
-            if (conn != null && !conn.isClosed()) {
-                conn.close();
-            }
-        } catch (Exception e) {
-            String diagnostic = JdbcExceptionUtils.format("JdbcJniScanner 
close error",
-                    e, jdbcPassword, jdbcUrl);
-            LOG.warn("{}", diagnostic);
-        } finally {
-            resultSet = null;
-            stmt = null;
-            conn = null;
-            if (connectionPoolMinSize == 0 && hikariDataSource != null) {
-                hikariDataSource.close();
-                
JdbcDataSource.getDataSource().getSourcesMap().remove(createCacheKey());
-                hikariDataSource = null;
-            }
+                stmt = null;
+            });
+        }
+        connectionUnusable |= failure != null || connectionAborted;
+        if (conn != null) {
+            failure = JdbcCleanup.attempt(failure, () -> {
+                // A failed statement close may already have removed it from 
Hikari's tracking.
+                // Failed open/cleanup and physical abort must never recycle 
this borrow.
+                // Preserve zero-idle per-borrow retirement without shutting 
down the shared pool:
+                // Hikari can recycle before an unrecognized proxy-close error 
escapes.
+                if (connectionUnusable || connectionPoolMinSize == 0) {
+                    hikariDataSource.evictConnection(conn);
+                }
+                // Eviction ends a zero-idle borrow; do not reset its detached 
pool entry.
+                if (connectionPoolMinSize != 0) {
+                    conn.close();
+                }
+                conn = null;
+                // Returning the parent connection ends this borrow, including 
its children.
+                resultSet = null;
+                stmt = null;
+            });
         }
+        connectionUnusable |= failure != null;
+        // The cached pool is shared, even with minimumIdle=0; its owner 
manages shutdown.
+        return failure;
     }
 
     @Override
@@ -389,8 +420,7 @@ public class JdbcJniScanner extends JniScanner {
                     if (connectionPoolKeepAlive) {
                         ds.setKeepaliveTime(connectionPoolMaxLifeTime / 5L);
                     }
-                    hikariDataSource = ds;
-                    JdbcDataSource.getDataSource().putSource(cacheKey, 
hikariDataSource);
+                    hikariDataSource = 
JdbcDataSource.getDataSource().putSourceIfAbsent(cacheKey, ds);
                     String safeJdbcUrl = JdbcExceptionUtils.redact(jdbcUrl, 
jdbcPassword, jdbcUrl);
                     LOG.info("JdbcJniScanner: Created connection pool for " + 
safeJdbcUrl);
                 }
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniWriter.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniWriter.java
index 9122e98880c..3acd5fa8916 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniWriter.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcJniWriter.java
@@ -95,6 +95,8 @@ public class JdbcJniWriter extends JniWriter {
     private Connection conn = null;
     private PreparedStatement preparedStatement = null;
     private ClassLoader classLoader = null;
+    private boolean commitPending = false;
+    private boolean connectionUnusable = false;
 
     // Statistics
     private long writtenRows = 0;
@@ -125,20 +127,28 @@ public class JdbcJniWriter extends JniWriter {
     @Override
     protected void openInternal() throws IOException {
         ClassLoader oldClassLoader = 
Thread.currentThread().getContextClassLoader();
+        boolean transactionStarted = false;
         try {
             initializeClassLoaderAndDataSource();
 
             conn = hikariDataSource.getConnection();
+            connectionUnusable = false;
             typeHandler.initializeWriteConnection(conn);
 
             if (useTransaction) {
                 conn.setAutoCommit(false);
+                transactionStarted = true;
             }
 
             LOG.debug("JdbcJniWriter: Preparing insert statement: " + 
insertSql);
             preparedStatement = conn.prepareStatement(insertSql);
+            commitPending = useTransaction;
         } catch (Exception e) {
-            throw new JdbcIOException("JdbcJniWriter open failed", e, 
jdbcPassword, jdbcUrl);
+            // Initialization must release resources without committing an 
incomplete open.
+            if (transactionStarted) {
+                JdbcCleanup.attempt(e, conn::rollback);
+            }
+            throw new JdbcIOException("JdbcJniWriter open failed", 
closeResources(e), jdbcPassword, jdbcUrl);
         } finally {
             Thread.currentThread().setContextClassLoader(oldClassLoader);
         }
@@ -169,41 +179,50 @@ public class JdbcJniWriter extends JniWriter {
 
     @Override
     protected void closeInternal() throws IOException {
-        try {
-            // Commit transaction before closing if useTransaction is enabled.
-            // autoCommit was set to false in open(), so without explicit 
commit()
-            // the JDBC driver will roll back all writes on connection close.
-            if (useTransaction && conn != null && !conn.isClosed()) {
+        // Consume commitPending before commit: a failed attempt must never be 
committed again.
+        Exception failure = null;
+        if (commitPending) {
+            commitPending = false;
+            try {
                 conn.commit();
+            } catch (Exception e) {
+                failure = JdbcCleanup.attempt(e, conn::rollback);
             }
-            if (preparedStatement != null && !preparedStatement.isClosed()) {
+        }
+        failure = closeResources(failure);
+        if (failure != null) {
+            throw new JdbcIOException("JdbcJniWriter close failed", failure, 
jdbcPassword, jdbcUrl);
+        }
+    }
+
+    private Exception closeResources(Exception failure) {
+        if (preparedStatement != null) {
+            failure = JdbcCleanup.attempt(failure, () -> {
                 preparedStatement.close();
-            }
-            if (conn != null && !conn.isClosed()) {
-                conn.close();
-            }
-        } catch (SQLException e) {
-            // If commit or close fails, attempt rollback before rethrowing
-            try {
-                if (useTransaction && conn != null && !conn.isClosed()) {
-                    conn.rollback();
+                preparedStatement = null;
+            });
+        }
+        connectionUnusable |= failure != null;
+        if (conn != null) {
+            failure = JdbcCleanup.attempt(failure, () -> {
+                // Nonfatal driver errors do not guarantee Hikari will discard 
a dirty borrow.
+                // Evict before proxy close; if eviction fails, do not return 
it normally.
+                // Preserve zero-idle per-borrow retirement without shutting 
down the shared pool:
+                // Hikari can recycle before an unrecognized proxy-close error 
escapes.
+                if (connectionUnusable || connectionPoolMinSize == 0) {
+                    hikariDataSource.evictConnection(conn);
                 }
-            } catch (SQLException rollbackEx) {
-                String diagnostic = JdbcExceptionUtils.format("JdbcJniWriter 
rollback on close failure also failed",
-                        rollbackEx, jdbcPassword, jdbcUrl);
-                LOG.warn("{}", diagnostic);
-            }
-            throw new JdbcIOException("JdbcJniWriter close failed", e, 
jdbcPassword, jdbcUrl);
-        } finally {
-            preparedStatement = null;
-            conn = null;
-            if (connectionPoolMinSize == 0 && hikariDataSource != null) {
-                hikariDataSource.close();
-                JdbcDataSource.getDataSource().getSourcesMap()
-                        .remove(createCacheKey());
-                hikariDataSource = null;
-            }
+                // Eviction ends a zero-idle borrow; do not reset its detached 
pool entry.
+                if (connectionPoolMinSize != 0) {
+                    conn.close();
+                }
+                conn = null;
+                preparedStatement = null;
+            });
         }
+        connectionUnusable |= failure != null;
+        // The cached pool is shared, even with minimumIdle=0; its owner 
manages shutdown.
+        return failure;
     }
 
     @Override
@@ -375,8 +394,7 @@ public class JdbcJniWriter extends JniWriter {
                     if (connectionPoolKeepAlive) {
                         ds.setKeepaliveTime(connectionPoolMaxLifeTime / 5L);
                     }
-                    hikariDataSource = ds;
-                    JdbcDataSource.getDataSource().putSource(cacheKey, 
hikariDataSource);
+                    hikariDataSource = 
JdbcDataSource.getDataSource().putSourceIfAbsent(cacheKey, ds);
                     String safeJdbcUrl = JdbcExceptionUtils.redact(jdbcUrl, 
jdbcPassword, jdbcUrl);
                     LOG.info("JdbcJniWriter: Created connection pool for " + 
safeJdbcUrl);
                 }
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcTypeHandler.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcTypeHandler.java
index f5b3024c6f1..be88ecb6f37 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcTypeHandler.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/JdbcTypeHandler.java
@@ -106,17 +106,18 @@ public interface JdbcTypeHandler {
                                                  int fetchSize) throws 
SQLException {
         PreparedStatement stmt = conn.prepareStatement(sql,
                 ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
-        stmt.setFetchSize(fetchSize);
-        return stmt;
+        return JdbcCleanup.setFetchSizeOrClose(stmt, fetchSize);
     }
 
     /**
      * Abort a read connection properly before closing resources.
      * Some databases (MySQL, SQLServer) need to abort() the connection to 
avoid
      * draining all remaining results, which can cause hangs on large result 
sets.
+     *
+     * @return true only when the physical connection was successfully aborted
      */
-    default void abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
-        // default: no-op
+    default boolean abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
+        return false;
     }
 
     /**
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/MySQLTypeHandler.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/MySQLTypeHandler.java
index 6f94cac49fc..0b7c5894565 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/MySQLTypeHandler.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/MySQLTypeHandler.java
@@ -215,16 +215,17 @@ public class MySQLTypeHandler extends DefaultTypeHandler {
         PreparedStatement stmt = conn.prepareStatement(sql,
                 ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
         // MySQL: Integer.MIN_VALUE signals streaming results to avoid OOM
-        stmt.setFetchSize(Integer.MIN_VALUE);
-        return stmt;
+        return JdbcCleanup.setFetchSizeOrClose(stmt, Integer.MIN_VALUE);
     }
 
     @Override
-    public void abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
+    public boolean abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
         if (rs != null && !rs.isAfterLast()) {
             // Abort connection to avoid draining all remaining results
             conn.abort(MoreExecutors.directExecutor());
+            return true;
         }
+        return false;
     }
 
     @Override
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/OracleTypeHandler.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/OracleTypeHandler.java
index bd70b5756c7..388f14cf8fe 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/OracleTypeHandler.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/OracleTypeHandler.java
@@ -142,8 +142,7 @@ public class OracleTypeHandler extends DefaultTypeHandler {
         }
         PreparedStatement stmt = conn.prepareStatement(sql,
                 ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
-        stmt.setFetchSize(fetchSize);
-        return stmt;
+        return JdbcCleanup.setFetchSizeOrClose(stmt, fetchSize);
     }
 
     @Override
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/SQLServerTypeHandler.java
 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/SQLServerTypeHandler.java
index 1cb40f929a3..0bcd7fee917 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/SQLServerTypeHandler.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/main/java/org/apache/doris/jdbc/SQLServerTypeHandler.java
@@ -108,12 +108,14 @@ public class SQLServerTypeHandler extends 
DefaultTypeHandler {
     }
 
     @Override
-    public void abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
+    public boolean abortReadConnection(Connection conn, ResultSet rs) throws 
SQLException {
         if (rs != null && !rs.isAfterLast()) {
             // SQLServer driver attempts to drain results on close.
             // Abort connection to prevent this behavior.
             conn.abort(MoreExecutors.directExecutor());
+            return true;
         }
+        return false;
     }
 
     @Override
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionLogDiagnosticsTest.java
 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionLogDiagnosticsTest.java
index c7f70a5ad77..05bfcc74c65 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionLogDiagnosticsTest.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionLogDiagnosticsTest.java
@@ -35,6 +35,7 @@ import java.sql.DriverPropertyInfo;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -58,9 +59,12 @@ class JdbcConnectionLogDiagnosticsTest {
             params.put("jdbc_driver_url", 
StubDriver.class.getProtectionDomain().getCodeSource()
                     .getLocation().toURI().toString());
             Object target = type.getConstructor(int.class, 
Map.class).newInstance(1, params);
-            Method cacheKey = type.getDeclaredMethod("createCacheKey");
-            cacheKey.setAccessible(true);
-            String key = (String) cacheKey.invoke(target);
+            String key = null;
+            if (type != JdbcConnectionTester.class) {
+                Method cacheKey = type.getDeclaredMethod("createCacheKey");
+                cacheKey.setAccessible(true);
+                key = (String) cacheKey.invoke(target);
+            }
             Connection connection = Mockito.mock(Connection.class);
             PreparedStatement statement = 
Mockito.mock(PreparedStatement.class);
             ResultSet result = Mockito.mock(ResultSet.class);
@@ -69,19 +73,21 @@ class JdbcConnectionLogDiagnosticsTest {
             Mockito.when(result.next()).thenReturn(true);
             ClassLoader original = 
Thread.currentThread().getContextClassLoader();
             if (type == JdbcConnectionTester.class) {
-                JdbcDataSource.getDataSource().putSource(key, new 
HikariDataSource() {
-                    @Override
-                    public Connection getConnection() {
-                        return connection;
-                    }
-                });
+                Mockito.when(connection.getAutoCommit()).thenReturn(true);
+                
Mockito.when(connection.isValid(Mockito.anyInt())).thenReturn(true);
+                
Mockito.when(connection.createStatement()).thenReturn(Mockito.mock(Statement.class));
+                StubDriver.connection = connection;
             }
             try (CapturedLog capture = new CapturedLog(type)) {
                 Method initialize = type.getDeclaredMethod(type == 
JdbcConnectionTester.class
                         ? "openInternal" : 
"initializeClassLoaderAndDataSource");
                 initialize.setAccessible(true);
                 initialize.invoke(target);
-                
Assertions.assertNotNull(JdbcDataSource.getDataSource().getSource(key));
+                if (key != null) {
+                    
Assertions.assertNotNull(JdbcDataSource.getDataSource().getSource(key));
+                } else {
+                    Mockito.verify(connection, Mockito.atLeastOnce()).close();
+                }
                 Assertions.assertEquals(1, capture.messages.size(), 
capture.messages.toString());
                 String text = capture.messages.get(0);
                 Assertions.assertTrue(text.contains(type.getSimpleName()), 
text);
@@ -92,11 +98,13 @@ class JdbcConnectionLogDiagnosticsTest {
             } finally {
                 try {
                     // Initialization can fail before the pool is added to the 
cache.
-                    HikariDataSource pool = 
JdbcDataSource.getDataSource().getSourcesMap().remove(key);
+                    HikariDataSource pool = key == null ? null
+                            : 
JdbcDataSource.getDataSource().getSourcesMap().remove(key);
                     if (pool != null) {
                         pool.close();
                     }
                 } finally {
+                    StubDriver.connection = null;
                     Thread.currentThread().setContextClassLoader(original);
                 }
             }
@@ -105,9 +113,14 @@ class JdbcConnectionLogDiagnosticsTest {
 
     /** Lets real Hikari configuration load a driver without opening any 
external connection. */
     public static class StubDriver implements Driver {
+        private static Connection connection;
+
         @Override
         public Connection connect(String url, Properties info) throws 
SQLException {
-            throw new SQLException("This test driver must not open a 
connection");
+            if (connection == null) {
+                throw new SQLException("This test driver has no configured 
connection");
+            }
+            return connection;
         }
 
         @Override
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionTesterTest.java
 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionTesterTest.java
new file mode 100644
index 00000000000..5169cdce58d
--- /dev/null
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcConnectionTesterTest.java
@@ -0,0 +1,157 @@
+// 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.doris.jdbc;
+
+import com.zaxxer.hikari.HikariDataSource;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverPropertyInfo;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.logging.Logger;
+
+public class JdbcConnectionTesterTest {
+    private static final CopyOnWriteArrayList<Connection> CONNECTIONS = new 
CopyOnWriteArrayList<>();
+    private static String failureAt;
+    private static final SQLException OPERATION_FAILURE = new 
SQLException("operation failed", "HY000", 51);
+    private static final SQLException CLOSE_FAILURE = new 
SQLException("statement close failed", "HY000", 52);
+
+    @ParameterizedTest
+    @ValueSource(strings = {"none", "prepare", "query", "next", "empty", 
"resultClose", "statementClose",
+            "queryAndClose"})
+    void openAlwaysClosesOneShotPoolWithoutNativeCleanup(String stage) throws 
Exception {
+        failureAt = stage;
+        CONNECTIONS.clear();
+        Map<String, HikariDataSource> cached = new 
HashMap<>(JdbcDataSource.getDataSource().getSourcesMap());
+        Map<String, String> params = new HashMap<>();
+        params.put("jdbc_url", "jdbc:tester:cleanup");
+        params.put("jdbc_driver_class", TestDriver.class.getName());
+        params.put("jdbc_driver_url", 
TestDriver.class.getProtectionDomain().getCodeSource()
+                .getLocation().toURI().toString());
+        params.put("connection_pool_max_wait_time", "1000");
+        // Even callers that omit clean_datasource must not leave a cached or 
live pool.
+        JdbcConnectionTester tester = new JdbcConnectionTester(1, params);
+        ClassLoader original = Thread.currentThread().getContextClassLoader();
+        if ("none".equals(stage)) {
+            tester.open();
+        } else {
+            IOException error = Assertions.assertThrows(IOException.class, 
tester::open);
+            if ("queryAndClose".equals(stage)) {
+                Assertions.assertSame(OPERATION_FAILURE, error.getCause());
+                Assertions.assertSame(CLOSE_FAILURE, 
error.getCause().getSuppressed()[0]);
+            }
+        }
+        Assertions.assertSame(original, 
Thread.currentThread().getContextClassLoader());
+        Assertions.assertEquals(cached, 
JdbcDataSource.getDataSource().getSourcesMap());
+        // Hikari may create and retire an initialization probe before the 
actual borrow.
+        Assertions.assertFalse(CONNECTIONS.isEmpty());
+        // Check before Java close: legacy JNI will skip it after a failed 
open.
+        for (Connection connection : CONNECTIONS) {
+            Mockito.verify(connection, Mockito.atLeastOnce()).close();
+        }
+        tester.close();
+        tester.close();
+    }
+
+    public static class TestDriver implements Driver {
+        @Override
+        public Connection connect(String url, Properties info) throws 
SQLException {
+            if (!acceptsURL(url)) {
+                return null;
+            }
+            Connection connection = Mockito.mock(Connection.class);
+            Statement validation = Mockito.mock(Statement.class);
+            PreparedStatement statement = 
Mockito.mock(PreparedStatement.class);
+            ResultSet result = Mockito.mock(ResultSet.class);
+            Mockito.when(connection.getAutoCommit()).thenReturn(true);
+            
Mockito.when(connection.isValid(Mockito.anyInt())).thenReturn(true);
+            
Mockito.when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED);
+            Mockito.when(connection.createStatement()).thenReturn(validation);
+            
Mockito.when(connection.prepareStatement(Mockito.anyString())).thenReturn(statement);
+            Mockito.when(statement.executeQuery()).thenReturn(result);
+            Mockito.when(result.next()).thenReturn(!"empty".equals(failureAt));
+            switch (failureAt) {
+                case "prepare":
+                    
Mockito.when(connection.prepareStatement(Mockito.anyString())).thenThrow(OPERATION_FAILURE);
+                    break;
+                case "query":
+                case "queryAndClose":
+                    
Mockito.when(statement.executeQuery()).thenThrow(OPERATION_FAILURE);
+                    if ("queryAndClose".equals(failureAt)) {
+                        Mockito.doThrow(CLOSE_FAILURE).when(statement).close();
+                    }
+                    break;
+                case "next":
+                    Mockito.when(result.next()).thenThrow(OPERATION_FAILURE);
+                    break;
+                case "resultClose":
+                    Mockito.doThrow(CLOSE_FAILURE).when(result).close();
+                    break;
+                case "statementClose":
+                    Mockito.doThrow(CLOSE_FAILURE).when(statement).close();
+                    break;
+                default:
+                    break;
+            }
+            CONNECTIONS.add(connection);
+            return connection;
+        }
+
+        @Override
+        public boolean acceptsURL(String url) {
+            return url.startsWith("jdbc:tester:");
+        }
+
+        @Override
+        public DriverPropertyInfo[] getPropertyInfo(String url, Properties 
info) {
+            return new DriverPropertyInfo[0];
+        }
+
+        @Override
+        public int getMajorVersion() {
+            return 1;
+        }
+
+        @Override
+        public int getMinorVersion() {
+            return 0;
+        }
+
+        @Override
+        public boolean jdbcCompliant() {
+            return false;
+        }
+
+        @Override
+        public Logger getParentLogger() {
+            return Logger.getGlobal();
+        }
+    }
+}
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcDiagnosticsTest.java
 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcDiagnosticsTest.java
index a47ae247f33..52e69ef327e 100644
--- 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcDiagnosticsTest.java
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcDiagnosticsTest.java
@@ -35,6 +35,7 @@ import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
@@ -151,6 +152,24 @@ class JdbcDiagnosticsTest {
         Connection connection = proxy(Connection.class, (object, method, args) 
-> {
             switch (method.getName()) {
                 case "isClosed": return false;
+                case "setAutoCommit":
+                case "close":
+                    return null;
+                case "createStatement":
+                    return proxy(Statement.class, (statement, operation, 
values) -> {
+                        switch (operation.getName()) {
+                            case "execute": return true;
+                            case "close": return null;
+                            default: throw new 
UnsupportedOperationException(operation.getName());
+                        }
+                    });
+                case "prepareStatement":
+                    return proxy(PreparedStatement.class, (statement, 
operation, values) -> {
+                        if (operation.getName().equals("close")) {
+                            return null;
+                        }
+                        throw new 
UnsupportedOperationException(operation.getName());
+                    });
                 case "commit": throw cause;
                 case "rollback":
                     rollbacks[0]++;
@@ -158,9 +177,24 @@ class JdbcDiagnosticsTest {
                 default: throw new 
UnsupportedOperationException(method.getName());
             }
         });
-        field(writer, "conn", connection);
-        assertDiagnostic(Assertions.assertThrows(IOException.class, 
writer::close), cause, "close");
-        Assertions.assertEquals(1, rollbacks[0]);
+        Method cacheKey = 
JdbcJniWriter.class.getDeclaredMethod("createCacheKey");
+        cacheKey.setAccessible(true);
+        String key = (String) cacheKey.invoke(writer);
+        try (HikariDataSource pool = new HikariDataSource() {
+            @Override
+            public Connection getConnection() {
+                return connection;
+            }
+        }) {
+            JdbcDataSource.getDataSource().putSource(key, pool);
+            try {
+                writer.open();
+                assertDiagnostic(Assertions.assertThrows(IOException.class, 
writer::close), cause, "close");
+                Assertions.assertEquals(1, rollbacks[0]);
+            } finally {
+                JdbcDataSource.getDataSource().getSourcesMap().remove(key, 
pool);
+            }
+        }
     }
 
     private static void assertDiagnostic(IOException error, SQLException 
cause, String operation) {
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcPoolOwnershipTest.java
 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcPoolOwnershipTest.java
new file mode 100644
index 00000000000..7ecd9d03e0c
--- /dev/null
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcPoolOwnershipTest.java
@@ -0,0 +1,664 @@
+// 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.doris.jdbc;
+
+import org.apache.doris.jni.spi.utils.OffHeap;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+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.AtomicLong;
+import javax.sql.DataSource;
+
+class JdbcPoolOwnershipTest {
+    private static final AtomicLong NEXT_ID = new AtomicLong();
+
+    @BeforeEach
+    void enableTestAllocator() {
+        OffHeap.setTesting();
+    }
+
+    @Test
+    void 
concurrentPoolPublicationRetainsOneOwnerAndClosesOnlyUnpublishedCandidate() 
throws Exception {
+        String key = "concurrent-pool-" + NEXT_ID.incrementAndGet();
+        HikariDataSource first = new HikariDataSource();
+        HikariDataSource second = new HikariDataSource();
+        ExecutorService workers = Executors.newFixedThreadPool(2);
+        CountDownLatch ready = new CountDownLatch(2);
+        CountDownLatch publish = new CountDownLatch(1);
+        try {
+            Future<HikariDataSource> firstResult = workers.submit(() -> {
+                ready.countDown();
+                publish.await();
+                return JdbcDataSource.getDataSource().putSourceIfAbsent(key, 
first);
+            });
+            Future<HikariDataSource> secondResult = workers.submit(() -> {
+                ready.countDown();
+                publish.await();
+                return JdbcDataSource.getDataSource().putSourceIfAbsent(key, 
second);
+            });
+            Assertions.assertTrue(ready.await(5, TimeUnit.SECONDS));
+            publish.countDown();
+            HikariDataSource shared = firstResult.get(5, TimeUnit.SECONDS);
+            Assertions.assertSame(shared, secondResult.get(5, 
TimeUnit.SECONDS));
+            Assertions.assertSame(shared, 
JdbcDataSource.getDataSource().getSource(key));
+            Assertions.assertFalse(shared.isClosed());
+            Assertions.assertTrue(first.isClosed() ^ second.isClosed(), "only 
the unpublished pool is closed");
+        } finally {
+            publish.countDown();
+            workers.shutdownNow();
+            Assertions.assertTrue(workers.awaitTermination(5, 
TimeUnit.SECONDS));
+            JdbcDataSource.getDataSource().getSourcesMap().remove(key);
+            first.close();
+            second.close();
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"SQLSERVER,0", "SQLSERVER,1", "MYSQL,0"})
+    void eofReturnsCleanPhysicalConnectionNormally(String type, int rows) 
throws Exception {
+        scanToEof(type, rows);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"SQLSERVER", "MYSQL"})
+    void earlyAbortEvictsOnlyItsBorrow(String type) throws Exception {
+        earlyAbort(type);
+    }
+
+    @Test
+    void realCleanupFailureAtEofIsStillReported() throws Exception {
+        try (PoolFixture fixture = new PoolFixture(1, 1)) {
+            JdbcJniScanner scanner = fixture.scanner("SQLSERVER");
+            try {
+                scanner.open();
+                Assertions.assertEquals(0, scanner.getNextBatchMeta());
+                PhysicalConnection physical = fixture.connections.get(0);
+                physical.resultCloseFailure = new SQLException("result close 
failed", "HY000", 42);
+                IOException error = Assertions.assertThrows(IOException.class, 
scanner::close);
+                Assertions.assertSame(physical.resultCloseFailure, 
error.getCause());
+                Assertions.assertEquals(0, physical.aborts);
+                Assertions.assertEquals(0, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                scanner.close();
+            } finally {
+                scanner.releaseTable();
+            }
+        }
+    }
+
+    @Test
+    void abortFailureStillClosesBorrowedResourcesAndReportsOriginalError() 
throws Exception {
+        try (PoolFixture fixture = new PoolFixture(1, 1)) {
+            JdbcJniScanner scanner = fixture.scanner("SQLSERVER");
+            scanner.open();
+            PhysicalConnection physical = fixture.connections.get(0);
+            physical.abortFailure = new SQLException("abort failed", "HY000", 
43);
+            IOException error = Assertions.assertThrows(IOException.class, 
scanner::close);
+            Assertions.assertSame(physical.abortFailure, error.getCause());
+            Assertions.assertEquals(1, physical.aborts);
+            Assertions.assertEquals(1, physical.resultCloses);
+            Assertions.assertEquals(1, physical.statementCloses);
+            Assertions.assertEquals(0, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+            scanner.close();
+            Assertions.assertEquals(1, physical.aborts);
+        }
+    }
+
+    @Test
+    void timedOutWriterCannotShutdownPoolOrAbortActiveWriter() throws 
Exception {
+        try (PoolFixture fixture = new PoolFixture(1)) {
+            JdbcJniWriter active = fixture.writer();
+            JdbcJniWriter waiting = fixture.writer();
+            active.open();
+            IOException error = Assertions.assertThrows(IOException.class, 
waiting::open);
+            Assertions.assertInstanceOf(SQLException.class, error.getCause());
+            waiting.close();
+            fixture.assertActiveWriterUnaffected(active);
+        }
+    }
+
+    @Test
+    void failedWriterPrepareReleasesOnlyItsConnection() throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            JdbcJniWriter active = fixture.writer();
+            JdbcJniWriter failing = fixture.writer();
+            active.open();
+            fixture.failPrepare = true;
+            IOException error = Assertions.assertThrows(IOException.class, 
failing::open);
+            Assertions.assertSame(fixture.prepareFailure, error.getCause());
+            Assertions.assertEquals(1, fixture.connections.get(1).rollbacks);
+            Assertions.assertEquals(0, fixture.connections.get(1).commits);
+            failing.close();
+            fixture.assertActiveWriterUnaffected(active);
+        }
+    }
+
+    @Test
+    void closingWriterCannotShutdownAnotherActiveWriter() throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            JdbcJniWriter active = fixture.writer();
+            JdbcJniWriter closing = fixture.writer();
+            active.open();
+            closing.open();
+            closing.close();
+            fixture.assertActiveWriterUnaffected(active);
+        }
+    }
+
+    @Test
+    void timedOutScannerCannotShutdownActiveWriterPool() throws Exception {
+        try (PoolFixture fixture = new PoolFixture(1)) {
+            JdbcJniWriter active = fixture.writer();
+            JdbcJniScanner waiting = fixture.scanner("SQLSERVER");
+            active.open();
+            Assertions.assertThrows(IOException.class, waiting::open);
+            waiting.close();
+            fixture.assertActiveWriterUnaffected(active);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"commit", "prepare"})
+    void rollbackFailureNeverRecyclesPhysicalConnection(String stage) throws 
Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            JdbcJniWriter writer = fixture.writer();
+            IOException error;
+            if ("prepare".equals(stage)) {
+                fixture.failPrepare = true;
+                fixture.failRollback = true;
+                error = Assertions.assertThrows(IOException.class, 
writer::open);
+            } else {
+                writer.open();
+                PhysicalConnection physical = fixture.connections.get(0);
+                java.lang.reflect.Field field = 
JdbcJniWriter.class.getDeclaredField("preparedStatement");
+                field.setAccessible(true);
+                ((PreparedStatement) field.get(writer)).executeBatch();
+                physical.commitFailure = fixture.commitFailure;
+                physical.rollbackFailure = fixture.rollbackFailure;
+                error = Assertions.assertThrows(IOException.class, 
writer::close);
+            }
+            PhysicalConnection physical = fixture.connections.get(0);
+            Assertions.assertSame("prepare".equals(stage) ? 
fixture.prepareFailure : fixture.commitFailure,
+                    error.getCause());
+            Assertions.assertSame(fixture.rollbackFailure, 
error.getCause().getSuppressed()[0]);
+            fixture.failPrepare = false;
+            fixture.failRollback = false;
+            fixture.assertCleanReplacement(physical);
+            Assertions.assertEquals("prepare".equals(stage) ? 0 : 1, 
physical.commits);
+        }
+    }
+
+    @Test
+    void writerStatementCloseFailureEvictsOnlyItsBorrow() throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            JdbcJniWriter writer = fixture.writer();
+            writer.open();
+            PhysicalConnection physical = fixture.connections.get(0);
+            physical.statementCloseFailure = fixture.statementCloseFailure;
+            try (Connection other = fixture.pool.getConnection()) {
+                IOException error = Assertions.assertThrows(IOException.class, 
writer::close);
+                Assertions.assertSame(fixture.statementCloseFailure, 
error.getCause());
+                Assertions.assertTrue(other.isValid(1));
+                fixture.assertCleanReplacement(physical);
+                Assertions.assertEquals(1, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"true,autoCommit", "true,warnings", "false,warnings"})
+    void zeroIdleWriterRetiresBorrowBeforeProxyCleanup(boolean transaction, 
String stage) throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            fixture.params.put("use_transaction", String.valueOf(transaction));
+            JdbcJniWriter writer = fixture.writer();
+            writer.open();
+            PhysicalConnection physical = fixture.connections.get(0);
+            physical.proxyCleanupFailureAt = stage;
+            try (Connection other = fixture.pool.getConnection()) {
+                IOException closeFailure = null;
+                try {
+                    writer.close();
+                } catch (IOException e) {
+                    closeFailure = e;
+                }
+                // Check physical identity, not just the pool slot released by 
proxy close.
+                fixture.assertCleanReplacement(physical);
+                Assertions.assertNull(closeFailure, "proxy cleanup of a 
retired entry must not fail the operation");
+                Assertions.assertEquals(transaction ? 1 : 0, physical.commits);
+                Assertions.assertEquals(1, physical.statementCloses);
+                Assertions.assertTrue(other.isValid(1));
+                Assertions.assertEquals(1, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                writer.close();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"MYSQL,autoCommit", "MYSQL,warnings", "SQLSERVER,warnings"})
+    void zeroIdleScannerRetiresBorrowBeforeProxyCleanup(String type, String 
stage) throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            JdbcJniScanner scanner = fixture.scanner(type);
+            try {
+                scanner.open();
+                Assertions.assertEquals(0, scanner.getNextBatchMeta());
+                PhysicalConnection physical = fixture.connections.get(0);
+                physical.proxyCleanupFailureAt = stage;
+                try (Connection other = fixture.pool.getConnection()) {
+                    IOException closeFailure = null;
+                    try {
+                        scanner.close();
+                    } catch (IOException e) {
+                        closeFailure = e;
+                    }
+                    fixture.assertCleanReplacement(physical);
+                    Assertions.assertNull(closeFailure, "proxy cleanup of a 
retired entry must not fail the operation");
+                    Assertions.assertEquals(0, physical.aborts);
+                    Assertions.assertEquals(1, physical.resultCloses);
+                    Assertions.assertEquals(1, physical.statementCloses);
+                    Assertions.assertTrue(other.isValid(1));
+                    Assertions.assertEquals(1, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                    scanner.close();
+                }
+            } finally {
+                scanner.releaseTable();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"POSTGRESQL,statement", "POSTGRESQL,fetch", "MYSQL,fetch",
+            "POSTGRESQL,query", "POSTGRESQL,metadata"})
+    void scannerStatementCloseFailureNeverRecyclesPhysicalConnection(String 
type, String stage) throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2)) {
+            fixture.failureAt = stage;
+            JdbcJniScanner scanner = fixture.scanner(type);
+            try {
+                IOException error;
+                if ("statement".equals(stage)) {
+                    scanner.open();
+                    Assertions.assertEquals(0, scanner.getNextBatchMeta());
+                    fixture.connections.get(0).statementCloseFailure = 
fixture.statementCloseFailure;
+                    error = Assertions.assertThrows(IOException.class, 
scanner::close);
+                } else {
+                    error = Assertions.assertThrows(IOException.class, 
scanner::open);
+                }
+                PhysicalConnection physical = fixture.connections.get(0);
+                Assertions.assertSame("statement".equals(stage) ? 
fixture.statementCloseFailure
+                        : fixture.operationFailure, error.getCause());
+                if (!"statement".equals(stage)) {
+                    Assertions.assertSame(fixture.statementCloseFailure, 
error.getCause().getSuppressed()[0]);
+                }
+                fixture.failureAt = "none";
+                fixture.assertCleanReplacement(physical);
+                scanner.close();
+            } finally {
+                scanner.releaseTable();
+            }
+        }
+    }
+
+    private static void scanToEof(String tableType, int rows) throws Exception 
{
+        try (PoolFixture fixture = new PoolFixture(1, 1)) {
+            fixture.rows = rows;
+            JdbcJniScanner scanner = fixture.scanner(tableType);
+            try {
+                scanner.open();
+                long address = scanner.getNextBatchMeta();
+                Assertions.assertEquals(rows == 0, address == 0);
+                Assertions.assertDoesNotThrow(scanner::close);
+                Assertions.assertDoesNotThrow(scanner::close);
+                Assertions.assertEquals(0, fixture.connections.get(0).aborts);
+                Assertions.assertEquals(0, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                Assertions.assertFalse(fixture.pool.isClosed());
+                try (Connection nextBorrow = fixture.pool.getConnection()) {
+                    Assertions.assertTrue(nextBorrow.isValid(1));
+                    
Assertions.assertSame(fixture.connections.get(0).connection,
+                            nextBorrow.unwrap(Connection.class), "healthy EOF 
should retain normal reuse");
+                }
+            } finally {
+                scanner.releaseTable();
+            }
+        }
+    }
+
+    private static void earlyAbort(String tableType) throws Exception {
+        try (PoolFixture fixture = new PoolFixture(2, 1)) {
+            JdbcJniScanner scanner = fixture.scanner(tableType);
+            scanner.open();
+            PhysicalConnection aborted = fixture.connections.get(0);
+            try (Connection otherBorrow = fixture.pool.getConnection()) {
+                Assertions.assertDoesNotThrow(scanner::close);
+                Assertions.assertDoesNotThrow(scanner::close);
+                Assertions.assertEquals(1, aborted.aborts);
+                Assertions.assertTrue(aborted.closed);
+                Assertions.assertEquals(1, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                Assertions.assertTrue(otherBorrow.isValid(1));
+                try (Connection replacement = fixture.pool.getConnection()) {
+                    Assertions.assertTrue(replacement.isValid(1));
+                    Assertions.assertNotSame(aborted.connection, 
replacement.unwrap(Connection.class));
+                    Assertions.assertEquals(2, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+                }
+            }
+            Assertions.assertEquals(0, 
fixture.pool.getHikariPoolMXBean().getActiveConnections());
+            Assertions.assertFalse(fixture.pool.isClosed());
+        }
+    }
+
+    private static class PoolFixture implements AutoCloseable {
+        private final CopyOnWriteArrayList<PhysicalConnection> connections = 
new CopyOnWriteArrayList<>();
+        private final SQLException prepareFailure = new SQLException("prepare 
failed", "HY000", 44);
+        private final SQLException commitFailure = new SQLException("commit 
failed", "HY000", 45);
+        private final SQLException rollbackFailure = new 
SQLException("rollback failed", "HY000", 46);
+        private final SQLException statementCloseFailure = new 
SQLException("statement close failed", "HY000", 47);
+        private final SQLException operationFailure = new 
SQLException("operation failed", "HY000", 48);
+        private final Map<String, String> params = new HashMap<>();
+        private final HikariDataSource pool;
+        private String cacheKey;
+        private volatile boolean failPrepare;
+        private volatile boolean failRollback;
+        private String failureAt = "none";
+        private int rows;
+
+        private PoolFixture(int maxSize) {
+            this(maxSize, 0);
+        }
+
+        private PoolFixture(int maxSize, int minSize) {
+            params.put("catalog_id", 
String.valueOf(-NEXT_ID.incrementAndGet()));
+            params.put("jdbc_url", "jdbc:fixture:pool-ownership");
+            params.put("jdbc_driver_url", 
"file:///nonexistent/pool-ownership-driver.jar");
+            params.put("connection_pool_min_size", String.valueOf(minSize));
+            params.put("connection_pool_max_size", String.valueOf(maxSize));
+            params.put("connection_pool_max_wait_time", "1000");
+            params.put("query_sql", "select id from ownership_test");
+            params.put("insert_sql", "insert into ownership_test values (?)");
+            params.put("required_fields", "id");
+            params.put("columns_types", "int");
+            params.put("use_transaction", "true");
+            HikariConfig config = new HikariConfig();
+            config.setMinimumIdle(minSize);
+            config.setMaximumPoolSize(maxSize);
+            config.setConnectionTimeout(1000);
+            config.setInitializationFailTimeout(-1);
+            config.setDataSource(proxy(DataSource.class, (object, method, 
args) -> {
+                switch (method.getName()) {
+                    case "getConnection":
+                        PhysicalConnection connection = new 
PhysicalConnection(this);
+                        connections.add(connection);
+                        return connection.connection;
+                    case "getLoginTimeout": return 0;
+                    case "setLoginTimeout": return null;
+                    default: throw new 
UnsupportedOperationException(method.getName());
+                }
+            }));
+            pool = new HikariDataSource(config);
+        }
+
+        private JdbcJniScanner scanner(String tableType) throws Exception {
+            params.put("table_type", tableType);
+            JdbcJniScanner scanner = new JdbcJniScanner(2, params);
+            install(scanner);
+            return scanner;
+        }
+
+        private JdbcJniWriter writer() throws Exception {
+            params.put("table_type", "SQLSERVER");
+            JdbcJniWriter writer = new JdbcJniWriter(2, params);
+            install(writer);
+            return writer;
+        }
+
+        private void install(Object owner) throws Exception {
+            Method keyMethod = 
owner.getClass().getDeclaredMethod("createCacheKey");
+            keyMethod.setAccessible(true);
+            cacheKey = (String) keyMethod.invoke(owner);
+            JdbcDataSource.getDataSource().putSource(cacheKey, pool);
+        }
+
+        private void assertCleanReplacement(PhysicalConnection previous) 
throws Exception {
+            Assertions.assertFalse(pool.isClosed());
+            try (Connection next = pool.getConnection()) {
+                Connection physical = next.unwrap(Connection.class);
+                Assertions.assertNotSame(previous.connection, physical,
+                        "failed cleanup must retire the physical connection, 
not just return the pool slot");
+                Assertions.assertTrue(next.getAutoCommit());
+                PhysicalConnection replacement = connections.stream()
+                        .filter(candidate -> candidate.connection == 
physical).findFirst().orElseThrow();
+                Assertions.assertFalse(replacement.dirty, "uncommitted writes 
must not reach another borrower");
+            }
+        }
+
+        private void assertActiveWriterUnaffected(JdbcJniWriter active) throws 
Exception {
+            Assertions.assertFalse(pool.isClosed(), "a borrower must not shut 
down the shared pool");
+            Assertions.assertSame(pool, 
JdbcDataSource.getDataSource().getSource(cacheKey));
+            Assertions.assertEquals(1, 
pool.getHikariPoolMXBean().getActiveConnections());
+            PhysicalConnection physical = connections.get(0);
+            Assertions.assertFalse(physical.closed);
+            Assertions.assertEquals(0, physical.aborts);
+            active.close();
+            Assertions.assertEquals(1, physical.commits);
+            Assertions.assertEquals(0, 
pool.getHikariPoolMXBean().getActiveConnections());
+        }
+
+        @Override
+        public void close() {
+            if (cacheKey != null) {
+                
JdbcDataSource.getDataSource().getSourcesMap().remove(cacheKey, pool);
+            }
+            pool.close();
+        }
+    }
+
+    // Model physical abort and first-failure proxy cleanup separately. An 
unrecognized reset
+    // error can close the physical connection without Hikari marking its pool 
entry evicted.
+    private static class PhysicalConnection {
+        private PoolFixture fixture;
+        private volatile boolean closed;
+        private boolean autoCommit = true;
+        private int cursor = -1;
+        private int aborts;
+        private int commits;
+        private int rollbacks;
+        private int resultCloses;
+        private int statementCloses;
+        private SQLException resultCloseFailure;
+        private SQLException abortFailure;
+        private SQLException commitFailure;
+        private SQLException rollbackFailure;
+        private SQLException statementCloseFailure;
+        private String proxyCleanupFailureAt = "none";
+        private boolean dirty;
+        private final ResultSetMetaData metadata = 
proxy(ResultSetMetaData.class, (object, method, args) -> {
+            switch (method.getName()) {
+                case "getColumnCount": return 1;
+                case "getColumnLabel": return "id";
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+        private final ResultSet resultSet = proxy(ResultSet.class, (object, 
method, args) -> {
+            switch (method.getName()) {
+                case "getMetaData":
+                    failOperation("metadata");
+                    return metadata;
+                case "next": return ++cursor < fixture.rows;
+                case "getInt":
+                case "getObject":
+                    return 1;
+                case "wasNull": return false;
+                case "isAfterLast": return fixture.rows > 0 && cursor >= 
fixture.rows;
+                case "close":
+                    resultCloses++;
+                    checkOpen();
+                    if (resultCloseFailure != null) {
+                        throw resultCloseFailure;
+                    }
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+        private final PreparedStatement statement = 
proxy(PreparedStatement.class, (object, method, args) -> {
+            switch (method.getName()) {
+                case "setFetchSize":
+                    failOperation("fetch");
+                    return null;
+                case "executeQuery":
+                    failOperation("query");
+                    return resultSet;
+                case "executeBatch":
+                    dirty = true;
+                    return new int[] {1};
+                case "close":
+                    statementCloses++;
+                    checkOpen();
+                    if (statementCloseFailure != null) {
+                        throw statementCloseFailure;
+                    }
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+        private final Connection connection = proxy(Connection.class, (object, 
method, args) -> {
+            switch (method.getName()) {
+                case "prepareStatement":
+                    checkOpen();
+                    if (fixture.failPrepare) {
+                        throw fixture.prepareFailure;
+                    }
+                    return statement;
+                case "createStatement":
+                    return proxy(Statement.class, (statementObject, operation, 
values) -> {
+                        switch (operation.getName()) {
+                            case "execute": return true;
+                            case "close": return null;
+                            default: throw new 
UnsupportedOperationException(operation.getName());
+                        }
+                    });
+                case "abort":
+                    aborts++;
+                    if (abortFailure != null) {
+                        throw abortFailure;
+                    }
+                    closed = true;
+                    return null;
+                case "isClosed": return closed;
+                case "isValid": return !closed;
+                case "close":
+                    closed = true;
+                    return null;
+                case "getAutoCommit": return autoCommit;
+                case "setAutoCommit":
+                    checkOpen();
+                    if ((boolean) args[0]) {
+                        failProxyCleanup("autoCommit");
+                    }
+                    autoCommit = (boolean) args[0];
+                    return null;
+                case "commit":
+                    checkOpen();
+                    commits++;
+                    if (commitFailure != null) {
+                        throw commitFailure;
+                    }
+                    dirty = false;
+                    return null;
+                case "rollback":
+                    checkOpen();
+                    rollbacks++;
+                    if (rollbackFailure != null || fixture.failRollback) {
+                        throw fixture.rollbackFailure;
+                    }
+                    dirty = false;
+                    return null;
+                case "clearWarnings":
+                    checkOpen();
+                    failProxyCleanup("warnings");
+                    return null;
+                case "isReadOnly": return false;
+                case "getTransactionIsolation": return 
Connection.TRANSACTION_READ_COMMITTED;
+                case "getNetworkTimeout": return 0;
+                case "setNetworkTimeout":
+                case "setReadOnly":
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+
+        private PhysicalConnection(PoolFixture fixture) {
+            this.fixture = fixture;
+        }
+
+        private void failOperation(String stage) throws SQLException {
+            if (fixture.failureAt.equals(stage)) {
+                statementCloseFailure = fixture.statementCloseFailure;
+                throw fixture.operationFailure;
+            }
+        }
+
+        private void failProxyCleanup(String stage) throws SQLException {
+            if (proxyCleanupFailureAt.equals(stage)) {
+                closed = true;
+                throw new SQLException("physical connection lost during " + 
stage, "S0001", 40501);
+            }
+        }
+
+        private void checkOpen() throws SQLException {
+            if (closed) {
+                throw new SQLException("physical connection is closed", 
"08006");
+            }
+        }
+    }
+
+    private static <T> T proxy(Class<T> type, InvocationHandler handler) {
+        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new 
Class<?>[] {type},
+                (object, method, args) -> {
+                    if (method.getDeclaringClass() == Object.class) {
+                        switch (method.getName()) {
+                            case "toString": return "pool ownership fixture " 
+ type.getSimpleName();
+                            case "hashCode": return 
System.identityHashCode(object);
+                            case "equals": return object == args[0];
+                            default: throw new 
UnsupportedOperationException(method.getName());
+                        }
+                    }
+                    return handler.invoke(object, method, args);
+                }));
+    }
+}
diff --git 
a/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcResourceCleanupTest.java
 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcResourceCleanupTest.java
new file mode 100644
index 00000000000..356e0097a1f
--- /dev/null
+++ 
b/fe/be-java-extensions/jdbc-scanner/src/test/java/org/apache/doris/jdbc/JdbcResourceCleanupTest.java
@@ -0,0 +1,727 @@
+// 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.doris.jdbc;
+
+import org.apache.doris.jni.spi.utils.JniUtil;
+
+import com.zaxxer.hikari.HikariDataSource;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+class JdbcResourceCleanupTest {
+    private static final AtomicLong NEXT_ID = new AtomicLong();
+
+    @ParameterizedTest
+    @CsvSource({"prepare,false", "query,false", "metadata,false",
+            "prepare,true", "query,true", "metadata,true"})
+    void scannerPartialOpenReleasesBorrowedResources(String stage, boolean 
callerCleanup) throws Exception {
+        scannerOpenFailure(stage, callerCleanup);
+    }
+
+    @Test
+    void writerPrepareFailureReleasesConnectionWithoutCommit() throws 
Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "prepare";
+        Map<String, String> params = params();
+        params.put("use_transaction", "true");
+        JdbcJniWriter writer = new JdbcJniWriter(1, params);
+        String key = installPool(writer, resources);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
writer::open);
+            Assertions.assertAll(
+                    () -> Assertions.assertSame(resources.failure, 
error.getCause()),
+                    () -> Assertions.assertEquals(1, 
resources.connectionCloses, "borrowed connection"),
+                    () -> Assertions.assertEquals(0, resources.commits, 
"failed initialization must not commit"),
+                    () -> Assertions.assertEquals(1, resources.rollbacks));
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void writerAutoCommitSetupFailureOnlyReleasesConnection() throws Exception 
{
+        Resources resources = new Resources();
+        resources.failureAt = "setAutoCommit";
+        Map<String, String> params = params();
+        params.put("use_transaction", "true");
+        JdbcJniWriter writer = new JdbcJniWriter(1, params);
+        String key = installPool(writer, resources);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
writer::open);
+            Assertions.assertSame(resources.failure, error.getCause());
+            writer.close();
+            Assertions.assertEquals(0, resources.commits);
+            Assertions.assertEquals(0, resources.rollbacks);
+            Assertions.assertEquals(1, resources.connectionCloses);
+            Assertions.assertEquals(0, resources.statementCloses);
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void failedWriterOpenRetainsRollbackAndCloseFailuresWithoutCommit() throws 
Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "prepare";
+        resources.failRollback = true;
+        SQLException closeFailure = new SQLException("connection close 
failed", "08006", 7005);
+        resources.extraFailures.put("connection.close", closeFailure);
+        Map<String, String> params = params();
+        params.put("use_transaction", "true");
+        JdbcJniWriter writer = new JdbcJniWriter(1, params);
+        String key = installPool(writer, resources);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
writer::open);
+            Assertions.assertSame(resources.failure, error.getCause());
+            Assertions.assertArrayEquals(new Throwable[] 
{resources.rollbackFailure, closeFailure},
+                    error.getCause().getSuppressed());
+            Assertions.assertEquals(0, resources.commits);
+            Assertions.assertEquals(1, resources.rollbacks);
+            Assertions.assertEquals(1, resources.connectionCloses);
+            resources.extraFailures.clear();
+            writer.close();
+            Assertions.assertEquals(0, resources.commits);
+            Assertions.assertEquals(2, resources.connectionCloses);
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void scannerPermanentConnectionCloseFailureNeverBecomesSuccess() throws 
Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "connection.close";
+        JdbcJniScanner scanner = scannerWithResources(resources);
+        Assertions.assertSame(resources.failure,
+                Assertions.assertThrows(IOException.class, 
scanner::close).getCause());
+        Assertions.assertSame(resources.failure,
+                Assertions.assertThrows(IOException.class, 
scanner::close).getCause());
+        Assertions.assertEquals(2, resources.connectionCloses);
+        Assertions.assertEquals(1, resources.statementCloses);
+        Assertions.assertEquals(1, resources.resultSetCloses);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"resultSet.close", "statement.close", 
"connection.close"})
+    void scannerCleanupFailuresKeepFirstErrorAndContinueClosing(String stage) 
throws Exception {
+        scannerCloseFailure(stage);
+    }
+
+    @Test
+    void writerStatementCloseFailureDoesNotSkipConnection() throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "statement.close";
+        JdbcJniWriter writer = writerWithResources(resources, false);
+        IOException error = Assertions.assertThrows(IOException.class, 
writer::close);
+        Assertions.assertAll(
+                () -> Assertions.assertSame(resources.failure, 
error.getCause()),
+                () -> Assertions.assertEquals(1, resources.statementCloses),
+                () -> Assertions.assertEquals(1, resources.connectionCloses));
+    }
+
+    @Test
+    void writerCommitFailureDoesNotSkipResourceCleanup() throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "commit";
+        JdbcJniWriter writer = writerWithResources(resources, true);
+        IOException error = Assertions.assertThrows(IOException.class, 
writer::close);
+        Assertions.assertAll(
+                () -> Assertions.assertSame(resources.failure, 
error.getCause()),
+                () -> Assertions.assertEquals(1, resources.commits),
+                () -> Assertions.assertEquals(1, resources.rollbacks),
+                () -> Assertions.assertEquals(1, resources.statementCloses),
+                () -> Assertions.assertEquals(1, resources.connectionCloses));
+    }
+
+    @Test
+    void writerRollbackFailureIsAttachedToTheOriginalError() throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "commit";
+        resources.failRollback = true;
+        JdbcJniWriter writer = writerWithResources(resources, true);
+        IOException error = Assertions.assertThrows(IOException.class, 
writer::close);
+        Assertions.assertAll(
+                () -> Assertions.assertSame(resources.failure, 
error.getCause()),
+                () -> Assertions.assertTrue(hasSuppressed(error, 
resources.rollbackFailure),
+                        "rollback failure must remain attached to the returned 
error"),
+                () -> Assertions.assertEquals(1, resources.statementCloses),
+                () -> Assertions.assertEquals(1, resources.connectionCloses));
+    }
+
+    @Test
+    void writerFailedConnectionCloseIsNotReportedAsSuccessOnSecondClose() 
throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "connection.close";
+        JdbcJniWriter writer = writerWithResources(resources, false);
+        IOException first = Assertions.assertThrows(IOException.class, 
writer::close);
+        Assertions.assertSame(resources.failure, first.getCause());
+        Assertions.assertThrows(IOException.class, writer::close,
+                "the previous close failed without closing the connection");
+    }
+
+    @Test
+    void successfulScannerAndWriterCleanupIsAControl() throws Exception {
+        Resources scannerResources = new Resources();
+        JdbcJniScanner scanner = scannerWithResources(scannerResources);
+        scanner.close();
+        Assertions.assertAll(
+                () -> Assertions.assertEquals(1, 
scannerResources.resultSetCloses),
+                () -> Assertions.assertEquals(1, 
scannerResources.statementCloses),
+                () -> Assertions.assertEquals(1, 
scannerResources.connectionCloses));
+        Resources writerResources = new Resources();
+        JdbcJniWriter writer = writerWithResources(writerResources, true);
+        writer.close();
+        Assertions.assertAll(
+                () -> Assertions.assertEquals(1, writerResources.commits),
+                () -> Assertions.assertEquals(1, 
writerResources.statementCloses),
+                () -> Assertions.assertEquals(1, 
writerResources.connectionCloses));
+    }
+
+    @Test
+    void fetchSizeFailureClosesUntransferredStatementAndPreservesErrors() 
throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "fetchSize";
+        RuntimeException closeFailure = new IllegalStateException("statement 
close failed");
+        resources.extraFailures.put("statement.close", closeFailure);
+        SQLException error = Assertions.assertThrows(SQLException.class,
+                () -> JdbcTypeHandlerFactory.create("POSTGRESQL")
+                        .initializeStatement(resources.connection, "select 1", 
17));
+        Assertions.assertSame(resources.failure, error);
+        Assertions.assertArrayEquals(new Throwable[] {closeFailure}, 
error.getSuppressed());
+        Assertions.assertEquals(17, resources.fetchSize);
+        Assertions.assertEquals(1, resources.statementCloses);
+        Assertions.assertEquals(0, resources.connectionCloses);
+        Resources success = new Resources();
+        Assertions.assertSame(success.statement, 
JdbcCleanup.setFetchSizeOrClose(success.statement, 23));
+    }
+
+    @Test
+    void mysqlStreamingFetchSizeRemainsUnchanged() throws Exception {
+        Resources resources = new Resources();
+        Assertions.assertSame(resources.statement,
+                JdbcTypeHandlerFactory.create("MYSQL")
+                        .initializeStatement(resources.connection, "select 1", 
17));
+        Assertions.assertEquals(Integer.MIN_VALUE, resources.fetchSize);
+        Assertions.assertEquals(0, resources.statementCloses);
+    }
+
+    @Test
+    void mysqlFetchSizeFailureClosesStatementBeforeOwnershipTransfer() throws 
Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "fetchSize";
+        SQLException error = Assertions.assertThrows(SQLException.class,
+                () -> JdbcTypeHandlerFactory.create("MYSQL")
+                        .initializeStatement(resources.connection, "select 1", 
17));
+        Assertions.assertSame(resources.failure, error);
+        Assertions.assertEquals(Integer.MIN_VALUE, resources.fetchSize);
+        Assertions.assertEquals(1, resources.statementCloses);
+    }
+
+    @Test
+    void openAndCleanupFailuresKeepPrimaryOrderAndRedactedJniDiagnostics() 
throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "metadata";
+        SQLException statementFailure = new SQLException("pwd=cleanup-secret", 
"HY001", 7003);
+        SQLException connectionFailure = new 
SQLException("jdbc:postgresql://hidden/db", "08006", 7004);
+        resources.extraFailures.put("statement.close", statementFailure);
+        resources.extraFailures.put("connection.close", connectionFailure);
+        JdbcJniScanner scanner = new JdbcJniScanner(1, params());
+        String key = installPool(scanner, resources);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
scanner::open);
+            Assertions.assertSame(resources.failure, error.getCause());
+            Assertions.assertArrayEquals(new Throwable[] {statementFailure, 
connectionFailure},
+                    error.getCause().getSuppressed());
+            Assertions.assertEquals(Arrays.asList("prepare", "fetchSize", 
"query", "metadata", "resultSet.close",
+                    "statement.close", "connection.close"), resources.events);
+            String message = JniUtil.throwableToString(error);
+            
Assertions.assertTrue(message.contains("remote_vendor_error_code=7001"));
+            
Assertions.assertTrue(message.contains("remote_vendor_error_code=7003"));
+            Assertions.assertTrue(message.contains("remote_sqlstate=08006"));
+            Assertions.assertFalse(message.contains("cleanup-secret"));
+            Assertions.assertFalse(message.contains("hidden/db"));
+            resources.failureAt = "none";
+            resources.extraFailures.clear();
+            scanner.close();
+            scanner.close();
+            Assertions.assertEquals(2, resources.connectionCloses);
+            Assertions.assertEquals(1, resources.resultSetCloses);
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void streamingAbortFailureDoesNotSkipCleanupOrRepeatAbort() throws 
Exception {
+        for (String tableType : Arrays.asList("MYSQL", "SQLSERVER")) {
+            Resources resources = new Resources();
+            resources.failureAt = "abort";
+            resources.extraFailures.put("connection.close", new 
SQLException("close failed"));
+            Map<String, String> params = params();
+            params.put("table_type", tableType);
+            JdbcJniScanner scanner = new JdbcJniScanner(1, params);
+            field(scanner, "hikariDataSource", resourcePool(resources));
+            field(scanner, "conn", resources.connection);
+            field(scanner, "stmt", resources.statement);
+            field(scanner, "resultSet", resources.resultSet);
+            IOException error = Assertions.assertThrows(IOException.class, 
scanner::close);
+            Assertions.assertSame(resources.failure, error.getCause());
+            Assertions.assertEquals(1, resources.aborts);
+            Assertions.assertEquals(1, resources.resultSetCloses);
+            Assertions.assertEquals(1, resources.statementCloses);
+            resources.failureAt = "none";
+            resources.extraFailures.clear();
+            scanner.close();
+            scanner.close();
+            Assertions.assertEquals(1, resources.aborts);
+            Assertions.assertEquals(2, resources.connectionCloses);
+        }
+    }
+
+    @Test
+    void streamingAbortStateBelongsToEachBorrowedConnection() throws Exception 
{
+        Resources resources = new Resources();
+        Map<String, String> params = params();
+        params.put("table_type", "MYSQL");
+        JdbcJniScanner scanner = new JdbcJniScanner(1, params);
+        String key = installPool(scanner, resources);
+        try {
+            scanner.open();
+            scanner.close();
+            scanner.open();
+            scanner.close();
+            Assertions.assertEquals(2, resources.aborts);
+            Assertions.assertEquals(2, resources.connectionCloses);
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void committedWriterDoesNotRollbackOrFinalizeAgainAfterCloseFailure() 
throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "statement.close";
+        JdbcJniWriter writer = writerWithResources(resources, true);
+        IOException first = Assertions.assertThrows(IOException.class, 
writer::close);
+        Assertions.assertSame(resources.failure, first.getCause());
+        writer.close();
+        Assertions.assertEquals(1, resources.commits);
+        Assertions.assertEquals(0, resources.rollbacks);
+        Assertions.assertEquals(1, resources.statementCloses);
+        Assertions.assertEquals(1, resources.connectionCloses);
+    }
+
+    @Test
+    void zeroMinimumSharedPoolRemainsOpenAfterBorrowedResourceFailure() throws 
Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "prepare";
+        int[] poolCloses = {0};
+        Map<String, String> params = params();
+        params.put("connection_pool_min_size", "0");
+        JdbcJniScanner scanner = new JdbcJniScanner(1, params);
+        Method method = scanner.getClass().getDeclaredMethod("createCacheKey");
+        method.setAccessible(true);
+        String key = (String) method.invoke(scanner);
+        HikariDataSource pool = new HikariDataSource() {
+            @Override
+            public Connection getConnection() {
+                return resources.connection;
+            }
+
+            @Override
+            public void evictConnection(Connection connection) {
+                resources.evictions++;
+            }
+
+            @Override
+            public void close() {
+                poolCloses[0]++;
+                super.close();
+            }
+        };
+        JdbcDataSource.getDataSource().putSource(key, pool);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
scanner::open);
+            Assertions.assertSame(resources.failure, error.getCause());
+            Assertions.assertEquals(0, 
error.getCause().getSuppressed().length);
+            Assertions.assertEquals(1, resources.evictions);
+            Assertions.assertEquals(0, resources.connectionCloses, "eviction 
already ended the borrow");
+            scanner.close();
+            Assertions.assertEquals(0, poolCloses[0]);
+            Assertions.assertSame(pool, 
JdbcDataSource.getDataSource().getSource(key));
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @Test
+    void writerDoesNotCloseSharedPoolAfterCleanupFailure() throws Exception {
+        Resources resources = new Resources();
+        Map<String, String> params = params();
+        params.put("connection_pool_min_size", "0");
+        params.put("use_transaction", "true");
+        JdbcJniWriter writer = new JdbcJniWriter(1, params);
+        Method method = writer.getClass().getDeclaredMethod("createCacheKey");
+        method.setAccessible(true);
+        String key = (String) method.invoke(writer);
+        int[] poolCloses = {0};
+        HikariDataSource pool = new HikariDataSource() {
+            @Override
+            public Connection getConnection() {
+                return resources.connection;
+            }
+
+            @Override
+            public void evictConnection(Connection connection) {
+                resources.evictions++;
+            }
+
+            @Override
+            public void close() {
+                poolCloses[0]++;
+                super.close();
+            }
+        };
+        JdbcDataSource.getDataSource().putSource(key, pool);
+        try {
+            writer.open();
+            resources.failureAt = "statement.close";
+            IOException error = Assertions.assertThrows(IOException.class, 
writer::close);
+            Assertions.assertSame(resources.failure, error.getCause());
+            Assertions.assertEquals(0, 
error.getCause().getSuppressed().length);
+            writer.close();
+            Assertions.assertEquals(0, poolCloses[0]);
+            Assertions.assertSame(pool, 
JdbcDataSource.getDataSource().getSource(key));
+            Assertions.assertEquals(1, resources.commits);
+            Assertions.assertEquals(0, resources.rollbacks);
+            Assertions.assertEquals(1, resources.evictions);
+            Assertions.assertEquals(0, resources.connectionCloses, "eviction 
already ended the borrow");
+        } finally {
+            removePool(key);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void failedEvictionDoesNotFallThroughToNormalReturn(boolean writerPath) 
throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = "statement.close";
+        Object target;
+        JdbcCleanup.Action close;
+        if (writerPath) {
+            JdbcJniWriter writer = writerWithResources(resources, true);
+            target = writer;
+            close = writer::close;
+        } else {
+            JdbcJniScanner scanner = scannerWithResources(resources);
+            target = scanner;
+            close = scanner::close;
+        }
+        RuntimeException evictionFailure = new IllegalStateException("eviction 
failed");
+        int[] evictions = {0};
+        field(target, "hikariDataSource", new HikariDataSource() {
+            @Override
+            public void evictConnection(Connection connection) {
+                if (evictions[0]++ == 0) {
+                    throw evictionFailure;
+                }
+            }
+        });
+        IOException error = Assertions.assertThrows(IOException.class, 
close::run);
+        Assertions.assertSame(resources.failure, error.getCause());
+        Assertions.assertArrayEquals(new Throwable[] {evictionFailure}, 
error.getCause().getSuppressed());
+        Assertions.assertEquals(0, resources.connectionCloses, "failed 
eviction must not recycle the borrow");
+        resources.failureAt = "none";
+        close.run();
+        Assertions.assertEquals(2, evictions[0]);
+        Assertions.assertEquals(1, resources.connectionCloses);
+        Assertions.assertEquals(writerPath ? 1 : 0, resources.commits, "retry 
must not commit twice");
+    }
+
+    private static void scannerOpenFailure(String failureAt, boolean 
callerCleanup) throws Exception {
+        Resources resources = new Resources();
+        resources.failureAt = failureAt;
+        JdbcJniScanner scanner = new JdbcJniScanner(1, params());
+        String key = installPool(scanner, resources);
+        try {
+            IOException error = Assertions.assertThrows(IOException.class, 
scanner::open);
+            if (callerCleanup) {
+                scanner.close();
+            }
+            Assertions.assertAll(
+                    () -> Assertions.assertSame(resources.failure, 
error.getCause()),
+                    () -> Assertions.assertEquals(1, 
resources.connectionCloses, "borrowed connection"),
+                    () -> Assertions.assertEquals("prepare".equals(failureAt) 
? 0 : 1,
+                            resources.statementCloses, "acquired statement"),
+                    () -> Assertions.assertEquals("metadata".equals(failureAt) 
? 1 : 0,
+                            resources.resultSetCloses, "acquired result set"));
+        } finally {
+            scanner.close();
+            removePool(key);
+        }
+    }
+
+    private static void scannerCloseFailure(String failureAt) throws Exception 
{
+        Resources resources = new Resources();
+        resources.failureAt = failureAt;
+        JdbcJniScanner scanner = scannerWithResources(resources);
+        IOException error = null;
+        try {
+            scanner.close();
+        } catch (IOException e) {
+            error = e;
+        }
+        IOException observed = error;
+        Assertions.assertAll(
+                () -> Assertions.assertNotNull(observed, "close failure must 
be reported"),
+                () -> Assertions.assertSame(resources.failure, observed == 
null ? null : observed.getCause()),
+                () -> Assertions.assertEquals(1, resources.resultSetCloses),
+                () -> Assertions.assertEquals(1, resources.statementCloses),
+                () -> Assertions.assertEquals(1, resources.connectionCloses));
+    }
+
+    private static JdbcJniScanner scannerWithResources(Resources resources) 
throws Exception {
+        JdbcJniScanner scanner = new JdbcJniScanner(1, params());
+        field(scanner, "hikariDataSource", resourcePool(resources));
+        field(scanner, "conn", resources.connection);
+        field(scanner, "stmt", resources.statement);
+        field(scanner, "resultSet", resources.resultSet);
+        return scanner;
+    }
+
+    private static JdbcJniWriter writerWithResources(Resources resources, 
boolean transaction) throws Exception {
+        Map<String, String> params = params();
+        params.put("use_transaction", String.valueOf(transaction));
+        JdbcJniWriter writer = new JdbcJniWriter(1, params);
+        String failureAt = resources.failureAt;
+        resources.failureAt = "none";
+        String key = installPool(writer, resources);
+        try {
+            writer.open();
+        } finally {
+            resources.failureAt = failureAt;
+            removePool(key);
+        }
+        return writer;
+    }
+
+    private static Map<String, String> params() {
+        Map<String, String> params = new HashMap<>();
+        params.put("catalog_id", String.valueOf(NEXT_ID.incrementAndGet()));
+        params.put("jdbc_url", "jdbc:postgresql://localhost/cleanup");
+        params.put("table_type", "POSTGRESQL");
+        params.put("jdbc_driver_url", 
"file:///nonexistent/cleanup-driver.jar");
+        params.put("connection_pool_min_size", "1");
+        params.put("query_sql", "select 1");
+        params.put("insert_sql", "insert into cleanup_test values (?)");
+        return params;
+    }
+
+    private static String installPool(Object target, Resources resources) 
throws Exception {
+        Method method = target.getClass().getDeclaredMethod("createCacheKey");
+        method.setAccessible(true);
+        String key = (String) method.invoke(target);
+        JdbcDataSource.getDataSource().putSource(key, new HikariDataSource() {
+            @Override
+            public Connection getConnection() {
+                return resources.connection;
+            }
+
+            @Override
+            public void evictConnection(Connection connection) {
+                resources.evictions++;
+            }
+        });
+        return key;
+    }
+
+    private static HikariDataSource resourcePool(Resources resources) {
+        return new HikariDataSource() {
+            @Override
+            public void evictConnection(Connection connection) {
+                resources.evictions++;
+            }
+        };
+    }
+
+    private static void removePool(String key) {
+        HikariDataSource pool = 
JdbcDataSource.getDataSource().getSourcesMap().remove(key);
+        pool.close();
+    }
+
+    private static void field(Object target, String name, Object value) throws 
Exception {
+        Field field = target.getClass().getDeclaredField(name);
+        field.setAccessible(true);
+        field.set(target, value);
+    }
+
+    private static boolean hasSuppressed(Throwable error, Throwable expected) {
+        for (Throwable current = error; current != null; current = 
current.getCause()) {
+            for (Throwable suppressed : current.getSuppressed()) {
+                if (suppressed == expected) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    private static <T> T proxy(Class<T> type, InvocationHandler handler) {
+        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new 
Class<?>[] {type},
+                (object, method, args) -> {
+                    if (method.getDeclaringClass() == Object.class) {
+                        switch (method.getName()) {
+                            case "toString": return "cleanup fixture " + 
type.getSimpleName();
+                            case "hashCode": return 
System.identityHashCode(object);
+                            case "equals": return object == args[0];
+                            default: throw new 
UnsupportedOperationException(method.getName());
+                        }
+                    }
+                    return handler.invoke(object, method, args);
+                }));
+    }
+
+    private static class Resources {
+        private final SQLException failure = new SQLException("injected 
cleanup failure", "HY000", 7001);
+        private final SQLException rollbackFailure = new 
SQLException("injected rollback failure", "HY000", 7002);
+        private String failureAt = "none";
+        private final Map<String, Exception> extraFailures = new HashMap<>();
+        private final List<String> events = new ArrayList<>();
+        private int evictions;
+        private int aborts;
+        private int fetchSize;
+        private boolean failRollback;
+        private int resultSetCloses;
+        private int statementCloses;
+        private int connectionCloses;
+        private int commits;
+        private int rollbacks;
+        private final ResultSetMetaData metadata = 
proxy(ResultSetMetaData.class,
+                (object, method, args) -> 0);
+        private final ResultSet resultSet = proxy(ResultSet.class, (object, 
method, args) -> {
+            switch (method.getName()) {
+                case "getMetaData":
+                    fail("metadata");
+                    return metadata;
+                case "isAfterLast": return false;
+                case "isClosed": return false;
+                case "close":
+                    resultSetCloses++;
+                    fail("resultSet.close");
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+        private final PreparedStatement statement = 
proxy(PreparedStatement.class, (object, method, args) -> {
+            switch (method.getName()) {
+                case "setFetchSize":
+                    fetchSize = (int) args[0];
+                    fail("fetchSize");
+                    return null;
+                case "executeQuery":
+                    fail("query");
+                    return resultSet;
+                case "isClosed": return false;
+                case "close":
+                    statementCloses++;
+                    fail("statement.close");
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+        private final Connection connection = proxy(Connection.class, (object, 
method, args) -> {
+            switch (method.getName()) {
+                case "createStatement":
+                    return proxy(Statement.class, (statementObject, operation, 
values) -> {
+                        switch (operation.getName()) {
+                            case "execute": return true;
+                            case "close": return null;
+                            default: throw new 
UnsupportedOperationException(operation.getName());
+                        }
+                    });
+                case "prepareStatement":
+                    fail("prepare");
+                    return statement;
+                case "abort":
+                    aborts++;
+                    fail("abort");
+                    return null;
+                case "getAutoCommit": return true;
+                case "isReadOnly": return false;
+                case "isValid": return true;
+                case "getTransactionIsolation": return 
Connection.TRANSACTION_READ_COMMITTED;
+                case "getNetworkTimeout": return 0;
+                case "setNetworkTimeout":
+                case "setReadOnly":
+                case "clearWarnings":
+                    return null;
+                case "setAutoCommit":
+                    fail("setAutoCommit");
+                    return null;
+                case "isClosed": return false;
+                case "commit":
+                    commits++;
+                    fail("commit");
+                    return null;
+                case "rollback":
+                    rollbacks++;
+                    if (failRollback) {
+                        throw rollbackFailure;
+                    }
+                    return null;
+                case "close":
+                    connectionCloses++;
+                    fail("connection.close");
+                    return null;
+                default: throw new 
UnsupportedOperationException(method.getName());
+            }
+        });
+
+        private void fail(String location) throws Exception {
+            events.add(location);
+            if (extraFailures.containsKey(location)) {
+                throw extraFailures.get(location);
+            }
+            if (location.equals(failureAt)) {
+                throw failure;
+            }
+        }
+
+    }
+}
diff --git 
a/fe/be-java-extensions/plugin-toolkit/src/main/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtils.java
 
b/fe/be-java-extensions/plugin-toolkit/src/main/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtils.java
index 32e98c78147..7a3a23d1503 100644
--- 
a/fe/be-java-extensions/plugin-toolkit/src/main/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtils.java
+++ 
b/fe/be-java-extensions/plugin-toolkit/src/main/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtils.java
@@ -49,8 +49,9 @@ public final class JdbcExceptionUtils {
     }
 
     /**
-     * Collects both JDBC chains, with identity-based cycle detection. 
Identical diagnostics are
-     * emitted once, but errors with the same message and different remote 
codes stay distinct.
+     * Collects JDBC chains and suppressed cleanup failures, with 
identity-based cycle detection.
+     * Identical diagnostics are emitted once, but errors with the same 
message and different
+     * remote codes stay distinct.
      * Non-SQL exceptions retain their messages without inventing remote error 
codes.
      */
     public static String format(String context, Throwable error, String... 
sensitiveValues) {
@@ -96,6 +97,7 @@ public final class JdbcExceptionUtils {
             if (current.getCause() != null) {
                 pending.addLast(current.getCause());
             }
+            Collections.addAll(pending, current.getSuppressed());
         }
         messages.removeAll(sqlMessages);
         String safeContext = redact(context, sensitiveValues);
diff --git 
a/fe/be-java-extensions/plugin-toolkit/src/test/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtilsTest.java
 
b/fe/be-java-extensions/plugin-toolkit/src/test/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtilsTest.java
index 64290b3252c..267d3895547 100644
--- 
a/fe/be-java-extensions/plugin-toolkit/src/test/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtilsTest.java
+++ 
b/fe/be-java-extensions/plugin-toolkit/src/test/java/org/apache/doris/jni/toolkit/jdbc/JdbcExceptionUtilsTest.java
@@ -26,6 +26,22 @@ import java.sql.SQLException;
 import java.time.Duration;
 
 class JdbcExceptionUtilsTest {
+    @Test
+    void suppressedCleanupDiagnosticsAreOrderedRedactedAndCycleSafe() {
+        SQLException primary = new SQLException("query failed", "42000", 1001);
+        SQLException cleanup = new SQLException("pwd=cleanup-secret 
jdbc:mysql://hidden/db", "08006", 1002);
+        primary.addSuppressed(cleanup);
+        cleanup.addSuppressed(primary);
+        String diagnostic = 
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(2),
+                () -> JdbcExceptionUtils.format("open", primary));
+        
Assertions.assertTrue(diagnostic.indexOf("remote_vendor_error_code=1001")
+                < diagnostic.indexOf("remote_vendor_error_code=1002"));
+        
Assertions.assertEquals(diagnostic.indexOf("remote_vendor_error_code=1002"),
+                diagnostic.lastIndexOf("remote_vendor_error_code=1002"));
+        Assertions.assertFalse(diagnostic.contains("cleanup-secret"));
+        Assertions.assertFalse(diagnostic.contains("hidden/db"));
+    }
+
     @Test
     void reportsRemoteCodesSeparatelyFromTheOperationContext() {
         SQLException cause = new SQLException("bad syntax", "42000", 1064);


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to