Skip to content

Make a MySQL connect cancellable so KILL QUERY and max_execution_time work - #114142

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:mysql-connect-cancellation
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:mysql-connect-cancellation

Conversation

@groeneai

@groeneai groeneai commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #79526
Related: #70857
Related: #113979

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

KILL QUERY and max_execution_time now take effect while a query is connecting to MySQL. Previously a query using mysql() or a MySQL engine table against an unresponsive host stayed in system.processes with is_cancelled = 1 for up to connection_max_tries * connect_timeout.

Description

mysql() infers its schema during query analysis, before any pipeline exists, so the connect blocks in poll() inside the client library, where nothing reads the cancellation flag.

Three changes in src/Common/mysqlxx:

  • Connection.cpp installs a MARIADB_OPT_IO_WAIT callback that waits in 200 ms slices and checks cancellation between them, preserving the connector's own EINTR, ETIMEDOUT and wait-indefinitely semantics. RAII scopes it to mysql_real_connect and mysql_ping, leaving post-connect I/O on the library's own wait.
  • PoolWithFailover.cpp checks cancellation before each attempt, and once before the terminal ALL_CONNECTION_TRIES_FAILED throw: the last attempt has no next iteration, so a cancellation there was reported as a connection failure.
  • Pool.cpp checks cancellation before Pool::Entry::forceConnected reconnects after a failed ping, and before it rethrows a failed reconnect: the ping guard also covers a healthy link's reply wait, so a cancelled query with a slow ping would reconnect forever.

MySQLWithFailoverSource::onCancel sends its remote KILL QUERY under QueryCancellationBlocker: with replace_running_query the 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 QUERY returns in 2.4 s instead of 100 s, now as QUERY_WAS_CANCELLED; max_execution_time = 5 in 5.3 s as TIMEOUT_EXCEEDED. Uncancelled behaviour is unchanged.

This is the first half of #79526: PoolWithFailover::get still holds the mutex across the blocking connect, so I left it open. The cancellation code reaches the client from mysql() and from a SELECT through a MySQL database; SHOW CREATE TABLE and CREATE DATABASE ... ENGINE = MySQL get the latency fix but still report CANNOT_GET_CREATE_TABLE_QUERY / CANNOT_CREATE_DATABASE, since the database engine wraps every exception, as it did with ALL_CONNECTION_TRIES_FAILED before. Also not covered: timeout_overflow_mode = 'break'; the retry loop in Pool::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-fix 76422598dac0).

arm pre-fix with fix
KILL, ct=100, tries=1 100.21 s, ALL_CONNECTION_TRIES_FAILED 2.43 s, QUERY_WAS_CANCELLED
KILL, ct=100, tries=3 300.31 s, ALL_CONNECTION_TRIES_FAILED 2.41 s, QUERY_WAS_CANCELLED
max_execution_time=5, ct=100 100.18 s, ALL_CONNECTION_TRIES_FAILED 5.32 s, TIMEOUT_EXCEEDED
no cancellation, ct=2 2.10 s, ALL_CONNECTION_TRIES_FAILED 2.12 s, same error
KILL, ct=0 (wait forever) 132.94 s, ALL_CONNECTION_TRIES_FAILED 2.28 s, QUERY_WAS_CANCELLED
ct=0, no cancellation 133.62 s 135.17 s, no early failure
warm pool broken, then KILL (manual, no test arm) 200.25 s, ALL_CONNECTION_TRIES_FAILED 5.39 s, QUERY_WAS_CANCELLED

New test 04775_mysql_connect_cancellation has 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, 02888 and the 268 stateless tests matching mysql or dictionar are green on both binaries. test_replace_query_waiting_on_mysql (QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING, green on master) and test_kill_query_during_slow_ping (a proxy holds every COM_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 full connect_timeout latency returns; forcing the bounded branch breaks connect_timeout = 0; treating EINTR as 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]

groeneai and others added 5 commits August 9, 2026 22:40
… 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Independent cold review plus an adversarial second-model pass on the final tree, over six fix
rounds. This round: 0 blockers, 0 majors agreed, 1 major disagreed with evidence, 3 nits.

# Finding Verdict
⚠️ The MySQL database engine's catch (...) sites suppress or translate the cancellation exception the pool now throws (DatabaseMySQL.cpp:104 tolerant on ATTACH, :187 to CANNOT_GET_CREATE_TABLE_QUERY, :665 to CANNOT_CREATE_DATABASE). Disagreed. The catches are type-agnostic and do swallow or replace it, but the top-level code is still a cancellation code: both new checks read the same is_killed flag as executeQuery.cpp:2002-2015, which re-raises QUERY_WAS_CANCELLED or TIMEOUT_EXCEEDED after the interpreter returns. And nothing regresses: PoolWithFailover::get had no cancellation checks before and threw ALL_CONNECTION_TRIES_FAILED, which those same sites already translated, so this changes which exception is translated and how long it takes to arrive, not whether translation happens. The tolerant ATTACH is intended and pinned (04210_show_remote_databases_in_system_tables.sql:19 says so and asserts it succeeds against an unreachable host). The database engine is outside this change's scope.
💡 On a failed connect the connector frees options.extension on its error path, so the RAII guard's destructor allocates a replacement just to store a null callback. Noted. One allocation per failed connect, freed again by ~Connection; no leak. Correcting an earlier round of this review, which said the failure path keeps the options because CLIENT_REMEMBER_OPTIONS is set: that flag is not set here, since client_flag is zero after mysql_init, so mysql_close_options does run.
💡 The ping side effect noted in the description has a further consequence: a cancellation inside that wait makes mysql_ping return false, so Pool::tryGet drops the healthy pooled connection (Pool.cpp:257) rather than reusing it. Noted. One warm connection, on a query that is being cancelled anyway.
💡 int remaining = timeout; is initialised on the unbounded path, where it is never read. Noted.
💡 Candidate blocker of my own: MARIADB_OPT_IO_WAIT goes through the connector's CHECK_OPT_EXTENSION_SET, which on a fresh allocation also sets tls_allow_invalid_server_cert, and that branch is the live one here (DEFAULT_SSL_VERIFY_SERVER_CERT is undefined in this build). Dropped after verification: unreachable from these call sites, because mysql_options(MYSQL_OPT_LOCAL_INFILE, ...) one line earlier already allocates the extension, on every connect, with or without this change.
💡 Re-checked rather than assumed: each of the 8 test arms fails on a reverted fix, five of them asserting both latency and error identity; the new unbounded_still_waits arm is reddened 3/3 by a mutant that leaves kill_unbounded_timeout green, so it is not a duplicate of it; max_execution_time, connect_timeout and timeout_overflow_mode are absent from the settings randomizer, and the only global max_execution_time in the test configs is Fast-test-only, which this test is tagged out of; the pool log line the fixture waits on is visible at the CI logger level, and a coarser level turns the arms into loud failures rather than silent passes; the test is parallel-safe without no-parallel; the invariant carriers I enumerated independently match the code, and the paths with no query context are no-ops by construction. No action.

Comment-to-code ratio on the src/ diff: 13 comment lines against 90 code lines, longest block
3 lines.

Session id: cron:clickhouse-review-slot-8:20260810-100400

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4d0a231]

Summary: ✅


AI Review

Summary

This 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 4d0a231a8808ee2b924d5d3e1827ef190811c586, the complete diff, connector implementation, callers, tests, and all prior discussion. No actionable findings remain within the documented scope. The earlier remote-cleanup and ping-retry regressions are fixed; the existing database-engine exception wrapping is an accepted scope limitation.

Missing context / blind spots
  • ⚠️ Current-head build and runtime CI is still in progress, and no local ClickHouse build is available for independent execution. Archived targeted stateless results show 50 successful runs of 04775_mysql_connect_cancellation; targeted integration results show all six MySQL cancellation tests passing, including both regression tests. Completed current-head CI would close the remaining validation gap.
Final Verdict

Status: ✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on the pre-fix binary: SELECT * FROM mysql('192.0.2.1:3306','db','tbl','u','p', SETTINGS connect_timeout=100, connection_max_tries=1) then KILL QUERY from a second client. 192.0.2.1 drops SYN, so the connect really blocks; a refused host returns in 0.000 s and the repro is vacuous.
b Root cause explained? Schema inference runs in QueryAnalyzer::resolveTableFunction -> fetchTablesColumnsList -> PoolWithFailover::get -> mysql_real_connect, before a pipeline exists. Cancellation is armed (QueryStatus inserted at executeQuery.cpp:1623, before InterpreterFactory::get at :1883) but nothing on that path reads it, so the thread stays in poll() for connection_max_tries * connect_timeout.
c Fix matches root cause? Yes: the blocking wait itself becomes interruptible, and the retry loop reads cancellation. No widened bound, no no-random-* tag, no guard masking an upstream bug.
d Test intent preserved / new tests added? New 04775_mysql_connect_cancellation, 8 arms: error identity, latency, two separate connect_timeout = 0 arms (one that it stays killable, one that it does not end on its own), a retry-count assertion read from system.text_log, a MySQL engine table cancelled from inside the pipeline, max_execution_time, and an uncancelled control that must still consume its timeout. Each arm was checked to be a live oracle by deleting the check it pins and confirming that arm reddens: deleting the per-attempt check reddens kill_retry_count alone, and deleting the terminal check reddens all four single-attempt arms, which is the expected blast radius since that check is their last cancellation checkpoint. The dedicated unbounded_still_waits arm asserts the unbounded wait is still in system.processes after several cancellation-polling slices, before anything cancels it; a mutant that gives that wait a 2 s budget leaves kill_unbounded_timeout green while reddening the new arm 3 of 3, which is why the two arms are separate rather than one. The arms that cancel a connect wait for the pool's own per-attempt log line before cancelling, so they cannot pass without having entered a connection attempt. No existing test weakened. 04507_mysql_connect_timeout_under_profiler and 02888_system_tables_with_inaccessible_table_function green on both binaries.
e Both directions demonstrated? Yes. Test level: passes in ~12.5 s with the fix, fails at 600 s (timeout) on the pre-fix binary. Query level: 100 s -> 2.4 s (1 try), 300 s -> 2.4 s (3 tries), and max_execution_time = 5 100 s -> 5.3 s. Retry count after cancellation: 1 with the fix, 3 without. Build IDs asserted per arm via SELECT lower(buildId()). 50 randomized runs green. The test's own race against the connect was also shown in both directions: with the connect deliberately deferred by 3 s, cancelling on the process row alone reproduces a red kill_retry_count, and a kill_engine_table plus all three kill_arm arms that pass without ever connecting, 3 of 3 each, while waiting for the connect to start produces none of those.
f Fix is general across code paths? Both blocking sites on the acquisition path are covered: Connection::connect and Connection::ping (which reconnects via mariadb_reconnect when MYSQL_OPT_RECONNECT is set, the default), plus per-attempt and terminal checks in the retry loop. Deliberately out of scope and stated in the description: post-connect read/write waits, the share_connection pool wait, the connector's pre-EINPROGRESS retry loop, and the sibling PostgreSQL/ODBC/MongoDB clients.
g Fix generalizes across inputs (params/datatypes/wrappers)? connect_timeout 0, 1, 2, 3, 5, 30, 100; connection_max_tries 1 and 3; KILL QUERY and max_execution_time; cold connect and warm-pool reconnect; with and without the query profiler. connect_timeout = 0 (wait indefinitely) is covered by its own branch and asserted from both sides by two independent arms: it must stay killable, and it must not end on its own. Note the connector maps connect_timeout = 0 to -1 before the wait sees it, so the unbounded path is a genuinely distinct branch rather than a zero-valued bounded one.
h Backward compatible? Yes. No setting default changed and no format or serialization change, so no SettingsChangesHistory.cpp entry. The only behaviour change is that a cancellation which previously did nothing now returns QUERY_WAS_CANCELLED or TIMEOUT_EXCEEDED, which is the documented contract being honoured.
i Invariants and contracts preserved? The callback is noexcept and wrapped in catch (...), since it is invoked from C; verified by making the cancellation check throw unconditionally, after which the server stays up and the query fails normally. RAII clears the hook on throwing paths, so post-connect I/O keeps the library's own wait. The connector's EINTR re-poll on the remaining budget and its ETIMEDOUT on expiry are both preserved. Both cancellation checks are no-ops without a thread status, verified on the MySQL database refresh and dictionary load paths. The arms' connect-stage gate reads a DEBUG-level log line; measured against a warning-level server, all six connect-stage arms report connect never started and the run goes red, so a coarser logger level can never turn them into silent passes.

Session id: cron:clickhouse-impl-slot-5:20260810-085500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @kssenii, could you review this? A query cancelled while mysql() is connecting stayed in system.processes until the connect timed out once per retry, because schema inference blocks in poll() inside the client library during analysis, where nothing reads the cancellation flag; this installs a cancellation-aware MARIADB_OPT_IO_WAIT callback scoped to the connect and checks cancellation in the pool's retry loop.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 175902c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Hung check failed, possible deadlock found cancelled DROP TABLE prometheus never returns from DatabaseCatalog::waitTableFinallyDropped; the test-database teardown convoys behind it on the DDL guard (trunk bug, reproduced on master) a fix task owns it (root cause proven and written up at #114064 (comment), no fix PR yet); fixing-PR link to follow here
Stress test (arm_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer indirect-only leaks whose blocks carry MaterializedCTE + ConstantNode + QueryTreeBuilder frames (one MaterializedCTE/QueryPlan retain cycle; STID is a report-shape hash, not a root cause) fixing PR 113397 (external, open) - same retain cycle, weak-ptr fix in MaterializingCTEStep + addPlansForMaterializingCTEs

Neither is caused by this PR: the diff is confined to mysqlxx connect cancellation and its own
04775 test, so it cannot reach TimeSeries teardown or analyzer/CTE plan construction. The
hung root is is_cancelled = 1 at 928.74s with shorter DDL-guard victims behind it; the leak
blocks were frame-checked for the CTE cycle rather than matched on STID.

Session id: cron:our-pr-ci-monitor:20260810-173000

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov you can look at these kill query failures fixes for the CI

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mysql MySQL-specific integration (table engine/function/protocol mapping). label Sep 4, 2026
groeneai and others added 2 commits October 27, 2026 12:01
…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]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 27, 2026
Comment thread src/Common/mysqlxx/PoolWithFailover.cpp Resolved
…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]>
Comment thread src/Common/mysqlxx/Connection.cpp Resolved
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5ef96b7

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, parallel) / 05304_json_shared_typed_paths_replication_backup flaky, not from this PR: the test read replica p2 before it had fetched the part inserted into p1, so the four p2 rows printed 0; 0 of 3 reruns failed #127914 (mine, open)
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 273 of 277 runs since 2026-10-26 22:00 UTC are red the same way, on 231 PRs #126200 (mine, open)
PR praktika rollup of the rows above #127914 and #126200 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-193015

groeneai and others added 2 commits November 11, 2026 14:20
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4d0a231a8 with master 0e42176d2 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.69, programs/clickhouse-keeper ×0.60 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.1 s 13.1 s +8.9 s (+210%)
Compile time of recompiled translation units

10 translation units recompiled, 18 s compile time in total, 10 of them have a recent master baseline.

Job report

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

can be tested Allows running workflows for external contributors comp-mysql MySQL-specific integration (table engine/function/protocol mapping). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants