Repository navigation
Conversation
… work A mysql() table function infers its schema during query analysis, before any pipeline exists, so the connect blocks in poll() inside the vendored MariaDB connector where nothing reads ClickHouse cancellation state. Cancellation is already armed at that point: ProcessList::insert runs at executeQuery.cpp:1623, before InterpreterFactory::get at :1883, and CancellationChecker raises is_killed on the max_execution_time deadline. Nothing on the analysis path reads it, so a killed query stayed in system.processes with is_cancelled = 1 for up to connection_max_tries * connect_timeout. On the defaults (connect_timeout = 10, connection_max_tries = 3) that is ~30 s of a query ignoring KILL QUERY, with no unusual settings; a CI hung check caught it at 228 s after the AST fuzzer raised connect_timeout to 100. Connection.cpp installs a MARIADB_OPT_IO_WAIT callback, an extension point the connector already honours by delegating the whole wait to it. The callback is a transliteration of pvio_socket_wait_io_or_timeout's own body plus slicing, so the behaviours that body owns are preserved rather than dropped: it re-polls on EINTR with the remaining monotonic budget (this is 9138e3f, which 04507 guards, and poll() is not restarted by the kernel even though the profiler handler sets SA_RESTART), sets errno to ETIMEDOUT when the budget expires, and treats timeout <= 0 as wait indefinitely, since SETTINGS connect_timeout = 0 reaches the hook as -1 and an unconditional deadline would fail such a connect instantly. Cancellation returns 0, which the connector already treats as an ordinary connect failure, so no new error plumbing is needed. RAII scopes the hook to mysql_real_connect and to mysql_ping, which performs a full reconnect through mariadb_reconnect when MYSQL_OPT_RECONNECT is set (the default), and clears it afterwards so post-connect reads and writes keep the library's own wait. The body is wrapped in catch (...) because it is invoked from C, where an escaping exception is undefined behaviour and noexcept alone would turn it into a server abort. PoolWithFailover.cpp checks cancellation before each connection attempt in the innermost replica loop, and once more after the loop. The last attempt has no next iteration to reach the first check, so without the second one a cancellation during it surfaced as a connection failure instead of QUERY_WAS_CANCELLED. That second check sits before the full-pool fallback rather than just before the terminal throw, so it dominates every exit left: a replica that reported mysqlxx::Pool is full sets full_pool at :252 and the fallback returns Pool::get's result at :279, which would otherwise hand a cancelled query a working connection or report a pool error. This fixes the timeout half of ClickHouse#79526. That report also notes that PoolWithFailover::get holds its mutex across the blocking connect, which is still true (the lock_guard at :206 covers the tryGet at :237), so the issue stays open. Pool::get itself is left alone. It is reachable even with shareable = false, because tryGet throws mysqlxx::Pool is full at Pool.cpp:268 once connections.size() reaches max_connections, but that needs a reachable MySQL saturated to connection_pool_size live connections, since connections only grows after a successful connect at :427. The check above keeps an already-cancelled query out of it; a cancellation arriving while inside its wait is still unobserved. Pool::Entry::forceConnected's retry loop, post-connect read and write waits, the connector's retry loop before the socket reports EINPROGRESS, and the equivalent gap in the PostgreSQL, ODBC and MongoDB clients are also out of scope. Related: ClickHouse#79526 Co-Authored-By: Claude Fable 5 <[email protected]>
The kill_three_tries arm did not pin the per-attempt check it claimed to: with that check deleted, each remaining attempt still stops at its first 200 ms slice inside the sliced wait, so three attempts cost ~600 ms against the arm's 20 s bound and the post-loop check still yields QUERY_WAS_CANCELLED. Latency is bounded by the wait slicing, not by the per-attempt check, so the new kill_retry_count arm counts what the check actually changes: how many connection attempts happen after cancellation. PoolWithFailover::get logs one line per completed retry, so the arm asserts exactly one such line in system.text_log for its own query_id, since attempt 1 is already under way when the cancellation arrives and legitimately logs its line while retries 2 and 3 must not run. Deleting the per-attempt check turns that count into 3 and reddens only this arm, verified over three runs. No arm reached the MySQL engine path, because TableFunctionMySQL builds and drops its own pool per call and connects during analysis. kill_engine_table covers it: a CREATE TABLE ... ENGINE = MySQL with explicit columns does not connect at DDL time, so the connect happens on the SELECT, from inside the pipeline via MySQLWithFailoverSource::onStart. The arm proves it took that path instead of repeating the table function by requiring a StorageMySQL logger row for its query_id, which is emitted at trace level, unlike the LOG_TEST line next to it. Deleting the post-loop check reddens this arm too. Both new arms read system.text_log, which is MergeTree backed, so the runner's randomized parallel replicas settings apply to those reads; they pin enable_parallel_replicas = 0 per query rather than tagging the whole test. No no-parallel tag is needed: the engine table lives in the per-test database and inspecting it through system.tables or system.columns does not connect. The Connection.cpp change is comments only, with the code tokens unchanged.
A visible system.processes row does not mean a connect has begun: the row is inserted before the interpreter that triggers analysis is constructed, so a cancellation could land ahead of the pool. That made kill_retry_count able to go red on a correct build (no attempt ran, so no retry line was logged) and let kill_engine_table pass without ever connecting, since its StorageMySQL guard is written at planning time. Both arms now wait for the pool's own per-attempt log line, which is emitted from inside the attempt, past the check that rejects an already cancelled query. A fixture that never reaches the connect now says so instead of looking like a verdict. Measured natively at 425 us (table function) and 1.2 ms (engine); deferring the connect behind a 3 s sleep widens the window to ~3.1 s, where the unguarded shape reproduces both outcomes 3 of 3 and the guarded shape neither.
The three kill_arm arms cancelled as soon as the query appeared in system.processes. That row is inserted before the interpreter that triggers analysis is constructed, so the cancellation could land before the pool was ever entered -- and both outcomes raise QUERY_WAS_CANCELLED well inside the 20 s bound, so the arms would still print "ok" on a build where the connect is not cancellable at all. Ask run_and_cancel for the connect-stage wait, and route its two fixture-failure codes through report_fixture_failure so a broken fixture is named instead of misattributed. Measured on a widened window (the connect deferred ~3 s behind a scalar subquery): without the wait all three arms report zero pool connection attempts while passing, with it all three report one. The wait costs nothing measurable -- 11.19 s mean against 11.54 s for the previous form over five runs each on one binary. Co-Authored-By: Claude Fable 5 <[email protected]>
kill_unbounded_timeout is the only arm exercising connect_timeout = 0, and it cancels, so it only proves the wait can be interrupted. A build that mistook the first 200 ms cancellation-polling slice for a real timeout would still satisfy it: the KILL is issued before the arm measures anything, so the pool reaches its terminal cancellation check with the flag already set and the arm still sees QUERY_WAS_CANCELLED well under its bound. Add unbounded_still_waits, which asserts the opposite direction. It waits for the connect to start, sleeps past several slices, and requires the query to still be in system.processes before anything cancels it. Verified with a mutant that gives the unbounded wait a 2 s budget: kill_unbounded_timeout stays green while the new arm fails 3/3, which is the vacuity the arm exists to close. A mutant that runs the budget check unconditionally reddens both. The connect-stage wait is extracted into wait_for_connect_start so the new arm shares it verbatim instead of duplicating the polling; run_and_cancel keeps its contract and propagates the same fixture return codes. Also record that the markers those arms read are logged at DEBUG: measured against a warning-level server, all six connect-stage arms report "connect never started" rather than passing vacuously.
Internal second-model review (click to expand)Independent cold review plus an adversarial second-model pass on the final tree, over six fix
Comment-to-code ratio on the Session id: cron:clickhouse-review-slot-8:20260810-100400 |
|
Workflow [PR], commit [4d0a231] Summary: ✅
AI ReviewSummaryThis PR makes MySQL connection and ping waits observe query cancellation, preserves cancellation exceptions through connection retries, and exempts remote cancellation cleanup from those checks. Reviewed head Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260810-085500 |
|
cc @novikd @kssenii, could you review this? A query cancelled while |
Style check `catch_all` flagged src/Common/mysqlxx/Connection.cpp:74: a `catch (...)` whose body is `return 0;` matches none of the rule's handled patterns (throw, tryLogCurrentException, LOG_*, current_exception, ...) and carried no suppression comment. Neither rethrowing nor logging is correct at that spot. The function is installed as MARIADB_OPT_IO_WAIT and is called from the vendored MariaDB connector's C frames, so it is declared noexcept and must swallow: letting an exception escape would unwind through C. The only throwing call inside the try is the cancellation predicate reached via CurrentThread::get(), and 0 is exactly the "wait failed" value the connector already handles, which is also what the timeout path returns. So this is the `// Ok:` case the rule provides for. The pre-existing comment above the try said the same thing, so it is folded into the new one at the decision site rather than stating it twice. No behaviour change: comments only.
|
|
||
| /// The last attempt has no next iteration to reach the check above, and the full pool below | ||
| /// can still return a connection, so a cancelled query would be served or misreported. | ||
| DB::CurrentThread::checkIfNotCancelled(); |
There was a problem hiding this comment.
PoolWithFailover::get now throws the real cancellation exception from here, but the MySQL database engine still rewrites it away. DatabaseMySQL::getCreateTableQueryImpl wraps any exception as CANNOT_GET_CREATE_TABLE_QUERY at src/Databases/MySQL/DatabaseMySQL.cpp:187-193, and the database factory does the same as CANNOT_CREATE_DATABASE at src/Databases/MySQL/DatabaseMySQL.cpp:665-668.
I rechecked the control flow in executeQuery.cpp: the pending-state remap at src/Interpreters/executeQuery.cpp:2002-2014 only runs after interpreter->execute() returns successfully, while the outer catch (...) at src/Interpreters/executeQuery.cpp:2134-2147 just rethrows whatever those callers wrapped. So SHOW CREATE TABLE and CREATE DATABASE ... ENGINE = MySQL against an unresponsive host can still come back as metadata errors instead of QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED.
Can we let cancellation exceptions escape unchanged here, or at least special-case QUERY_WAS_CANCELLED and TIMEOUT_EXCEEDED before wrapping the rest?
There was a problem hiding this comment.
You are right, and my earlier dismissal was wrong. I claimed the pending-state remap at
executeQuery.cpp:2002-2015 re-raises the cancellation code; it does not on this path.
interpreter->execute() is at :1956, so that block only runs when the interpreter RETURNS,
and an exception from the database engine travels the catch (...) at :2134, which logs and
rethrows what the caller wrapped.
Verified by running it rather than re-reading. Blackholed 192.0.2.1:3306 (a refused host
returns in 0.00 s and the probe would be vacuous; the control blocked for the full
connect_timeout), connect_timeout = 100, connection_max_tries = 1, two servers with
asserted distinct build IDs. Oracle is the top-level code the client receives, not a nested
one. max_execution_time = 5, so both columns are the same configuration:
| entrypoint | pre-fix 76422598dac0 |
with fix a2e66245a461 |
|---|---|---|
mysql() table function |
100.2 s, ALL_CONNECTION_TRIES_FAILED |
5.3 s, TIMEOUT_EXCEEDED |
SELECT through a MySQL database |
100.1 s, ALL_CONNECTION_TRIES_FAILED |
5.3 s, TIMEOUT_EXCEEDED |
SHOW CREATE TABLE |
200.1 s, CANNOT_GET_CREATE_TABLE_QUERY |
5.4 s, CANNOT_GET_CREATE_TABLE_QUERY |
CREATE DATABASE ... ENGINE = MySQL |
100.1 s, CANNOT_CREATE_DATABASE |
5.3 s, CANNOT_CREATE_DATABASE |
KILL QUERY at the same connect_timeout agrees: 3.4 s and QUERY_WAS_CANCELLED for the
first two, 3.5 s and 390 / 3.4 s and 501 for the two you named. So both of your
entrypoints keep the metadata code. The cancellation exception is present but only nested,
e.g. Code: 501 ... because Code: 394 ... Query was cancelled.
Two things I checked before deciding what to do about it. It is not a regression: pre-fix
those same sites wrapped ALL_CONNECTION_TRIES_FAILED into the same 390 / 501, so this
changes which exception is wrapped, not whether wrapping happens. And the latency fix does
reach them, which is the complaint in #79526: 200.1 s to 5.4 s and 100.1 s to 5.3 s.
I have corrected the description, which was the part that overstated the scope; it now names
which entrypoints deliver the cancellation code and which keep the metadata code. I am not
widening the diff here: making 390 / 501 preserve a cancellation code means teaching those
wraps to rethrow when getCurrentExceptionCode() is a cancellation, the way
BackupsWorker.cpp:128 does, which changes the MySQL database engine's error contract and
belongs with its owners rather than in a mysqlxx cancellation fix. Happy to do it here if a
reviewer prefers that.
CI finish ledger - 175902cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither is caused by this PR: the diff is confined to Session id: cron:our-pr-ci-monitor:20260810-173000 |
|
cc @alexey-milovidov you can look at these kill query failures fixes for the CI |
…llation # Conflicts: # src/Common/mysqlxx/Connection.cpp
The master merge moved contrib/mariadb-connector-c to a version whose mysql_options(MARIADB_OPT_IO_WAIT) writes through options.extension without checking it; the previous pin allocated it on demand. On a failed connect the connector frees the options and reallocates the extension, and if that calloc fails it returns with options.extension == nullptr. The guard destructor then runs while the ConnectionFailed exception unwinds and dereferences it. Reproduced by forcing that reallocation to return NULL under gdb on a refused mysql() connect: SIGSEGV in mysql_optionsv called from the guard destructor before, a normal ALL_CONNECTION_TRIES_FAILED after. The constructor is not affected: it runs after a successful mysql_init (which allocates the extension) or on an established connection. Also trims the comments this PR added in mysqlxx to the ones stating the connector's contract, which the code cannot show: the io-wait callback's timeout and return values, the catch-all's reason, and the null extension. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y's thread `replace_running_query` only flags the old query, which then cancels its pipeline on its own thread. `MySQLWithFailoverSource::onCancel` therefore acquired the connection for the remote `KILL QUERY` on a thread whose query is cancelled, and the cancellation check added to `PoolWithFailover::get` refused it. The remote query kept running, the old query stayed blocked reading its result, and the replacement failed with `QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING` after `replace_running_query_max_wait_ms`. Block query cancellation around that cleanup; the connect timeouts still bound it. The new integration test fails on the previous head and passes on master and with this change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ected The io-wait callback installed around `mysql_ping` fails the wait once the query is cancelled and the socket is not ready within one 200 ms slice. On a healthy link whose COM_PING reply is slow, `Pool::Entry::forceConnected` then reconnects (the handshake is fast, so the callback never fails it), pings again, and loops: a killed or timed-out query never returns. Check cancellation before reconnecting. `QueryCancellationBlocker`, used by `MySQLWithFailoverSource::onCancel`, still exempts the cleanup connection, and threads without a query are unaffected. Measured with a proxy that holds every COM_PING for 30 s: on the previous head the killed query was still running 40 s after KILL QUERY, with 60 new connections; with the fix it ends about 1 s after KILL QUERY with QUERY_WAS_CANCELLED (max_execution_time = 3: TIMEOUT_EXCEEDED after 4.1 s). Master waits out both pings (60 s) and then reports QUERY_WAS_CANCELLED. A cancellation that lands during that reconnect itself (after a ping failed for another reason) aborts the connect and surfaced as `ConnectionFailed`; recheck cancellation before rethrowing it, as `PoolWithFailover::get` does after its last attempt. With a proxy that drops the link at the second ping and stalls the next greeting, KILL QUERY returned Code 1000 `ConnectionFailed` and now returns QUERY_WAS_CANCELLED (master: `ConnectionFailed` after the 10 s connect_timeout). test_kill_query_during_slow_ping runs the COM_PING-holding proxy inside the node. It clears CLIENT_SSL in the server greeting so that the session stays in plain text. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 5ef96b7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261027-193015 |
…llation # Conflicts: # src/Common/mysqlxx/Connection.cpp # src/Common/mysqlxx/Pool.cpp
The style check now requires an event_time condition on every system.text_log query in a test, because a full scan of the log on a busy CI server exceeds max_rows_to_read of the test profile. The rows these queries look for are written by the test itself a few seconds earlier, so a 10 minute window keeps them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units10 translation units recompiled, 18 s compile time in total, 10 of them have a recent master baseline. |
Related: #79526
Related: #70857
Related: #113979
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
KILL QUERYandmax_execution_timenow take effect while a query is connecting to MySQL. Previously a query usingmysql()or aMySQLengine table against an unresponsive host stayed insystem.processeswithis_cancelled = 1for up toconnection_max_tries * connect_timeout.Description
mysql()infers its schema during query analysis, before any pipeline exists, so the connect blocks inpoll()inside the client library, where nothing reads the cancellation flag.Three changes in
src/Common/mysqlxx:Connection.cppinstalls aMARIADB_OPT_IO_WAITcallback that waits in 200 ms slices and checks cancellation between them, preserving the connector's ownEINTR,ETIMEDOUTand wait-indefinitely semantics. RAII scopes it tomysql_real_connectandmysql_ping, leaving post-connect I/O on the library's own wait.PoolWithFailover.cppchecks cancellation before each attempt, and once before the terminalALL_CONNECTION_TRIES_FAILEDthrow: the last attempt has no next iteration, so a cancellation there was reported as a connection failure.Pool.cppchecks cancellation beforePool::Entry::forceConnectedreconnects after a failed ping, and before it rethrows a failed reconnect: thepingguard also covers a healthy link's reply wait, so a cancelled query with a slow ping would reconnect forever.MySQLWithFailoverSource::onCancelsends its remoteKILL QUERYunderQueryCancellationBlocker: withreplace_running_querythe old query cancels itself on its own thread, where the pool check would refuse that connection and leave the remote statement running.Against a blackholed host with
connect_timeout = 100,KILL QUERYreturns in 2.4 s instead of 100 s, now asQUERY_WAS_CANCELLED;max_execution_time = 5in 5.3 s asTIMEOUT_EXCEEDED. Uncancelled behaviour is unchanged.This is the first half of #79526:
PoolWithFailover::getstill holds the mutex across the blocking connect, so I left it open. The cancellation code reaches the client frommysql()and from aSELECTthrough aMySQLdatabase;SHOW CREATE TABLEandCREATE DATABASE ... ENGINE = MySQLget the latency fix but still reportCANNOT_GET_CREATE_TABLE_QUERY/CANNOT_CREATE_DATABASE, since the database engine wraps every exception, as it did withALL_CONNECTION_TRIES_FAILEDbefore. Also not covered:timeout_overflow_mode = 'break'; the retry loop inPool::get; post-connect I/O; and the PostgreSQL, ODBC and MongoDB clients.Validation
Debug builds, distinct build IDs asserted in every arm (fix
194fda381c40, pre-fix76422598dac0).KILL, ct=100, tries=1ALL_CONNECTION_TRIES_FAILEDQUERY_WAS_CANCELLEDKILL, ct=100, tries=3ALL_CONNECTION_TRIES_FAILEDQUERY_WAS_CANCELLEDmax_execution_time=5, ct=100ALL_CONNECTION_TRIES_FAILEDTIMEOUT_EXCEEDEDALL_CONNECTION_TRIES_FAILEDKILL, ct=0 (wait forever)ALL_CONNECTION_TRIES_FAILEDQUERY_WAS_CANCELLEDKILL(manual, no test arm)ALL_CONNECTION_TRIES_FAILEDQUERY_WAS_CANCELLEDNew test
04775_mysql_connect_cancellationhas 8 arms, passes in ~18 s with the fix, times out at 600 s on the pre-fix binary, and passed 50 randomized runs.04507,02888and the 268 stateless tests matchingmysqlordictionarare green on both binaries.test_replace_query_waiting_on_mysql(QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING, green on master) andtest_kill_query_during_slow_ping(a proxy holds everyCOM_PING; the killed query kept reconnecting) fail on the previous head and pass with the fix.Reverting each part in turn: without the terminal check a single-try cancellation returns
ALL_CONNECTION_TRIES_FAILED; without the per-attempt check a cancelled query still starts all 3 attempts instead of 1; without slicing the fullconnect_timeoutlatency returns; forcing the bounded branch breaksconnect_timeout = 0; treatingEINTRas a failure aborts a valid connect on the first profiler signal (0.30 s instead of 1.09 s). MySQL database refresh and dictionary loads have no query context, where the checks are no-ops.Workflow [PR]
Sync PR [sync-upstream/pr/114142]