From debf5d0083288f480ee5ea49d7a8f72b26c10c65 Mon Sep 17 00:00:00 2001 From: Stacey Levine Date: Fri, 20 Nov 2026 15:18:31 -0500 Subject: [PATCH 1/3] fix(mssql): never let a timeout cancel reach a reused connection The timer that cancels a query at its deadline could start the cancel just before the query ended. Stopping the timer could not stop that cancel, so the connection could go back to the pool and the late cancel could stop the next query on it. - The cancel and its stop now share a lock. A cancel that has not started never runs after the stop, and the stop waits up to 5 seconds for one that is running. - When a cancel ran, may still be running, or the query passed its deadline, the connection is removed from the pool and closed instead of reused. It is removed before its statements are closed. Co-Authored-By: Claude Opus 5.5 --- .../com/external/plugins/MssqlPlugin.java | 23 ++- .../plugins/utils/MssqlExecuteUtils.java | 151 ++++++++++++-- .../plugins/MssqlDriverBehaviourTest.java | 69 ++++++- .../plugins/utils/MssqlExecuteUtilsTest.java | 190 +++++++++++++++++- 4 files changed, 403 insertions(+), 30 deletions(-) diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index 1f2f5a4cac0..91d95722e4b 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -69,7 +69,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; @@ -278,7 +277,7 @@ public Mono executeCommon( final int timeoutMillis = actionConfiguration.getTimeoutInMillisecond(); final int queryTimeoutSeconds = MssqlExecuteUtils.queryTimeoutSeconds(timeoutMillis); final long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis); - ScheduledFuture cancelAtDeadline = null; + MssqlExecuteUtils.DeadlineCancel cancelAtDeadline = null; try { if (FALSE.equals(preparedStatement)) { @@ -332,18 +331,26 @@ public Mono executeCommon( "SQLSTATE: " + e.getSQLState())); } finally { - // Stop the timer before the connection goes back to the pool, so that it never cancels - // a statement on a connection another query is using. - if (cancelAtDeadline != null) { - cancelAtDeadline.cancel(false); - } + // Stop the cancel before the connection goes back to the pool, so that it never cancels + // a query that another action runs on the same connection. The connection is removed + // from the pool instead when: + // - the timer's cancel ran, or may still be on its way; + // - the deadline passed, because this thread may then have cancelled the query itself. + boolean cancelStopped = cancelAtDeadline == null || cancelAtDeadline.stop(); + boolean reusable = cancelStopped && !MssqlExecuteUtils.isPastDeadline(deadlineNanos); // Log HikariCP status logHikariCPStatus( MessageFormat.format("After executing Mssql query [{0}]", query), hikariDSConnection); - closeConnectionPostExecution(resultSet, statement, preparedQuery, sqlConnectionFromPool); + closeConnectionPostExecution( + resultSet, + statement, + preparedQuery, + sqlConnectionFromPool, + hikariDSConnection, + reusable); } ActionExecutionResult result = new ActionExecutionResult(); diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java index 66e29e1f573..d6360148032 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -1,6 +1,8 @@ package com.external.plugins.utils; import com.external.plugins.exceptions.MssqlErrorMessages; +import com.zaxxer.hikari.HikariDataSource; +import lombok.extern.slf4j.Slf4j; import microsoft.sql.DateTimeOffset; import org.apache.commons.lang3.ObjectUtils; @@ -23,11 +25,13 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; import static java.lang.Boolean.FALSE; +@Slf4j public class MssqlExecuteUtils { // 0x followed by upper-case hex digits, the way SQL Server shows binary values. @@ -80,6 +84,50 @@ public static void closeConnectionPostExecution( Thread.currentThread().getName())); } + /** + * Like {@link #closeConnectionPostExecution}, but when {@code reusable} is false, the connection is removed from the + * pool and closed instead of going back to it. A cancel sent to SQL Server for this connection may still be on its + * way, and must not stop the next query that would use it. + */ + public static void closeConnectionPostExecution( + ResultSet resultSet, + Statement statement, + PreparedStatement preparedQuery, + Connection connectionFromPool, + HikariDataSource pool, + boolean reusable) { + if (reusable || connectionFromPool == null) { + closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); + return; + } + if (pool == null || pool.isClosed()) { + // Nothing to remove it from. A closed pool aborts its connections anyway. + log.warn("A Mssql connection that a cancel may still reach was closed without removing it from a pool."); + closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); + return; + } + log.info( + "Removing a Mssql connection from pool {}: a cancel at the query's timeout ran or may still be sent.", + pool.getPoolName()); + try { + // Removed first, while the connection is still open, so Hikari closes it at once and never lends it again. + // Closing the statements afterwards cannot then wait on a server that stopped answering. + pool.evictConnection(connectionFromPool); + } catch (RuntimeException e) { + log.warn("Could not remove a Mssql connection from the pool after a query cancel.", e); + // Close the connection to SQL Server first. The pool may still lend it again, but a late cancel then + // has no session to reach, and the next borrower gets a connection error instead. + try { + connectionFromPool.unwrap(Connection.class).close(); + } catch (SQLException closeError) { + log.warn("Could not close a Mssql connection after a query cancel.", closeError); + } + closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); + return; + } + closeConnectionPostExecution(resultSet, statement, preparedQuery, null); + } + public static void populateRowsAndColumns( List> rowsList, List columnsList, @@ -184,25 +232,98 @@ public static boolean isPastDeadline(long deadlineNanos) { * timeout no longer runs once the first response has arrived. The checks between reads cannot interrupt such a * read. Cancelling ends it with an error. * - *

The caller must cancel the returned task before it closes the statement and returns the connection to the - * pool. + *

The caller must call {@link DeadlineCancel#stop()} before it closes the statement, and must not return the + * connection to the pool when {@code stop()} returns false. */ - public static ScheduledFuture cancelAtDeadline(Statement statement, long deadlineNanos) { + public static DeadlineCancel cancelAtDeadline(Statement statement, long deadlineNanos) { + DeadlineCancel cancel = new DeadlineCancel(statement); long delayNanos = Math.max(0, deadlineNanos - System.nanoTime()); // The timer thread only starts the cancel. Sending it to a stalled server can block, and that must not // delay the cancels of other queries. - return CANCEL_TIMER.schedule( - () -> CANCEL_THREADS.start(() -> { - try { - if (!statement.isClosed()) { - statement.cancel(); - } - } catch (SQLException e) { - // The statement finished or was closed meanwhile. Nothing is left to cancel. - } - }), - delayNanos, - TimeUnit.NANOSECONDS); + cancel.timer = CANCEL_TIMER.schedule(() -> CANCEL_THREADS.start(cancel::run), delayNanos, TimeUnit.NANOSECONDS); + return cancel; + } + + /** + * The cancel of one query at its deadline. + * + *

Stopping the timer cannot stop a cancel that has already started on its own thread. Without more, that cancel + * could reach SQL Server after the connection went back to the pool, and stop another query on the same + * connection. So the cancel and {@link #stop()} share a lock: + * + *

    + *
  • A cancel that has not started yet never runs after {@code stop()}. + *
  • {@code stop()} waits for a cancel that is running, up to {@link #STOP_WAIT_MILLIS}. + *
  • When a cancel has run, or is still running after that wait, {@code stop()} returns false. The connection + * must then be removed from the pool, not reused. + *
+ */ + public static final class DeadlineCancel { + + /** How long {@link #stop()} waits for a running cancel before giving up on the connection. */ + static final long STOP_WAIT_MILLIS = 5_000; + + private final Statement statement; + private final ReentrantLock lock = new ReentrantLock(); + private ScheduledFuture timer; + // Set before stop() waits for the lock, so a cancel that has not started yet never starts, even when stop() + // gives up waiting or is interrupted. + private volatile boolean stopped; + // Read and written only while holding the lock. + private boolean started; + + private DeadlineCancel(Statement statement) { + this.statement = statement; + } + + private void run() { + lock.lock(); + try { + if (stopped || statement.isClosed()) { + return; + } + started = true; + statement.cancel(); + } catch (SQLException e) { + // The statement finished or was closed meanwhile. Nothing is left to cancel. + } finally { + lock.unlock(); + } + } + + /** The lock that the cancel and {@link #stop()} share. For tests. */ + ReentrantLock lockForTests() { + return lock; + } + + /** + * Stops the cancel. After this returns, no cancel for this query starts. + * + * @return true when no cancel ran, so the connection can go back to the pool. False when a cancel ran or may + * still be running: the connection must be removed from the pool. + */ + public boolean stop() { + stopped = true; + if (timer != null) { + timer.cancel(false); + } + boolean locked; + try { + locked = lock.tryLock(STOP_WAIT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + locked = false; + } + if (!locked) { + // A cancel is still sending. It may reach SQL Server later. + return false; + } + try { + return !started; + } finally { + lock.unlock(); + } + } } /** diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java index 972e58843c0..6736d303a9a 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java @@ -527,6 +527,53 @@ private static Stream endlessLaterResults() { "ran longer than its timeout of 3000 ms"))); } + // AIP-FD-39: the cancel sent at the deadline can reach SQL Server late. So the connection of a query that was + // cancelled must be removed from the pool and closed, never lent to another query. The query records its own + // session, and the test checks on SQL Server that this session ends. + @ParameterizedTest(name = "prepared statement {0}") + @ValueSource(booleans = {true, false}) + void should_closeTheConnection_when_theQueryIsCancelledAtItsTimeout(boolean preparedStatement) { + // Given + run( + "IF OBJECT_ID('driver_cancelled_sessions') IS NULL" + + " CREATE TABLE driver_cancelled_sessions (spid int, login_time datetime);" + + " DELETE FROM driver_cancelled_sessions", + false); + ActionConfiguration actionConfiguration = new ActionConfiguration(); + // The wait happens inside a read of the later results, so only the timer's cancel can end it. + actionConfiguration.setBody("INSERT INTO driver_cancelled_sessions" + + " SELECT session_id, login_time FROM sys.dm_exec_sessions WHERE session_id = @@SPID;" + + " RAISERROR('flush', 0, 1) WITH NOWAIT; WAITFOR DELAY '00:00:20'"); + actionConfiguration.setTimeoutInMillisecond("3000"); + actionConfiguration.setPluginSpecifiedTemplates( + List.of(new Property("preparedStatement", String.valueOf(preparedStatement)))); + + // When + StepVerifier.create(mssqlPluginExecutor.executeParameterized( + pool, new ExecuteActionDTO(), createDatasourceConfiguration(container), actionConfiguration)) + .assertNext(result -> assertThat(result.getIsExecutionSuccess()).isFalse()) + .expectComplete() + .verify(Duration.ofSeconds(30)); + + // Then + assertThat(firstValue(run("SELECT COUNT(*) AS n FROM driver_cancelled_sessions", false), "n")) + .as("the cancelled query recorded its session") + .isEqualTo(1); + await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> assertThat(firstValue( + run( + "SELECT COUNT(*) AS n FROM sys.dm_exec_sessions s" + + " JOIN driver_cancelled_sessions c" + + " ON s.session_id = c.spid AND s.login_time = c.login_time", + false), + "n")) + .as("sessions of the cancelled query still open on SQL Server") + .isZero()); + } + + private static int firstValue(ActionExecutionResult result, String column) { + return ((ArrayNode) result.getBody()).get(0).get(column).asInt(); + } + // AIP-FD-38: a query that runs past its timeout must not hold a pooled connection and a worker thread. The // reactive timeout cannot interrupt the blocking JDBC call, so before the fix such a query ran on: the endless // ones forever, because the plugin reads the later results to find errors (APP-16536). @@ -562,11 +609,31 @@ void should_failAndFreeTheConnection_when_theQueryRunsPastItsTimeout( .verify(Duration.ofSeconds(30)); assertThat(took).isLessThan(Duration.ofSeconds(10)); - // The connection goes back to the pool shortly after the timeout. + // The connection goes back to the pool, or is removed from it, shortly after the timeout. await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertThat( connectionPool.getHikariPoolMXBean().getActiveConnections()) .as("connections the query still holds after its timeout") .isZero()); + + // AIP-FD-39: the cancel sent at the deadline must not stop the next query on the pool. + ActionConfiguration nextQuery = new ActionConfiguration(); + nextQuery.setBody("WAITFOR DELAY '00:00:01'; SELECT 42 AS answer"); + nextQuery.setTimeoutInMillisecond("10000"); + nextQuery.setPluginSpecifiedTemplates( + List.of(new Property("preparedStatement", String.valueOf(preparedStatement)))); + StepVerifier.create(mssqlPluginExecutor.executeParameterized( + connectionPool, + new ExecuteActionDTO(), + createDatasourceConfiguration(container), + nextQuery)) + .assertNext(result -> { + assertThat(result.getIsExecutionSuccess()) + .as("the next query on the pool: %s", result.getBody()) + .isTrue(); + assertThat(String.valueOf(result.getBody())).contains("42"); + }) + .expectComplete() + .verify(Duration.ofSeconds(30)); } finally { connectionPool.close(); } diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java index 69d508ea89c..dd521a369dd 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java @@ -1,11 +1,14 @@ package com.external.plugins.utils; import com.external.plugins.exceptions.MssqlErrorMessages; +import com.zaxxer.hikari.HikariDataSource; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.InOrder; import org.mockito.Mockito; +import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; @@ -13,14 +16,19 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.ReentrantLock; import static java.lang.Boolean.FALSE; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.after; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @@ -107,14 +115,184 @@ void should_cancelTheStatement_when_theDeadlinePassesDuringABlockedRead() throws void should_notCancelTheStatement_when_theTimerIsStoppedBeforeTheDeadline() throws Exception { // Given Statement statement = Mockito.mock(Statement.class); - long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200); + // A deadline far enough away that a slow test machine still stops the timer first. + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1000); // When - MssqlExecuteUtils.cancelAtDeadline(statement, deadline).cancel(false); + boolean reusable = + MssqlExecuteUtils.cancelAtDeadline(statement, deadline).stop(); // Then + assertThat(reusable).isTrue(); // Still not cancelled well after the deadline. - verify(statement, after(400).never()).cancel(); + verify(statement, after(1500).never()).cancel(); + } + + // AIP-FD-39: the timer has started the cancel, but the cancel has not taken the lock yet. A stop() in that window + // must win: the cancel must not run afterwards, and the connection can be reused. + @Test + void should_neverCancel_when_stopComesBetweenTheTimerAndTheCancel() throws Exception { + // Given: the test holds the lock, so the cancel the timer started waits for it. + Statement statement = Mockito.mock(Statement.class); + MssqlExecuteUtils.DeadlineCancel cancel = + MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(50)); + ReentrantLock lock = cancel.lockForTests(); + lock.lock(); + CompletableFuture stop; + try { + await().atMost(Duration.ofSeconds(5)).until(lock::hasQueuedThreads); + + // When: stop() is called, and also waits for the lock. + stop = CompletableFuture.supplyAsync(cancel::stop); + await().atMost(Duration.ofSeconds(5)).until(() -> lock.getQueueLength() == 2); + } finally { + lock.unlock(); + } + + // Then: whichever gets the lock first, the cancel does not run and the connection can be reused. + assertThat(stop.get(5, TimeUnit.SECONDS)).isTrue(); + verify(statement, after(300).never()).cancel(); + } + + @Test + void should_notReuseTheConnection_when_aCancelRanBeforeTheStop() throws Exception { + // Given + Statement statement = Mockito.mock(Statement.class); + MssqlExecuteUtils.DeadlineCancel cancel = MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime()); + verify(statement, timeout(5000)).cancel(); + + // When + boolean reusable = cancel.stop(); + + // Then + assertThat(reusable).isFalse(); + } + + // AIP-FD-39: a cancel that the timer has already started must finish before the connection can go back to the + // pool. Otherwise it can reach SQL Server later and stop the next query on that connection. + @Test + void should_waitForARunningCancel_when_stopping() throws Exception { + // Given: the cancel is sending to SQL Server and has not finished. + Statement statement = Mockito.mock(Statement.class); + CountDownLatch cancelStarted = new CountDownLatch(1); + CountDownLatch releaseCancel = new CountDownLatch(1); + doAnswer(invocation -> { + cancelStarted.countDown(); + releaseCancel.await(10, TimeUnit.SECONDS); + return null; + }) + .when(statement) + .cancel(); + MssqlExecuteUtils.DeadlineCancel cancel = MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime()); + try { + assertThat(cancelStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + // When + CompletableFuture stop = CompletableFuture.supplyAsync(cancel::stop); + + // Then: stop waits for the cancel, then says the connection must not be reused. + assertThat(catchThrowable(() -> stop.get(300, TimeUnit.MILLISECONDS))) + .isInstanceOf(TimeoutException.class); + releaseCancel.countDown(); + assertThat(stop.get(5, TimeUnit.SECONDS)).isFalse(); + } finally { + releaseCancel.countDown(); + } + } + + @Test + void should_notReuseTheConnection_when_aCancelIsStillRunningAfterTheWait() throws Exception { + // Given: the cancel hangs, for example on a server that stopped answering. + Statement statement = Mockito.mock(Statement.class); + CountDownLatch cancelStarted = new CountDownLatch(1); + CountDownLatch releaseCancel = new CountDownLatch(1); + doAnswer(invocation -> { + cancelStarted.countDown(); + releaseCancel.await(30, TimeUnit.SECONDS); + return null; + }) + .when(statement) + .cancel(); + MssqlExecuteUtils.DeadlineCancel cancel = MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime()); + assertThat(cancelStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + try { + // When + long start = System.nanoTime(); + boolean reusable = cancel.stop(); + + // Then: stop gives up after its wait, and the connection is not reused. + assertThat(reusable).isFalse(); + assertThat(Duration.ofNanos(System.nanoTime() - start)) + .isGreaterThanOrEqualTo(Duration.ofMillis(MssqlExecuteUtils.DeadlineCancel.STOP_WAIT_MILLIS - 100)); + } finally { + releaseCancel.countDown(); + } + } + + @Test + void should_removeTheConnectionFromThePool_when_itIsNotReusable() throws Exception { + // Given + Statement statement = Mockito.mock(Statement.class); + Connection connection = Mockito.mock(Connection.class); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, statement, null, connection, pool, false); + + // Then: removed first, so closing the statement cannot wait on a server that stopped answering. + InOrder order = inOrder(pool, statement); + order.verify(pool).evictConnection(connection); + order.verify(statement).close(); + verify(connection, never()).close(); + } + + @Test + void should_closeTheConnectionToSqlServer_when_thePoolCannotRemoveIt() throws Exception { + // Given + Connection connection = Mockito.mock(Connection.class); + Connection physicalConnection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenReturn(physicalConnection); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + Mockito.doThrow(new IllegalStateException("pool error")).when(pool).evictConnection(connection); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); + + // Then: the session on SQL Server ends before the connection goes back to the pool. + InOrder order = inOrder(physicalConnection, connection); + order.verify(physicalConnection).close(); + order.verify(connection).close(); + } + + @Test + void should_closeTheConnection_when_itIsNotReusableAndThePoolIsClosed() throws Exception { + // Given: Hikari ignores an eviction once the pool is closed. + Connection connection = Mockito.mock(Connection.class); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + when(pool.isClosed()).thenReturn(true); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); + + // Then + verify(connection).close(); + verify(pool, never()).evictConnection(Mockito.any()); + } + + @Test + void should_returnTheConnectionToThePool_when_itIsReusable() throws Exception { + // Given + Statement statement = Mockito.mock(Statement.class); + Connection connection = Mockito.mock(Connection.class); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, statement, null, connection, pool, true); + + // Then + verify(connection).close(); + verify(pool, never()).evictConnection(Mockito.any()); } @Test @@ -122,11 +300,11 @@ void should_removeTheTaskFromTheQueue_when_theTimerIsStoppedBeforeTheDeadline() // Given Statement statement = Mockito.mock(Statement.class); long farDeadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(1); - ScheduledFuture task = MssqlExecuteUtils.cancelAtDeadline(statement, farDeadline); + MssqlExecuteUtils.DeadlineCancel task = MssqlExecuteUtils.cancelAtDeadline(statement, farDeadline); int queued = MssqlExecuteUtils.pendingCancels(); // When - task.cancel(false); + task.stop(); // Then // A finished query does not stay in the queue until its deadline. From 1d0b829867f89b612f8651d45b5a459681afec5a Mon Sep 17 00:00:00 2001 From: Stacey Levine Date: Fri, 20 Nov 2026 17:24:52 -0500 Subject: [PATCH 2/3] fix(mssql): end the session of a discarded connection at once - When a connection must not be reused, end its session on SQL Server with Connection.abort before the statements are closed. Hikari's own close runs later on another thread, and can be skipped while the pool shuts down. Closing the statements first could also make the driver wait for the rest of the response. - If the pool cannot remove the connection, it goes back already closed, so the next borrower gets a connection error, never this session. - Tests: the timeout test checks the timeout error before it checks that the session ended. The race test starts the cancel itself, after it holds the lock. The stuck-cancel test fails if stop() waits without a bound. Co-Authored-By: Claude Opus 5.5 --- .../plugins/utils/MssqlExecuteUtils.java | 82 ++++++++++++++----- .../plugins/MssqlDriverBehaviourTest.java | 6 +- .../plugins/utils/MssqlExecuteUtilsTest.java | 66 +++++++++++---- 3 files changed, 115 insertions(+), 39 deletions(-) diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java index d6360148032..af19cc33bd3 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -85,9 +85,15 @@ public static void closeConnectionPostExecution( } /** - * Like {@link #closeConnectionPostExecution}, but when {@code reusable} is false, the connection is removed from the - * pool and closed instead of going back to it. A cancel sent to SQL Server for this connection may still be on its - * way, and must not stop the next query that would use it. + * Like {@link #closeConnectionPostExecution}, but when {@code reusable} is false, the connection never serves + * another query. A cancel sent to SQL Server for this connection may still be on its way, and must not stop the + * next query that would use it. In that case: + * + *
    + *
  • the connection is removed from the pool; + *
  • its session on SQL Server ends at once, before the statements are closed; + *
  • if the pool cannot remove it, it goes back closed, so the next borrower gets a connection error. + *
*/ public static void closeConnectionPostExecution( ResultSet resultSet, @@ -100,32 +106,61 @@ public static void closeConnectionPostExecution( closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); return; } - if (pool == null || pool.isClosed()) { - // Nothing to remove it from. A closed pool aborts its connections anyway. - log.warn("A Mssql connection that a cancel may still reach was closed without removing it from a pool."); - closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); + + // Taken while the pool's wrapper still holds it. + Connection sqlServerConnection = physicalConnection(connectionFromPool); + boolean removed = false; + if (pool != null && !pool.isClosed()) { + log.info( + "Removing a Mssql connection from pool {}: a cancel at the query's timeout ran or may still be sent.", + pool.getPoolName()); + try { + // While the wrapper is still open, so Hikari removes it at once and never lends it again. + pool.evictConnection(connectionFromPool); + removed = true; + } catch (RuntimeException e) { + log.warn("Could not remove a Mssql connection from the pool after a query cancel.", e); + } + } else { + log.warn("A Mssql connection that a cancel may still reach is closed without removing it from a pool."); + } + + // End the session on SQL Server now, without reading what is left on it. Hikari closes the connection later + // on its own thread, and may skip that close while the pool shuts down. Closing the statements first could + // also make the driver wait for the rest of the response from a server that stopped answering. + // When the driver's connection cannot be reached, the pool's wrapper passes the abort on to it. + abortQuietly(sqlServerConnection != null ? sqlServerConnection : connectionFromPool); + + // The statements now close at once, because their connection is closed. When the pool could not remove the + // wrapper, it goes back closed: the next borrower gets a connection error, never this session. + closeConnectionPostExecution(resultSet, statement, preparedQuery, removed ? null : connectionFromPool); + } + + /** Returns the driver's own connection inside the pool's wrapper, or null when it cannot be reached. */ + private static Connection physicalConnection(Connection connectionFromPool) { + try { + return connectionFromPool.unwrap(Connection.class); + } catch (SQLException e) { + log.warn("Could not reach the Mssql connection inside the pool's wrapper.", e); + return null; + } + } + + /** Ends the connection's session on SQL Server at once. {@link Connection#abort} does not wait for the server. */ + private static void abortQuietly(Connection connection) { + if (connection == null) { return; } - log.info( - "Removing a Mssql connection from pool {}: a cancel at the query's timeout ran or may still be sent.", - pool.getPoolName()); try { - // Removed first, while the connection is still open, so Hikari closes it at once and never lends it again. - // Closing the statements afterwards cannot then wait on a server that stopped answering. - pool.evictConnection(connectionFromPool); - } catch (RuntimeException e) { - log.warn("Could not remove a Mssql connection from the pool after a query cancel.", e); - // Close the connection to SQL Server first. The pool may still lend it again, but a late cancel then - // has no session to reach, and the next borrower gets a connection error instead. + connection.abort(Runnable::run); + } catch (SQLException | RuntimeException e) { + log.warn("Could not abort a Mssql connection after a query cancel. Closing it instead.", e); try { - connectionFromPool.unwrap(Connection.class).close(); + connection.close(); } catch (SQLException closeError) { log.warn("Could not close a Mssql connection after a query cancel.", closeError); } - closeConnectionPostExecution(resultSet, statement, preparedQuery, connectionFromPool); - return; } - closeConnectionPostExecution(resultSet, statement, preparedQuery, null); } public static void populateRowsAndColumns( @@ -296,6 +331,11 @@ ReentrantLock lockForTests() { return lock; } + /** Starts the cancel now, as the timer does at the deadline. For tests that control when it starts. */ + void startCancelForTests() { + CANCEL_THREADS.start(this::run); + } + /** * Stops the cancel. After this returns, no cancel for this query starts. * diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java index 6736d303a9a..e9882ed0aa6 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlDriverBehaviourTest.java @@ -551,7 +551,11 @@ void should_closeTheConnection_when_theQueryIsCancelledAtItsTimeout(boolean prep // When StepVerifier.create(mssqlPluginExecutor.executeParameterized( pool, new ExecuteActionDTO(), createDatasourceConfiguration(container), actionConfiguration)) - .assertNext(result -> assertThat(result.getIsExecutionSuccess()).isFalse()) + // The query must fail because of its timeout, not because the connection broke for another reason. + .assertNext(result -> { + assertThat(result.getIsExecutionSuccess()).isFalse(); + assertThat(String.valueOf(result.getBody())).contains("ran longer than its timeout of 3000 ms"); + }) .expectComplete() .verify(Duration.ofSeconds(30)); diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java index dd521a369dd..4c86e4d8321 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java @@ -132,14 +132,16 @@ void should_notCancelTheStatement_when_theTimerIsStoppedBeforeTheDeadline() thro // must win: the cancel must not run afterwards, and the connection can be reused. @Test void should_neverCancel_when_stopComesBetweenTheTimerAndTheCancel() throws Exception { - // Given: the test holds the lock, so the cancel the timer started waits for it. + // Given: the test holds the lock, then starts the cancel itself, so the cancel always waits for the lock. The + // timer's own deadline is far away, so only the test starts it. Statement statement = Mockito.mock(Statement.class); MssqlExecuteUtils.DeadlineCancel cancel = - MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(50)); + MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime() + TimeUnit.MINUTES.toNanos(1)); ReentrantLock lock = cancel.lockForTests(); lock.lock(); CompletableFuture stop; try { + cancel.startCancelForTests(); await().atMost(Duration.ofSeconds(5)).until(lock::hasQueuedThreads); // When: stop() is called, and also waits for the lock. @@ -214,15 +216,18 @@ void should_notReuseTheConnection_when_aCancelIsStillRunningAfterTheWait() throw .when(statement) .cancel(); MssqlExecuteUtils.DeadlineCancel cancel = MssqlExecuteUtils.cancelAtDeadline(statement, System.nanoTime()); - assertThat(cancelStarted.await(5, TimeUnit.SECONDS)).isTrue(); - try { + assertThat(cancelStarted.await(5, TimeUnit.SECONDS)).isTrue(); + // When long start = System.nanoTime(); - boolean reusable = cancel.stop(); + CompletableFuture stop = CompletableFuture.supplyAsync(cancel::stop); - // Then: stop gives up after its wait, and the connection is not reused. - assertThat(reusable).isFalse(); + // Then: stop gives up after its wait while the cancel is still stuck, well before the mock's 30-second + // backstop, and the connection is not reused. + assertThat(stop.get(MssqlExecuteUtils.DeadlineCancel.STOP_WAIT_MILLIS + 3_000, TimeUnit.MILLISECONDS)) + .isFalse(); + assertThat(releaseCancel.getCount()).as("the cancel is still stuck").isEqualTo(1); assertThat(Duration.ofNanos(System.nanoTime() - start)) .isGreaterThanOrEqualTo(Duration.ofMillis(MssqlExecuteUtils.DeadlineCancel.STOP_WAIT_MILLIS - 100)); } finally { @@ -231,28 +236,32 @@ void should_notReuseTheConnection_when_aCancelIsStillRunningAfterTheWait() throw } @Test - void should_removeTheConnectionFromThePool_when_itIsNotReusable() throws Exception { + void should_removeTheConnectionAndEndItsSession_when_itIsNotReusable() throws Exception { // Given Statement statement = Mockito.mock(Statement.class); Connection connection = Mockito.mock(Connection.class); + Connection sqlServerConnection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenReturn(sqlServerConnection); HikariDataSource pool = Mockito.mock(HikariDataSource.class); // When MssqlExecuteUtils.closeConnectionPostExecution(null, statement, null, connection, pool, false); - // Then: removed first, so closing the statement cannot wait on a server that stopped answering. - InOrder order = inOrder(pool, statement); + // Then: removed from the pool, and its session ended, before the statement is closed. Closing the statement + // first could wait on a server that stopped answering, and Hikari's own close runs later on another thread. + InOrder order = inOrder(pool, sqlServerConnection, statement); order.verify(pool).evictConnection(connection); + order.verify(sqlServerConnection).abort(Mockito.any()); order.verify(statement).close(); verify(connection, never()).close(); } @Test - void should_closeTheConnectionToSqlServer_when_thePoolCannotRemoveIt() throws Exception { + void should_endTheSessionAndReturnItClosed_when_thePoolCannotRemoveIt() throws Exception { // Given Connection connection = Mockito.mock(Connection.class); - Connection physicalConnection = Mockito.mock(Connection.class); - when(connection.unwrap(Connection.class)).thenReturn(physicalConnection); + Connection sqlServerConnection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenReturn(sqlServerConnection); HikariDataSource pool = Mockito.mock(HikariDataSource.class); Mockito.doThrow(new IllegalStateException("pool error")).when(pool).evictConnection(connection); @@ -260,15 +269,17 @@ void should_closeTheConnectionToSqlServer_when_thePoolCannotRemoveIt() throws Ex MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); // Then: the session on SQL Server ends before the connection goes back to the pool. - InOrder order = inOrder(physicalConnection, connection); - order.verify(physicalConnection).close(); + InOrder order = inOrder(sqlServerConnection, connection); + order.verify(sqlServerConnection).abort(Mockito.any()); order.verify(connection).close(); } @Test - void should_closeTheConnection_when_itIsNotReusableAndThePoolIsClosed() throws Exception { + void should_endTheSession_when_itIsNotReusableAndThePoolIsClosed() throws Exception { // Given: Hikari ignores an eviction once the pool is closed. Connection connection = Mockito.mock(Connection.class); + Connection sqlServerConnection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenReturn(sqlServerConnection); HikariDataSource pool = Mockito.mock(HikariDataSource.class); when(pool.isClosed()).thenReturn(true); @@ -276,10 +287,31 @@ void should_closeTheConnection_when_itIsNotReusableAndThePoolIsClosed() throws E MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); // Then - verify(connection).close(); + InOrder order = inOrder(sqlServerConnection, connection); + order.verify(sqlServerConnection).abort(Mockito.any()); + order.verify(connection).close(); verify(pool, never()).evictConnection(Mockito.any()); } + @Test + void should_closeTheSession_when_abortFails() throws Exception { + // Given + Connection connection = Mockito.mock(Connection.class); + Connection sqlServerConnection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenReturn(sqlServerConnection); + Mockito.doThrow(new SQLException("abort not allowed")) + .when(sqlServerConnection) + .abort(Mockito.any()); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); + + // Then + verify(sqlServerConnection).close(); + verify(pool).evictConnection(connection); + } + @Test void should_returnTheConnectionToThePool_when_itIsReusable() throws Exception { // Given From 19d395c33dfca0e467c03f927ec0dbfee773b2ac Mon Sep 17 00:00:00 2001 From: Stacey Levine Date: Fri, 20 Nov 2026 17:55:44 -0500 Subject: [PATCH 3/3] fix(mssql): end the session before the pool closes the connection Abort the driver's connection while it is still checked out, then remove it from the pool. Hikari closes the connection again on its own thread after the removal. Run at the same time, the two cleanups in mssql-jdbc could release a timer that other connections share. When the driver's connection cannot be reached, the abort goes through the pool's wrapper after the removal, as before. Co-Authored-By: Claude Opus 5.5 --- .../plugins/utils/MssqlExecuteUtils.java | 20 +++++++++++----- .../plugins/utils/MssqlExecuteUtilsTest.java | 24 +++++++++++++++---- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java index af19cc33bd3..ec33b3ced01 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -107,8 +107,16 @@ public static void closeConnectionPostExecution( return; } - // Taken while the pool's wrapper still holds it. + // End the session on SQL Server now, without reading what is left on it, while the connection is still checked + // out. Hikari closes the connection again on its own thread after it is removed, and may skip that close while + // the pool shuts down. Aborting first means the two closes never run at the same time: the driver's cleanup is + // not safe to run twice at once, and could shut down a timer that other connections share. Closing the + // statements first could also make the driver wait for the rest of the response. Connection sqlServerConnection = physicalConnection(connectionFromPool); + if (sqlServerConnection != null) { + abortQuietly(sqlServerConnection); + } + boolean removed = false; if (pool != null && !pool.isClosed()) { log.info( @@ -125,11 +133,11 @@ public static void closeConnectionPostExecution( log.warn("A Mssql connection that a cancel may still reach is closed without removing it from a pool."); } - // End the session on SQL Server now, without reading what is left on it. Hikari closes the connection later - // on its own thread, and may skip that close while the pool shuts down. Closing the statements first could - // also make the driver wait for the rest of the response from a server that stopped answering. - // When the driver's connection cannot be reached, the pool's wrapper passes the abort on to it. - abortQuietly(sqlServerConnection != null ? sqlServerConnection : connectionFromPool); + if (sqlServerConnection == null) { + // The driver's connection could not be reached. The pool's wrapper passes the abort on to it. This runs + // after the removal, because an aborted wrapper would no longer be removed from the pool at once. + abortQuietly(connectionFromPool); + } // The statements now close at once, because their connection is closed. When the pool could not remove the // wrapper, it goes back closed: the next borrower gets a connection error, never this session. diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java index 4c86e4d8321..59da103222b 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/utils/MssqlExecuteUtilsTest.java @@ -247,11 +247,11 @@ void should_removeTheConnectionAndEndItsSession_when_itIsNotReusable() throws Ex // When MssqlExecuteUtils.closeConnectionPostExecution(null, statement, null, connection, pool, false); - // Then: removed from the pool, and its session ended, before the statement is closed. Closing the statement - // first could wait on a server that stopped answering, and Hikari's own close runs later on another thread. - InOrder order = inOrder(pool, sqlServerConnection, statement); - order.verify(pool).evictConnection(connection); + // Then: the session ends before the removal, so it never runs at the same time as Hikari's own close on its + // thread. Both happen before the statement is closed, which could wait on a server that stopped answering. + InOrder order = inOrder(sqlServerConnection, pool, statement); order.verify(sqlServerConnection).abort(Mockito.any()); + order.verify(pool).evictConnection(connection); order.verify(statement).close(); verify(connection, never()).close(); } @@ -293,6 +293,22 @@ void should_endTheSession_when_itIsNotReusableAndThePoolIsClosed() throws Except verify(pool, never()).evictConnection(Mockito.any()); } + @Test + void should_abortThroughThePoolsWrapperAfterTheRemoval_when_theDriversConnectionCannotBeReached() throws Exception { + // Given + Connection connection = Mockito.mock(Connection.class); + when(connection.unwrap(Connection.class)).thenThrow(new SQLException("not a wrapper")); + HikariDataSource pool = Mockito.mock(HikariDataSource.class); + + // When + MssqlExecuteUtils.closeConnectionPostExecution(null, null, null, connection, pool, false); + + // Then: an aborted wrapper would no longer be removed at once, so the removal comes first. + InOrder order = inOrder(pool, connection); + order.verify(pool).evictConnection(connection); + order.verify(connection).abort(Mockito.any()); + } + @Test void should_closeTheSession_when_abortFails() throws Exception { // Given