Skip to content

Fix streaming result leak to pooled connections when proxy client disconnects (#40375) - #40577

Open
penghuazhou wants to merge 5 commits into
apache:masterfrom
penghuazhou:fix/pr40495-connector-local
Open

penghuazhou wants to merge 5 commits into
apache:masterfrom
penghuazhou:fix/pr40495-connector-local

Conversation

@penghuazhou

@penghuazhou penghuazhou commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #40375.

When a proxy client disconnects while its SELECT is starting or streaming, FrontendChannelInboundHandler.closeAllResources() can run on the shared frontend executor before the command thread's finish() releases resources. It then closes the backend Statement/Connection while the command thread is still entering Statement.execute (or reading the streaming result). Connector/J's StatementImpl.realClose can 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 with S1000: 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

  • ProxyDatabaseConnectionManager tracks an in-flight command (markCommandExecuting() at connector creation, cleared in closeExecutionResources()). closeAllResources() gates on it: while a command is in flight it only cancels, it does not close handlers or recycle connections.
  • DatabaseProxyConnector gains cancel() (cancel statements only; result sets stay owned by the executing thread) and isDisconnected(). The generic ProxyBackendHandler interface is unchanged.
  • StandardDatabaseProxyConnector serializes cancel() and close() on a connector-local lock, and cancelStatements() / cancelHandlers() ignore non-SQLException driver failures so cleanup always reaches process deregistration and protocol release.
  • MySQLCommandExecuteEngine / PostgreSQLCommandExecuteEngine drain the streaming result after the channel closes (named draining helpers) and swallow the KILL-induced SQLException.
  • ProxyJDBCExecutorCallback.executeSQL aborts before Statement.execute when the frontend is gone, using ShardingSpherePreconditions.checkState with a lazy exception supplier.
  • ExecutorEngine.parallelExecute now 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.
  • CommandExecutorTask is not modified.

Design questions

(1) Why the original fix needed CommandExecutorTask and ProxyBackendHandler, 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 generic ProxyBackendHandler collection, so the interface had to grow cancel(). 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 concrete DatabaseProxyConnector type the manager already stores. No cleanup ordering crosses into CommandExecutorTask.

(2) Evaluation of a connector-local alternative. It can guarantee that a connection is never recycled while a command is in flight (the gate; closeConnections stays the only recycle point) and that cancel and close are ordered (cleanup only KILLs, the command thread closes in closeExecutionResources()). 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 writeQueryData because the connector cannot read the result for the command thread. A shard task that reaches Statement.execute after cleanup is aborted in the JDBC callback immediately before execute. Async groups that outlive a synchronous failure are now awaited (or cancelled on interrupt) by ExecutorEngine before the command thread's cleanup runs. Remaining residuals: a blocked read without socketTimeout cannot be interrupted by cancel(); 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:

  1. [P1] Command-thread completion does not establish completion of all backend tasks. ExecutorEngine now awaits every submitted async group before propagating a synchronous failure, and cancels them on interrupt. Deterministic regression test: assertParallelExecuteAwaitsAsyncGroupsWhenSyncFails.
  2. [P2] Cross-thread cancellation races with direct connector closure. cancel() and close() are serialized on one connector-local lock, and cancelStatements() / cancelHandlers() ignore non-SQLException driver failures (Connector/J 8.4.0 cancel NPE). Tests: assertCancelIgnoresNonSqlException, assertCancelAndCloseAreSerialized, and a manager runtime-cancel test.
  3. [P2] Ad-hoc comments. Removed; intent is carried by named helpers (writeQueryDataAndConsumeRemaining, drainQueryData) and ShardingSpherePreconditions. Only Checkstyle control directives remain.
  4. [P2] Conditional throw bypassed the precondition utility. Now ShardingSpherePreconditions.checkState with a lazy SQLException supplier, preserving type, message, order and construction timing.
  5. [P2] Unnecessary assertion line break. The assertion is on one line (158 characters).
  6. [P2] Dedicated delegation test. Removed assertIsDisconnected; execution-abort and resource-lifecycle tests remain.
  7. [P2] Declarations interrupted helper adjacency. close() is followed by its cleanup helpers, and cancel() by cancelStatements().

Testing

  • Full build ./mvnw clean install -B -T1C -Pcheck: 448 modules, 13:38 min, no test failures (Spotless, Checkstyle and RAT included).
  • Focused tests: 146 tests across the four touched modules pass, including the new deterministic concurrency, NPE handling, serialization and disconnect-guard tests.
  • Integration (Standalone, distribution rebuilt from source, MySQL 8.0.28): 6 steady clients x 1,000 primary-key SELECTs, 8 workers x 50 mid-stream disconnects, and 4 execute-phase client aborts produced 0 S1000, 0 NullPointerException and 0 proxy-side errors.
  • XA mode is not runnable here: the storage account lacks XA_RECOVER_ADMIN, so the proxy refuses XA startup. Cluster mode needs a registry center and was not run.

Residual risks

  • A blocked backend read without socketTimeout cannot be interrupted by Statement.cancel(); the connection is kept out of the pool rather than forcibly released.
  • Slow prepare / MDL before statement registration has no cancel target.
  • XA and cluster end-to-end coverage remains environment-limited as noted above.

…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 terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. [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.

  2. [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.

  3. [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.

  4. [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.

  5. [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.

  6. [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.

  7. [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>
@penghuazhou

penghuazhou commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@terrymanu Addressed all seven blocking findings in 8563965:

  • [P1] ExecutorEngine.parallelExecute now awaits every submitted async group before propagating a synchronous failure (cancels the rest on interrupt). New deterministic test assertParallelExecuteAwaitsAsyncGroupsWhenSyncFails blocks an async group and proves the sync exception is not propagated until it exits.
  • [P2 cancel/close] StandardDatabaseProxyConnector.cancel() and close() now share a connector-local lock, and cancelStatements()/cancelHandlers() ignore non-SQLException driver failures (Connector/J 8.4.0 cancel session NPE), so cleanup always reaches processEngine.disconnect and release. Tests: assertCancelIgnoresNonSqlException, assertCancelAndCloseAreSerialized, plus a manager runtime-cancel test.
  • [P2 nits] Removed ad-hoc comments (intent is in named helpers and ShardingSpherePreconditions), switched the disconnect guard to checkState with a lazy SQLException, joined the 158-character assertion, removed the delegation-only assertIsDisconnected, and restored close() -> helpers / cancel() -> cancelStatements() adjacency.

Verification: full ./mvnw clean install -B -T1C -Pcheck passes (448 modules, 13:38), focused tests 146/146, and a rebuilt distribution run against MySQL 8.0.28 produced 0 S1000, 0 NPE and 0 proxy errors with 6,000 steady selects, 400 mid-stream disconnects and 4 execute-phase aborts.

ryanzhou and others added 2 commits December 3, 2026 15:10
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 terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. [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.

  2. [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 SQLException declaration serves no behavior or contract, contrary to the implementation rule requiring declarations to have a necessary purpose.

    Required Change: Remove throws SQLException from this private method while retaining the declaration required by public writeQueryData.

  3. [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.

  4. [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)).

  5. [P2] New private helpers are not declared in call order

    Evidence: getGroupResults:135–164 calls cancelFutures before toException, 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, then toException.

  6. [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>
@penghuazhou

penghuazhou commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@terrymanu ,Addressed the six blocking findings in fb81074:

  • [P1] Resumed portal activity tracking. Portal.execute now calls databaseConnectionManager.markCommandExecuting(), so a suspended portal resumed by a later Execute is covered by the disconnect cancel-only gate. Tests: PortalTest.assertExecuteMarksCommandExecutingWhenResumingSuspendedPortal (suspend then resume marks the command) and ProxyDatabaseConnectionManagerTest.assertCloseAllResourcesWhileResumedPortalExecuting (suspended handler + resumed command + disconnect only cancels; the command finish closes).
  • [P2] drainQueryData no longer declares throws SQLException; it catches the only checked-exception source.
  • [P2] getGroupResults now returns Collection<O> and accumulates in Collection<O>; the public execute still returns List.
  • [P2] ExecutorEngineTest asserts the preserved exception with sameInstance.
  • [P2] Helper order is now addException, cancelFutures, toException (then throwException).
  • [P2] Renamed assertCancelIgnoresNonSqlException to assertCancelIgnoresNonSQLException.

Verification: focused tests 167/167 (including the new portal tests), and the full ./mvnw clean install -B -T1C -Pcheck passes (448 modules, 14:20, Spotless/Checkstyle/RAT included).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Proxy] Client disconnect during SELECT can cause streaming-result errors in other client connections (5.5.3)

2 participants