Skip to content

Honour query cancellation in the ReadWriteBufferFromHTTP retry loop - #112144

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-xdbc-bridge-uninterruptible-read
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-xdbc-bridge-uninterruptible-read

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #107941
Related: #111930

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Makes KILL QUERY, and max_execution_time with the default timeout_overflow_mode = 'throw', take effect promptly for reads over HTTP (the url, odbc and jdbc table functions, the URL table engine, the web disk, and HTTP dictionaries whose source runs on the query's own thread). ReadWriteBufferFromHTTP retried an unresponsive server up to http_max_tries times, sleeping up to http_retry_max_backoff_ms between attempts, without ever checking whether the query had been cancelled, so a cancelled query could keep working for several minutes.

Description

ReadWriteBufferFromHTTP::doWithRetries never consulted query cancellation, and the backoff between attempts is an uninterruptible sleepForMilliseconds. Against a server that accepts the connection but does not answer, every attempt runs into its own receive timeout, so the worst case is http_max_tries * http_receive_timeout plus about 33 seconds of accumulated backoff: about 330 seconds with the product defaults (http_max_tries = 10, http_receive_timeout = 30), and about 630 seconds under the CI test profile, which sets http_receive_timeout = 60. Throughout that window KILL QUERY and max_execution_time have no effect, and a pipeline worker plus two waiter threads stay occupied. PipelineExecutor observes cancellation only between tasks, so it cannot interrupt this single task either.

The fix adds two CurrentThread::checkIfNotCancelled calls on the retry path only: one after the failed attempt has been classified as retriable, one after the backoff sleep. This is the same shape already used by ZooKeeperRetriesControl in ZooKeeperRetries.h and by the S3 client in S3/Client.cpp.

Because both checks are on the retry path, the attempt that is already in flight when cancellation arrives still runs to its own receive timeout. The worst-case window therefore shrinks from the full retry budget to a single http_receive_timeout plus the current backoff, roughly 40 seconds with the defaults, rather than to zero. Making the in-flight wait itself interruptible is a larger change and is the subject of #104929.

The checks observe cancellation through QueryStatus::throwIfKilled, which requires the query to have been marked as killed. KILL QUERY always marks it, and so does a max_execution_time timeout with the default timeout_overflow_mode = 'throw'. With timeout_overflow_mode = 'break' the cancellation checker deliberately does not mark the query (it calls checkTimeLimit, which only returns false), so the retry loop is unaffected in that mode. Returning a partial result from a read that never produced one would be a different change, so the scope is stated rather than widened.

Both checks sit after the attempt has thrown and been classified, so a genuine first-attempt error still propagates as itself. That matters here: the earlier attempt at this fix (#102801, reverted in 4cf703f916c496) checked at the top of every attempt, which suppressed CANNOT_PARSE_INPUT_ASSERTION_FAILED and made 02270_errors_in_files_s3 flaky. That test's url() assertion was re-run against this build and is unchanged.

Because the primitive is thread-local, no constructor parameter or per-caller wiring is needed, so every ReadWriteBufferFromHTTP consumer is covered rather than just StorageURLSource, and all three retry entry points (nextImpl, readBigAt, the getFileInfo HEAD probe) share the single guarded loop. Threads with no query attached are unaffected: checkIfNotCancelled returns early when there is no current thread status, and throwIfQueryCanceled returns early when there is no thread group.

That last property also bounds what this change can reach, which is why the entry above says "whose source runs on the query's own thread". A direct dictionary calls its source inline on the query thread, and the flat/hashed layouts are loaded through ExternalLoader, which captures the requesting query's thread group (CurrentThread::getGroup in startLoading, restored by ThreadGroupSwitcher in doLoading), so both observe cancellation. The cache family (cache, ssd_cache and their complex_key_ variants) instead hands the update to a persistent worker of its own CacheDictionaryUpdateQueue pool, which attaches no thread group, while the query thread waits separately for up to query_wait_timeout_milliseconds (60 seconds by default). On that path the new checks are no-ops and the retry loop can outlive the waiting query, exactly as before this change. Propagating cancellation into those detached update units is a separate change in a different component and is tracked separately; nothing here regresses it.

Found while triaging a Stress test (amd_msan) hung check where a cancelled odbc() query kept retrying for about nine minutes after max_execution_time = 60 fired: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111930&sha=84788620b746b5c00af1121143172495ae3f13fe&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Relationship to open pull requests in this area, for reviewers deciding where the fix belongs:

  • Improve canceling queries with url() function #104089 addresses the same defect by threading a CheckCancelled callback through the ReadWriteBufferFromHTTP constructor, BuilderRWBufferFromHTTP and StorageURLSource. This change is disjoint from it: it touches only ReadWriteBufferFromHTTP.cpp, changes no signatures, and uses CurrentThread::checkIfNotCancelled, which did not exist when Improve canceling queries with url() function #104089 was written (added in b82d83174e9956, 2026-07-03).
  • Throw cancellation in ReadBuffer::next #109785 adds a cancellation check at the entry of ReadBuffer::next. It cannot shorten this hang, because the whole retry loop runs inside a single next call that was already entered before cancellation. The two are complementary, and this check would respect CancellationChecksBlockerInThread if that lands.

No new setting and no default change, so SettingsChangesHistory.cpp needs no entry.

groeneai and others added 3 commits July 27, 2026 07:01
ReadWriteBufferFromHTTP::doWithRetries loops up to http_max_tries times and
never consults query cancellation, and the backoff between attempts is an
uninterruptible sleepForMilliseconds. Against a peer that accepts the connection
but does not answer, the worst case is (http_max_tries - 1) * http_receive_timeout
plus the accumulated backoff - about 570 seconds with the defaults - during which
KILL QUERY and max_execution_time have no effect and a pipeline worker plus two
waiter threads stay occupied. PipelineExecutor observes cancellation only between
tasks, so it cannot interrupt this single task either.

Add two CurrentThread::checkIfNotCancelled() calls on the retry path only: one
after the failed attempt has been classified as retriable, one after the backoff
sleep. Same shape as ZooKeeperRetriesControl and the S3 client. Because both sit
after the attempt threw and after the last-attempt/non-retriable rethrow, a
genuine first-attempt error still propagates as itself - the failure mode that
got the earlier attempt at this fix reverted in 4cf703f, which suppressed
CANNOT_PARSE_INPUT_ASSERTION_FAILED and made 02270_errors_in_files_s3 flaky.

The primitive is thread-local, so no constructor parameter or per-caller wiring
is needed: every ReadWriteBufferFromHTTP consumer is covered rather than just
StorageURLSource, and all three retry entry points (nextImpl, readBigAt, the
getFileInfo HEAD probe) share the single guarded loop. Threads with no query
attached are unaffected, since both checkIfNotCancelled and throwIfQueryCanceled
return early without a thread status or thread group.

Found while triaging a Stress test (amd_msan) hung check where a cancelled
odbc() query kept retrying for about nine minutes after max_execution_time = 60
had already fired.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review round on the previous commit found that the regression test could not
tell the two `CurrentThread::checkIfNotCancelled` calls in
`ReadWriteBufferFromHTTP::doWithRetries` apart: with the settings it used, the
attempt already in flight when cancellation arrived always outlived the
cancellation instant, so the check before the backoff sleep always fired and
the check after it was never reached. Deleting the second call left the test
green.

The test now has three sections and each check is pinned by a different one.
Cancelling during attempt 1's receive (a 20s backoff) pins the check before the
sleep through the elapsed time; cancelling during a 9s backoff pins the check
after the sleep through the exact number of requests sent, which stays 1 only
if the loop refuses to start another attempt when the sleep ends. Every section
reads `ProfileEvents['ReadWriteBufferFromHTTPRequestsSent']` back from
`system.query_log` and pins it in the reference, and pins
`http_make_head_request = 0` so that count is not perturbed by the HEAD probe,
which the stress runner randomizes. Verified by building the three mutants
separately: removing only the first call fails the read section alone, removing
only the second fails the backoff section alone and on the request count alone,
and removing both fails all three.

The KILL section's stderr file now interpolates the test database into its name.
`CLICKHOUSE_TMP` is the shared suite directory whenever the runner is given
`--database`, which is the stress configuration, so two concurrent copies of the
test truncated and unlinked one another's file.

Also records in the source comment that these checks observe cancellation only
once the query is marked as killed, so `max_execution_time` with
`timeout_overflow_mode = 'break'` does not stop the loop. That mode asks for a
partial result, and a read that never produced one has none to return, so the
limitation is documented rather than widened into a behaviour change.

ClickHouse#111930 below is the run whose CI report surfaced the hang, not its cause.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111930&sha=84788620b746b5c00af1121143172495ae3f13fe&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Related: ClickHouse#111930
Related: ClickHouse#107941

Co-Authored-By: Claude Fable 5 <[email protected]>
Both sections of the regression test derived the cancellation instant from a
clock that starts before the retry loop exists: max_execution_time is armed in
ProcessList::insert, before planning, and the KILL readiness poll only proved
that the request counter had been incremented just before the blocking receive.
On a loaded runner that made the read section fail on a correct build when
startup exceeded its 1s budget, let the backoff section's cancellation land in
attempt 1's read (so the post-sleep check was again pinned by nothing while the
section still passed), and made the KILL section's bound reject the legitimate
post-sleep path.

The read section now has a 5s cancellation budget against a 10s receive timeout,
so cancellation is inside attempt 1's read by construction. The backoff section
observes its phase instead of assuming it: the query runs in the background and
is killed only once system.processes reports one request sent and more elapsed
time than the receive timeout, which means attempt 1 has already failed and the
loop is inside a 20s sleep with about 16s of delivery slack. The exact request
count is then the discriminator, with no timing dependence, and a pinned
"backoff phase observed" line stops a run that never reached the backoff from
passing vacuously. The old timeout-driven backoff section and the KILL section
became the same mechanism, so they are one section.

No production code changed in this commit.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111930&sha=84788620b746b5c00af1121143172495ae3f13fe&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Related: ClickHouse#111930

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 17 adjudicated findings) - click to expand

Before opening, this change was reviewed by a second model against the ClickHouse review skill, in
three rounds (one per commit). Every finding was adjudicated against the code; the two source-level
blockers raised in round 1 are recorded below with the evidence that settled them.

Rounds: r0 7 findings (2 blocker / 2 major / 3 nit), r1 5 (3 major / 2 nit), r2 5 (1 major / 4 nit).
Verdicts: 11 accepted and fixed, 2 disagreed with evidence, 4 dropped as duplicates of a finding
already counted in the same round.

Accepted and fixed

# Finding What changed
❌ timeout_overflow_mode = 'break' never marks the query killed, so both checks are no-ops in that mode, which the change did not state Verified end to end (CancellationChecker::cancelTask calls checkTimeLimit instead of cancelQuery, so is_killed stays false and throwIfKilled returns immediately). The limitation is now stated in the changelog entry, in the description and in the source comment. The alternative (returning a partial result) was rejected: a read that never produced one has nothing to return.
⚠️ The regression test could not tell the two checks apart: with the original settings the in-flight attempt always outlived the cancellation instant, so the check before the backoff sleep always fired and deleting the one after it left the test green The test now pins each check with a separate section, and each was verified by building the two mutants separately: deleting only the first fails the read section alone, deleting only the second fails the backoff section alone and on the request count alone.
⚠️ Both sections derived the cancellation instant from a clock that starts before the retry loop exists (max_execution_time is armed in ProcessList::insert, before planning), so on a loaded runner the backoff section's cancellation could land in the read instead and the second check would again be pinned by nothing while the section still passed The backoff section now observes its phase instead of assuming it: it waits until the server reports one request sent and more elapsed time than the receive timeout, then issues KILL QUERY. The exact request count (1 vs 2) is the discriminator, with no timing dependence, and a pinned backoff phase observed line stops a run that never reached the backoff from passing vacuously.
⚠️ The test wrote a fixed-basename temp file under CLICKHOUSE_TMP, which is the shared suite directory whenever the runner is given --database (the stress configuration), so two concurrent copies truncated and unlinked one another's file Every temp path is now scoped with the test database name and cleaned up in the EXIT trap; verified with two concurrent copies.
⚠️ The changelog entry claimed coverage of "HTTP dictionaries" without qualification, but the cache family runs its source in a detached update-pool worker with no thread group, where the checks are no-ops The entry now says "HTTP dictionaries whose source runs on the query's own thread", and the description names the covered paths (direct inline, flat/hashed through ExternalLoader, which captures the requester's thread group) and the uncovered cache family with its mechanism. Propagating cancellation into those detached update units is a separate change in a different component and is tracked separately; nothing here regresses it.
💡 Worst-case arithmetic in the description used (http_max_tries - 1) * http_receive_timeout, but the loop performs http_max_tries receives Recomputed from the loop structure: about 330 seconds at product defaults and about 630 under the CI profile, with 32.7 seconds of accumulated backoff.
💡 Description overstated the residual window as zero, and the changelog was written in past tense against the changelog guidelines Residual is now stated explicitly (one http_receive_timeout plus the current backoff, roughly 40 seconds at defaults); entry rewritten in present tense.

Disagreed, with evidence

# Finding Why it was not accepted
❌ Callers with a catch (...) around this read would swallow the new cancellation exception The necessary step is that this change creates the swallowing. Every cited catch (...) is byte-identical on master and already swallows the same class of DB::Exception; this change makes each of those paths strictly faster (one in-flight attempt per failover option instead of a full retry budget), and StorageURL's handler rethrows unchanged when there is a single option, which is the shape the reported odbc() case takes.
💡 The backoff section's phase predicate compares absolute elapsed time, so it could in principle mis-identify the phase if server-side startup exceeded four seconds Measured rather than assumed: system.query_log on three independent runs gives total durations of 22005/22048/22017 ms against a 2000 ms receive plus a 20000 ms sleep, so startup is about 5 to 50 ms, three orders of magnitude below the threshold. The stronger form (recording the elapsed value at the first observed request and waiting one receive timeout from that) would add a second state variable and a second failure mode for no measurable gain; it is recorded for whoever next touches this test.

Noted, not blocking

The two system.query_log lookups in the test filter by query_id without a time predicate. In-tree
convention is to add one (152 of the 166 stateless shell tests that read system.query_log do), and
it is worth adding next time this file is touched; the realized risk is low, since a 30-day sweep of
CI failures that hit the row-read limit finds no system.query_log reads among them.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A python listener accepts the TCP connection and never answers; SELECT * FROM url('http://127.0.0.1:<port>/','TSV','c1 UInt64') SETTINGS http_receive_timeout = 10, http_max_tries = 3, max_execution_time = 5, http_retry_initial_backoff_ms = 20000, http_retry_max_backoff_ms = 30000, http_make_head_request = 0. Every attempt ends in a receive timeout after exactly http_receive_timeout, so the budget is fixed (3 x 10s receive + 50s backoff), not probabilistic: measured server-side durations are 10.0s with the fix and 80.2s without it.
b Root cause explained? ReadWriteBufferFromHTTP::doWithRetries never consults query cancellation, and the inter-attempt sleepForMilliseconds is uninterruptible. A query cancelled during attempt N therefore still runs attempts N+1..http_max_tries. PipelineExecutor observes cancellation only between tasks, so it cannot interrupt this single task either, which is why the cancelling thread and the pool wait() show up as blocked waiters.
c Fix matches root cause? Yes: two CurrentThread::checkIfNotCancelled() calls inside the loop that ignores cancellation, mirroring ZooKeeperRetriesControl (ZooKeeperRetries.h:229/:238) and S3/Client.cpp:422/:711. No timeout widened, no retry budget shrunk, no test setting pinned.
d Test intent preserved / new tests added? No existing test modified. New 04648_url_retry_loop_honors_cancellation.sh has two sections, and each of the two added checks is pinned by exactly one of them. --- cancelled during a read --- (max_execution_time = 5 against a 10s receive timeout and a 20s backoff) pins the pre-sleep check via elapsed time: cancellation is observed while attempt 1 is still reading. --- KILL QUERY during a backoff --- pins the post-sleep check via the exact request count, and its phase is observed rather than assumed: the query runs in the background and is killed only once system.processes reports one request sent AND more elapsed time than the 2s receive timeout, so attempt 1 has provably already failed and the loop is inside the 20s backoff (measured accepted pair requests=1 elapsed=6s, leaving about 16s of delivery slack). It also covers the second cancel reason (QUERY_WAS_CANCELLED instead of TIMEOUT_EXCEEDED). Both sections read ProfileEvents['ReadWriteBufferFromHTTPRequestsSent'] back from system.query_log and pin it in the reference, with http_make_head_request = 0 so the count is exact under the stress runner's randomization; the wall-clock lines are cheap guards and are never exact durations, and a backoff phase observed line is pinned so a run that never reached the backoff cannot pass vacuously. Temp-file names interpolate $CLICKHOUSE_DATABASE, because CLICKHOUSE_TMP is the shared suite directory in the stress --database=test_{i} regime.
e Both directions demonstrated? Yes, Build-ID-verified for every build. Fixed build 814377d4: the test passes in 33.8s (server-side 10.0s for the read section, 22.0s for the backoff section). Three separate mutations, each rebuilt and run on its own, with predictions written before any build (mutation-predictions-r2.md), show that each check is pinned by a different section and that neither assertion is vacuous: deleting only the pre-sleep check (e6ee3e7c) fails the read section alone (kept retrying for 30197 ms, backoff section still passes); deleting only the post-sleep check (2a24055d) fails the backoff section alone and on the request count alone (requests sent: 2 instead of 1); deleting both (ac187e64) fails both sections (3 and 4 requests, 80.2s and 88.3s, POCO_EXCEPTION instead of the cancellation error), which is also the master-HEAD behaviour the Bugfix Validation job needs. Every mutation failed on exactly the predicted line, none for an unrelated reason. Restoring reproduced Build ID 814377d4 bit-identically with a byte-identical source md5. 50/50 randomized runs pass at 33.52-33.99s each (bound 180s), and four concurrent copies (--test-runs 4 --jobs 4) all pass at 33.8-34.0s.
f Fix is general across code paths? Yes, and this drove the layer choice. doWithRetries is the single retry loop behind all three entry points (nextImpl, readBigAt, the getFileInfo HEAD probe), so one guard covers them; a guard in nextImpl alone would have missed two. Because the primitive is thread-local, every ReadWriteBufferFromHTTP consumer whose read runs on the query's own thread is covered (URL/URLCluster/XDBC, the web disk, RestCatalog, DataPartsExchange, bridge helpers, and direct-layout plus ExternalLoader-driven HTTP/XDBC dictionaries), not just StorageURLSource. The cache dictionary family is the documented exception: it runs its source in a detached CacheDictionaryUpdateQueue worker that attaches no thread group, so the checks are no-ops there; that is stated in the PR description and tracked separately. Sibling loops in S3/Client.cpp already carry the same guard; ReadBufferFromS3's own retry loop is a separate root cause and deliberately out of scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? No datatype axis (the change handles no data). The axes that exist are covered: both CancelReason branches of throwProperExceptionIfNeeded are asserted; both terminal branches of the loop are exercised (retriable now cancels; last-attempt/non-retriable unchanged, shown by the non-cancelled control below and by 02270); boundary http_max_tries = 1 never enters the retry branch, so a single-attempt read is unchanged. A NOT-cancelled query with http_max_tries = 4 still records exactly 4 ReadWriteBufferFromHTTPRequestsSent and still propagates the original POCO_EXCEPTION.
h Backward compatible? Yes. No setting added or default changed, so no SettingsChangesHistory.cpp entry; no format or protocol change. The only behaviour change is that an already-cancelled query now fails promptly with the accurate error code, which is what KILL QUERY and max_execution_time already promise.
i Invariants and contracts preserved? Yes. Both checks are placed after the catch blocks and after the last_attempt || !is_retriable rethrow, so a non-cancelled failure keeps its own exception type - the failure mode that got the first attempt at this fix reverted is structurally impossible, and 02270_errors_in_files_s3's url() assertion (CANNOT_PARSE_INPUT_ASSERTION_FAILED with the failing URL in the message) was re-run against this build and is unchanged. readBigAt's chassert(total_bytes_copied == initial_n || is_canceled) sits after the doWithRetries call, so a throw unwinds past it. getFileInfo catches only HTTPException and tryGetFileSize only HTTP/network/Poco IO exceptions, so a cancellation DB::Exception propagates instead of being swallowed into an empty file info or nullopt. No method in this header is noexcept and no lock is held across the new calls. Threads without a query cannot start throwing: checkIfNotCancelled returns early with no thread status, throwIfQueryCanceled returns early with no thread group, background merge/mutate groups never install the predicate, and getProcessListElementSafe returns empty without a process-list element.

Session id: cron:clickhouse-review-slot-53:20260727-140001

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @alexey-milovidov — could you review this? ReadWriteBufferFromHTTP::doWithRetries never consulted query cancellation and its inter-attempt backoff is an uninterruptible sleep, so a cancelled url()/odbc() read kept retrying for the full http_max_tries budget (about 330 s at product defaults, 630 s under the CI profile) while KILL QUERY and max_execution_time had no effect; this adds two CurrentThread::checkIfNotCancelled calls on the retry path only, so a genuine first-attempt error still propagates as itself.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [99d1e9c]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, 6/8) FAIL
test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming FAIL cidb

AI Review

Summary

This PR adds CurrentThread::checkIfNotCancelled on the retriable path of ReadWriteBufferFromHTTP::doWithRetries and a focused stateless regression test, which does fix prompt cancellation for the single-URI retry loop itself. I am not approving it as-is because the user-facing contract in the PR body and changelog still overstates coverage: the multi-URL failover paths above ReadWriteBufferFromHTTP continue treating cancellation as an ordinary endpoint failure.

Findings

⚠️ Majors

  • [src/IO/ReadWriteBufferFromHTTP.cpp:395, src/Storages/StorageURL.cpp:637-656, src/Disks/IO/ReadBufferFromWebServer.cpp:123-183] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112144#discussion_r3659259278] The new checks only stop one URI's internal retry budget. When url() / ENGINE = URL / web disk are given multiple URL options, the outer failover loops still catch the DB::Exception from CurrentThread::checkIfNotCancelled() and continue with the next candidate. In StorageURLSource that can also remap the original cancellation to NETWORK_ERROR after the last option fails. So the PR does not yet make cancellation "take effect promptly" for the whole surface promised by the description and changelog.
    Suggested fix: treat cancellation (QUERY_WAS_CANCELLED, TIMEOUT_EXCEEDED, or an explicit killed-query check) as terminal in those outer failover loops instead of continue; if that is intentionally out of scope, narrow the PR description and changelog entry to exclude multi-URL / brace-expanded failover forms.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either propagate cancellation through the multi-URL failover loops, or narrow the public contract so the PR only claims the single-URI retry-loop improvement it actually implements.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
/// as itself, and a cancelled query must not start another attempt. This observes
/// cancellation only once the query is marked as killed, so `max_execution_time` with
/// `timeout_overflow_mode = 'break'` (which does not mark it) does not stop the loop.
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.

These checkIfNotCancelled calls only stop the per-URI retry loop. The callers that fan out across multiple URL options still catch the resulting DB::Exception as an ordinary endpoint failure and continue with the next candidate: StorageURLSource::getFirstAvailableURIAndReadBuffer does that at src/Storages/StorageURL.cpp:637-656 and then converts the whole operation to NETWORK_ERROR, while ReadBufferFromWebServer::initialize does the same at src/Disks/IO/ReadBufferFromWebServer.cpp:123-183. So url() / ENGINE = URL / web disk reads with failover or brace-expanded URLs still keep issuing fresh HTTP reads after KILL QUERY, and url() can lose the cancellation code entirely. These failover loops need to rethrow QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED immediately instead of treating them as ordinary option failures.

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.

Verified this against both binaries rather than by reading, and it is partly right. The measurements below use the same dead-listener harness as the test in this PR (accepts every connection, never answers), with max_execution_time=3, http_receive_timeout=2, http_max_tries=6, http_retry_initial_backoff_ms=20000, http_retry_max_backoff_ms=30000, http_make_head_request=0. reqs is ProfileEvents['ReadWriteBufferFromHTTPRequestsSent'] read back from system.query_log. The control is a pristine master build whose copy of src/IO/ReadWriteBufferFromHTTP.cpp is byte-identical to origin/master.

url() options master master ms master reqs this PR ms reqs
1 1000 POCO_EXCEPTION 152127 6 159 TIMEOUT_EXCEEDED 22106 1
2 (a|b) 210 NETWORK_ERROR 304144 12 210 NETWORK_ERROR 24188 2
3 (a|b|c) 210 NETWORK_ERROR 456118 18 210 NETWORK_ERROR 26079 3

Confirmed: with two or more URL options the cancellation code is lost. getFirstAvailableURIAndReadBuffer catches it at StorageURL.cpp:637, keeps only the text in first_exception_message at :643, and ends at :656 with NETWORK_ERROR. The single-option case survives only because of if (options == 1) throw; at :639. Confirmed too that one further in-flight read is issued per remaining option, which is where reqs = 3 at three options comes from.

Two corrections. First, this is not created here: :637 and :639 are byte-identical on origin/master, and master re-maps the same shapes to 210 as well. What changed is that the laundered exception is now a cancellation code, which is what makes the laundering visible. Second, the web disk behaves differently from url(): ReadBufferFromWebServer::initialize stores the exception in last_exception at :174-178 and finishes with std::rethrow_exception(last_exception) at :183, so the last option's exception propagates unchanged and the code is preserved. Only the extra-attempt-per-option half of the claim applies there.

On "still keep issuing fresh HTTP reads after KILL QUERY": it is one in-flight attempt per option, not a fresh retry budget, so every option count gets strictly better here rather than staying unbounded, 456118 ms and 18 requests down to 26079 ms and 3 requests at three options.

I am not widening this PR to cover it. Unconditionally rethrowing TIMEOUT_EXCEEDED from the failover catch would also rethrow a TIMEOUT_EXCEEDED raised for reasons other than cancellation and break legitimate failover past a slow first option, so the right predicate needs its own design, in a different file. This PR's description already scopes what the change reaches, and the residual is tracked separately with the measurements above and three candidate designs: rethrow only when the query is actually marked cancelled, rethrow on an explicit cancellation code set, or check cancellation at the top of the failover loop so the next option is never attempted. I will post the link here when that PR opens.

The test asserts ReadWriteBufferFromHTTPRequestsSent, read back from
system.processes and from the query's own system.query_log row on the
initiator. With parallel replicas enabled, TableFunctionURL::getStorage
returns a StorageURLCluster instead of a StorageURL, so the HTTP reads run
in secondary queries on the replicas and that counter is never accounted on
the initiator.

Both assertions then read 0, the second section's phase poll never observes
a request so it cannot place the KILL inside the backoff, and the query runs
its whole retry budget. That is the deterministic failure on the
amd_llvm_coverage / ParallelReplicas / s3 storage shard: the query_log rows
of the failing job carry Shards: 3 and ReadTaskRequestsReceived, and no
ReadWriteBufferFromHTTP key at all.

Pin parallel_replicas_for_cluster_engines = 0 on both queries so the read
stays on the initiator. The setting is not randomized by the test runner,
and the alternative of tagging the test no-parallel-replicas would drop its
coverage on that whole job family instead.

Verified against a server running the CI parallel-replicas profile: 50 of 50
runs pass where the unpinned test reproduced the CI signature, the default
profile is unaffected, and the two cancellation checks remain separately
pinned (deleting either one still fails exactly one section).

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the test failure on Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)

Pushed 99d1e9c6676b8ca357d074b63e2ec4ccda847871. One test file, +6/-2, no source change.

That shard failed deterministically (Failed 3 out of 3 reruns) and it was not a timing problem
under coverage instrumentation. With parallel replicas enabled, TableFunctionURL::getStorage
takes its can_use_parallel_replicas branch and returns a StorageURLCluster instead of a
StorageURL, so the HTTP reads run in secondary queries on the replicas and
ReadWriteBufferFromHTTPRequestsSent is never accounted on the initiator. The test reads that
counter from system.processes and from the initiator's system.query_log row, so every
assertion that depends on it collapses at once:

  • requests sent: 1 became 0 in both sections;
  • the second section's phase poll read an empty row rather than a below-threshold value, so it
    never printed backoff phase observed and could not place the KILL QUERY inside the backoff;
  • the query therefore ran its whole retry budget, giving kept retrying for 106710 ms.

The failing job's own query_log confirms it: all four initiator rows carry Shards: 3,
DistributedConnectionTries: 3 and ReadTaskRequestsReceived, with no ReadWriteBufferFromHTTP
key at all, which is a cluster read rather than a slow local one.

The fix pins parallel_replicas_for_cluster_engines = 0 on both queries, so the read stays on
the initiator. The setting is not randomized by the test runner. I did not tag the test
no-parallel-replicas, because that would drop its coverage on that whole job family, whereas
the pin keeps it running there.

Verified against a server configured with the CI parallel-replicas profile (the same cluster and
profile the shard uses), with the server build id asserted on every arm:

Arm Result
Pinned test, parallel-replicas profile, --test-runs 50 --jobs 10 50 passed, 0 failed, 32.99-34.05 s
Pinned test, parallel-replicas profile, --test-runs 4 --jobs 4 4 of 4 passed
Unpinned test, same profile Reproduced the CI output exactly
Pinned test, default profile 3 of 3 passed, so no regression there
Pinned test on master HEAD Fails with POCO_EXCEPTION, 3 and 4 requests, 80 s and 88 s

The last row matters twice: the change does not make the test vacuous, and the test still fails
on master HEAD as the pr-bugfix category requires.

The two cancellation checks are also still pinned separately under that profile. Deleting only
the check before the backoff sleep fails the first section alone (kept retrying for 30107 ms)
while the second still passes; deleting only the check after the sleep fails the second section
alone, on the request count (1 becomes 2). Each mutant was built and run on its own, and
restoring the file rebuilt to a bit-identical binary.

The two 00084_external_aggregation failures on the previous head are unrelated to this change
and were not reproducible on rerun (Runs: 22, Failed: 0 and Runs: 4, Failed: 0). They will be
accounted for in the finish ledger once CI completes on the new head.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.30% -0.10%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 99d1e9c

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
Integration tests (amd_msan, 6/8) / test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming flaky: expected 6 rows in rabbitmq_refreshonce_dst, got '1\n' at test_system_stop.py:93, i.e. SYSTEM REFRESH on a stopped RabbitMQ table consumed one message instead of the backlog #111480 (mine, open): "Fix SYSTEM REFRESH on a stopped RabbitMQ table not consuming the backlog", which changes RabbitMQSource/StorageRabbitMQ and this very test file
Sync - CH Inc sync (private, not actionable)

The failure is unrelated to this diff, which touches src/IO/ReadWriteBufferFromHTTP.cpp and one new
stateless test. Everything else on this head is green, including Fast test, Style check and the
whole stateless matrix.

Session id: cron:our-pr-ci-monitor:20260728-033000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Recording the disposition so a reviewer does not have to reconstruct it: #112930 supersedes this PR, and I recommend closing this one in favour of it.

This PR adds two CurrentThread::checkIfNotCancelled() calls around the backoff in ReadWriteBufferFromHTTP::doWithRetries and nothing else, 3 added source lines. #112930 has the same unconditional check after the wait, and additionally replaces the uninterruptible sleepForMilliseconds with a condition variable wait, threads a Cancellation object through StorageURL, tells a cancelled metadata request apart from an absent file in tryGetFileSize and tryGetLastModificationTime, adds StorageURLSource::cancel, stops the failover probe on cancellation, and defines what a soft break timeout returns.

It also covers the odbc() variant, which I checked rather than assumed: StorageXDBC derives from IStorageURLBase and delegates to IStorageURLBase::read (StorageXDBC.cpp:133), which builds a StorageURLSource, whose cancellation member is default constructed (StorageURL.h:298), so an XDBC read gets a live cancellation object rather than a null one. The post-wait check there is unconditional, outside the if (cancelled) branch, so a killed query throws either way.

I am not closing this myself: the superseding PR is not mine and its author is tracking both.

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants