← Back to Pull requests

[fix](fe) Stop stalled MySQL result writes on query cancellation #70607

Closed
unknown closed this pull request without merging on Nov 20, 2026 01:19 UTC
View on GitHub
unknown unknown commented on Nov 16, 2026 05:38 UTC
Author

What problem does this PR solve?

When a MySQL client stops consuming a large result, the FE can block writing a result packet. KILL QUERY cancels the query's backend execution and result fetching, but the original FE worker remains in the network write until net_write_timeout expires. The query therefore remains visible even though backend execution has already been cancelled or finished.

The normal flow is:

BE result -> ResultReceiver -> StmtExecutor -> MysqlResultSender -> MysqlChannel -> client

Cancellation reaches StmtExecutor, the coordinator and result receivers. It does not interrupt an already-running Channels.writeBlocking or flushBlocking in MysqlChannel. Adding only a cancellation check between rows cannot release a worker already waiting inside that write.

Fix

  • Bind a cancellation-reason supplier to the current MySQL command. It reads the current executor's existing atomic cancellation state, including executor changes within a multi-statement command, and is cleared in finally.

  • Replace the long blocking write/flush with nonblocking attempts and bounded awaitWritable waits. A stalled write checks cancellation at intervals of at most 100 ms. The original network-write deadline is retained rather than renewed on each check; the writable path introduces no waiting.

  • On cancellation or timeout of a stalled write/flush, latch a terminal transport failure, mark the session killed and close the channel on the writer thread. Later writes rethrow the original failure even if a Command/prepared handler consumes its exception, buffers are reset, or the peer becomes writable again. Part of a MySQL packet may already be on the wire, so no ERR can safely be appended to that stream.

  • Preserve ordinary KILL QUERY connection reuse: a cancellation error that can be written normally is still sent without disconnecting the client.

  • Check cancellation while sending rows and resolve EOF cancellation before deciding whether an intermediate response is sent. A cancelled non-last SELECT defers its single ERR to command finalization. Packet emission does not re-evaluate that intermediate decision. Committed OK responses and NOOP commands that already sent a response are preserved.
  • The bounded cancellation response applies to stalled MySQL writes. This PR does not change coordinator-initialization cancellation races or promise the same bound at every query execution stage.

    Release note

    Cancelled queries now stop promptly when blocked sending MySQL results. Ordinary query cancellation continues to allow connection reuse; cancelling a stalled result stream closes that connection.

    Check List (For Author)

  • Test

  • - [x] Regression test
    - [x] Unit Test
    - [x] Manual test (details below)
    - [ ] No need to test or manual test. Explain why:

  • Behavior changed:

  • - [ ] No.
    - [x] Yes. Cancellation interrupts a stalled MySQL result write instead of waiting for its network timeout; that stalled connection is closed.

  • Does this need documentation?

  • - [x] No.
    - [ ] Yes.

    Unit tests

    MysqlChannelTest, MysqlResultSenderTest, MysqlWriteCancellationTest, MysqlConnectProcessorCursorFetchTest and MysqlPacketGoldenTest cover cancellation during write/flush waits, partial writes, original timeout deadlines, writable cancellation responses, command cleanup, EOF/OK/NOOP handling and the existing packet golden cases.

    Current PR head 367c2788f97 passed all 39 tests in the five named classes plus EncryptSQLTest (0 failures, 0 errors), using run-fe-ut.sh. Checkstyle reported zero violations. The unchanged production implementation passed the complete FE package build with build.sh --fe at acad76189b6; this follow-up only changes four test mock initializers. All six selected test suites completed successfully; the script was then stopped during slow unpacking of a subsequent unrelated Java extension dependency. This is not a full-script or full-FEUT success claim.

    The FEUT failure in all four EncryptSQLTest methods was reproduced locally before this follow-up. These audit tests use constructor mocks with CALLS_REAL_METHODS, bypassing the initialization of the executor's atomic cancellation state. Statement finalization now reads that state, exposing the incomplete mock setup. Each initializer now explicitly stubs getPendingCancelReason() to return null, representing uncancelled execution. The existing SQL masking assertions and production initialization invariant remain unchanged.

    Two focused protocol reproductions failed on the previous implementation. The new tests verify one terminal ERR across intermediate-statement and command finalization, followed by a usable next response. A prepared-handler test simulates the Command exception wrapper after a partial write, then makes the sink writable and clears/reset buffers: the connection is killed and closed, and neither finalization nor another write can append bytes.

    JDBC regression

    Added test_mysql_kill_query_reuse. It cancels a long query twice on the same JDBC connection, checks the server connection ID after each cancellation, and then executes SELECT 42. The output was generated with run-regression-test.sh and a subsequent comparison run passed: 1 suite, 0 failures. This JDBC/socket validation predates the follow-up protocol fixes; current-head coverage of the newly reported cases is provided by the unit tests above.

    Local socket reproduction

    The following functional checks ran against a locally built FE before rebasing onto current master; the BE used the existing local binary. They are local samples, not throughput or percentile benchmarks.

    1. Connect a MySQL client, set net_write_timeout=20, reduce its receive buffer to 4 KiB, send the following query and stop reading the response:

       SELECT repeat('x', 1048576) FROM numbers('number'='128');
       

    2. Confirm the FE is waiting in MysqlChannel.realNetSend / awaitWritable using a thread dump, then cancel from another connection.
    3. Before the fix, the FE waited for the full 20-second write timeout (about 17 seconds remained after cancellation). After the fix, three KILL QUERY samples removed the session in approximately 29 / 62 / 85 ms, and the client observed disconnection. KILL CONNECTION controls completed in approximately 3 ms. Session-list sampling used a 20 ms interval.
    4. For ordinary cancellation while fetching results, cancel three successive queries on one TCP connection. Each cancellation returned an error, and subsequent queries and PING succeeded with both the server connection ID and client socket unchanged. Three additional early-cancellation checks also retained their original connection, although one waited for the current five-second BE operation to finish.
    5. With normal client consumption, all 128 rows / 128 MiB of the result were received.

    The current implementation also passed a complete FE package build with build.sh --fe and Checkstyle with zero violations. Remote current-head build and review are requested separately.

    Check List (For Reviewer who merge this PR)

  • Confirm the release note

  • Confirm test cases

  • Confirm document

  • Add branch pick label
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: morrySnow Review duration: 5501m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #70607"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%
    Repository