Repository navigation
Fix streaming result leak to pooled connections when proxy client disconnects (#40375) - #40577
penghuazhou wants to merge 5 commits into
Conversation
…connects (apache#40375) Keep backend connections out of the pool until the running command finishes when its client disconnects. The in-flight marker, KILL-only cancel and the cancel-vs-release gate stay inside the connector layer; the protocol engines drain the streaming result after the channel closes, and the JDBC callback aborts a not-yet-started backend operation once the frontend is gone. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
terrymanu
left a comment
There was a problem hiding this comment.
Summary
This PR addresses premature backend connection recycling when a client disconnects during SELECT execution or streaming, which can affect unrelated clients. It defers recycling through an execution-state flag, cancels statements, and continues consuming results; however, asynchronous task completion and cancellation/closure ordering remain insufficiently coordinated.
Result
Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 7
The following findings are a confirmed subset. Required ledger and session validation could not complete because the public PR head Git object is unavailable locally. This is not an exhaustive blocking-issue list.
Blocking Issues
-
[P1] Command-thread completion does not establish completion of all backend tasks
Evidence: closeExecutionResources:340–350. ExecutorEngine submits asynchronous groups before executing the synchronous group. A synchronous exception bypasses waiting for those groups. A scheduling probe using the exact candidate source confirmed that execute can throw while an asynchronous callback remains active.
Impact: Disconnect cancellation or the new guard can trigger this path. Command cleanup then clears commandExecuting and closes or returns connections while other shards may still execute or register result sets. The exceptional multi-shard path still violates the connection-lifetime requirement in #40375.
Required Change: Ensure all submitted backend tasks have exited before closing and returning their resources, and add a deterministic concurrency regression test. -
[P2] Cross-thread cancellation still races with direct connector closure
Evidence: cancelStatements:398–408. CommandExecutorTask directly closes the command executor before entering finish, where closeLock is acquired. Connector/J 8.4.0 cancel still accesses this.session.getThreadId() after establishing its cancellation connection.
Impact: The original query can complete and close its Statement, clearing session before the cancellation thread resumes and dereferences it. The resulting NPE escapes cleanup that catches only SQLException, skipping process deregistration and protocol-resource release.
Required Change: Coordinate cancellation with every direct closure path, and cover this interleaving. -
[P2] Added explanatory comments violate the repository comment rule
Evidence: New comments appear in callback:70–71, MySQL:84–108, and PostgreSQL:94.
Impact: CODE_OF_CONDUCT.md permits only Javadoc, TODO, and FIXME comments. Passing automated style checks does not satisfy this written rule.
Required Change: Express implementation intent through code naming and place necessary contracts in an allowed documentation form. Checkstyle control directives are excluded from this finding. -
[P2] The new conditional throw bypasses the existing precondition utility
Evidence: callback:72–74.
Impact: This branch only constructs and throws SQLException, meeting the repository rule for using ShardingSpherePreconditions. The existing generic checkState signature supports the same checked exception.
Required Change: Use checkState with a lazy exception supplier, preserving the exception type, message, execution order, and construction timing. -
[P2] The new assertion contains an unnecessary line break
Evidence: ProxyJDBCExecutorCallbackTest:185–186.
Impact: The complete statement, including indentation, is 158 characters, below the repository’s 200-character wrapping threshold.
Required Change: Keep this assignment on one line. -
[P2] A dedicated unit test was added for simple delegation
Evidence: StandardDatabaseProxyConnectorTest:892–897.
Impact: assertIsDisconnected only verifies the delegated getClosed().get() value. It covers no connector-owned decision or state transition and violates the explicit prohibition on separate tests for simple delegation.
Required Change: Remove this dedicated test while retaining the execution-abort and resource-lifecycle behavior tests. -
[P2] New declarations interrupt caller/private-helper adjacency
Evidence: StandardDatabaseProxyConnector:370–410.
Impact: Declarations including isDisconnected and cancel were inserted between close and its previously adjacent private cleanup helpers, violating the helper-ordering rule in CODE_OF_CONDUCT.md.
Required Change: Reposition the newly added declarations to restore caller/helper adjacency and call order.
Coverage
- Public candidate head: 7af10f2; merge-base: ce399e7. Two independent assessments covered all 14 changed files. Every snapshot file matched its authoritative GitHub blob identity.
- Checkstyle and Spotless passed for all 13 changed Java files. Both focused Maven test attempts timed out before compilation, so no test result was obtained. The scheduling probe verifies the execution-completion boundary; it does not reproduce contamination of a real database connection pool.
- This is a code-scope assessment. CI was neither queried nor reviewed. Required ledger/session validation remains incomplete. The working tree and Git state were unchanged.
…d proxy clients (apache#40375) - ExecutorEngine now awaits every submitted async group before propagating a synchronous failure (or cancels them on interrupt), so cleanup cannot close connections while shards are still running. - StandardDatabaseProxyConnector serializes cancel() and close() on one lock and ignores driver exceptions such as Connector/J's cancel NPE, so a cross-thread cancel cannot skip process/protocol cleanup. - Replace ad-hoc comments with named draining helpers and ShardingSpherePreconditions, remove the delegation-only test, and restore helper adjacency. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
@terrymanu Addressed all seven blocking findings in 8563965:
Verification: full |
…o fix/pr40495-connector-local
Upstream master added a query result factory selector to ProxyJDBCExecutorCallback and its test helper; update the new test to the new mockCallback signature. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
terrymanu
left a comment
There was a problem hiding this comment.
Summary
This PR addresses backend connections being recycled before execution finishes when a client disconnects. Execution-state tracking, serialized cancellation and closure, result draining, and waiting for asynchronous tasks improve ordinary execution paths. However, activity tracking does not cover resumed PostgreSQL portals, leaving a resource-lifecycle gap.
Result
Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 6
One lifecycle issue and five applicable standards violations remain. Items 1 and 2 were already present in the previously reviewed public version and were missed in that review; the remaining issues were introduced by subsequent commits.
Blocking Issues
-
[P1] Resuming a portal does not mark the command as executing
Evidence: The factory sets the flag, while closeExecutionResources clears it. A suspended portal in a LOCAL transaction retains its handler and connection. A subsequent Execute reuses that portal without passing through the factory.
Impact: If the client disconnects during resumed reading, closeAllResources sees the flag as false, closes the handler still being read, and recycles the connection.
Required Change: Cover resumed portal execution with activity tracking, and add a regression test for suspending, resuming, and disconnecting a portal within a LOCAL transaction.
-
[P2] The private drain helper declares a checked exception it never propagates
Evidence: drainQueryData:90–98 catches every SQLException from its only checked-exception source,
next().Impact: The new private
throws SQLExceptiondeclaration serves no behavior or contract, contrary to the implementation rule requiring declarations to have a necessary purpose.Required Change: Remove
throws SQLExceptionfrom this private method while retaining the declaration required by publicwriteQueryData. -
[P2] The private asynchronous-result helper should use Collection
Evidence: getGroupResults:127–146 only accumulates and returns elements. Its sole caller also uses only
addAll.Impact: The refactoring removes the previous requirement to return a List directly. Neither the current return value nor its local accumulator requires List, violating the applicable collection-declaration rule.
Required Change: Use Collection for this private method’s return type and accumulator, while preserving the public interface’s List contract.
-
[P2] The exception identity assertion does not use sameInstance
Evidence: ExecutorEngineTest:145–173 verifies that the original SQLException instance is preserved, but uses
is(expected).Impact: This is a reference-identity assertion, for which the applicable standard explicitly requires
sameInstance.Required Change: Use
assertThat(actual.getCause(), sameInstance(expected)). -
[P2] New private helpers are not declared in call order
Evidence: getGroupResults:135–164 calls
cancelFuturesbeforetoException, but their declarations appear in the opposite order.Impact: This violates the private-helper ordering requirement in CODE_OF_CONDUCT.md.
Required Change: Order the new helpers by their first calls:
addException,cancelFutures, thentoException. -
[P2] SQL capitalization in the new test method violates the naming convention
Evidence: StandardDatabaseProxyConnectorTest:981 introduces
assertCancelIgnoresNonSqlException.Impact: The three-letter acronym SQL must be uppercase in method names.
Required Change: Rename it to
assertCancelIgnoresNonSQLException.
Coverage
- Public PR head:
534010814e2b9d209bbd58d291cb7ee7f32bf405. All 16 changed files were reviewed through two independent assessments and coordinator validation. - Local Checkstyle and Spotless passed for all 15 Java files; 143 focused tests passed. PostgreSQL tests could not start because dependencies were unavailable offline.
- This is a code-scope assessment. CI was not reviewed, and no end-to-end verification against a real database was performed. No PR code was modified and no remote comments were posted.
…ache#40375) - Portal.execute marks the command executing, so a resumed suspended portal in a LOCAL transaction is protected by the disconnect cancel-only gate. - drainQueryData no longer declares an unreachable checked exception. - getGroupResults uses Collection and its helpers are ordered by first call. - Use sameInstance for the preserved exception assertion and rename the SQL acronym test method. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
@terrymanu ,Addressed the six blocking findings in fb81074:
Verification: focused tests 167/167 (including the new portal tests), and the full |
Summary
Fixes #40375.
When a proxy client disconnects while its
SELECTis starting or streaming,FrontendChannelInboundHandler.closeAllResources()can run on the shared frontend executor before the command thread'sfinish()releases resources. It then closes the backendStatement/Connectionwhile the command thread is still enteringStatement.execute(or reading the streaming result). Connector/J'sStatementImpl.realClosecan drop the reference to a still-open streaming result, and the connection returns to Hikari with streaming state set; later statements on that pooled connection fail withS1000: Streaming result set ... is still active.This revision keeps the fix inside the connector layer and only coordinates with the command/kernel layers where the connector cannot act.
What changed
ProxyDatabaseConnectionManagertracks an in-flight command (markCommandExecuting()at connector creation, cleared incloseExecutionResources()).closeAllResources()gates on it: while a command is in flight it only cancels, it does not close handlers or recycle connections.DatabaseProxyConnectorgainscancel()(cancel statements only; result sets stay owned by the executing thread) andisDisconnected(). The genericProxyBackendHandlerinterface is unchanged.StandardDatabaseProxyConnectorserializescancel()andclose()on a connector-local lock, andcancelStatements()/cancelHandlers()ignore non-SQLException driver failures so cleanup always reaches process deregistration and protocol release.MySQLCommandExecuteEngine/PostgreSQLCommandExecuteEnginedrain the streaming result after the channel closes (named draining helpers) and swallow the KILL-induced SQLException.ProxyJDBCExecutorCallback.executeSQLaborts beforeStatement.executewhen the frontend is gone, usingShardingSpherePreconditions.checkStatewith a lazy exception supplier.ExecutorEngine.parallelExecutenow awaits every submitted async group before propagating a synchronous failure (and cancels the rest on interrupt), so command cleanup cannot close or recycle connections while shards are still running.CommandExecutorTaskis not modified.Design questions
(1) Why the original fix needed
CommandExecutorTaskandProxyBackendHandler, and why this one does not. In the original approach the "command executing" window was a boolean owned by the disconnect ingress, so only the command entry could set it, and cancellation reached handlers through the genericProxyBackendHandlercollection, so the interface had to growcancel(). Both boundaries are avoidable here: the connector is created before any backend access, so marking it at creation covers the borrow / execute / stream / close window, and cancellation is exposed on the concreteDatabaseProxyConnectortype the manager already stores. No cleanup ordering crosses intoCommandExecutorTask.(2) Evaluation of a connector-local alternative. It can guarantee that a connection is never recycled while a command is in flight (the gate;
closeConnectionsstays the only recycle point) and that cancel and close are ordered (cleanup only KILLs, the command thread closes incloseExecutionResources()). It cannot own the streaming drain: Connector/J clears its streaming state only when the same reader thread consumes EOF or the KILL ERR, and that read loop lives in the dialect protocol engine. That is why the drain stays at the protocol write boundary.(3) Cases that still need command/kernel-level coordination. Streaming consumption after disconnect must stay in
writeQueryDatabecause the connector cannot read the result for the command thread. A shard task that reachesStatement.executeafter cleanup is aborted in the JDBC callback immediately beforeexecute. Async groups that outlive a synchronous failure are now awaited (or cancelled on interrupt) byExecutorEnginebefore the command thread's cleanup runs. Remaining residuals: a blocked read withoutsocketTimeoutcannot be interrupted bycancel(); slow prepare / MDL before statement registration has no cancel target; direct-borrow paths without a registered engine are protected only against early recycling.Review follow-up (commit 8563965)
All seven blocking findings from the formal review are addressed:
ExecutorEnginenow awaits every submitted async group before propagating a synchronous failure, and cancels them on interrupt. Deterministic regression test:assertParallelExecuteAwaitsAsyncGroupsWhenSyncFails.cancel()andclose()are serialized on one connector-local lock, andcancelStatements()/cancelHandlers()ignore non-SQLException driver failures (Connector/J 8.4.0 cancel NPE). Tests:assertCancelIgnoresNonSqlException,assertCancelAndCloseAreSerialized, and a manager runtime-cancel test.writeQueryDataAndConsumeRemaining,drainQueryData) andShardingSpherePreconditions. Only Checkstyle control directives remain.ShardingSpherePreconditions.checkStatewith a lazySQLExceptionsupplier, preserving type, message, order and construction timing.assertIsDisconnected; execution-abort and resource-lifecycle tests remain.close()is followed by its cleanup helpers, andcancel()bycancelStatements().Testing
./mvnw clean install -B -T1C -Pcheck: 448 modules, 13:38 min, no test failures (Spotless, Checkstyle and RAT included).S1000, 0NullPointerExceptionand 0 proxy-side errors.XA_RECOVER_ADMIN, so the proxy refuses XA startup. Cluster mode needs a registry center and was not run.Residual risks
socketTimeoutcannot be interrupted byStatement.cancel(); the connection is kept out of the pool rather than forcibly released.