Repository navigation
Conversation
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]>
Internal second-model review (3 rounds, 17 adjudicated findings) - click to expandBefore opening, this change was reviewed by a second model against the ClickHouse review skill, in Rounds: r0 7 findings (2 blocker / 2 major / 3 nit), r1 5 (3 major / 2 nit), r2 5 (1 major / 4 nit). Accepted and fixed
Disagreed, with evidence
Noted, not blockingThe two |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-53:20260727-140001 |
|
cc @nikitamikhaylov @alexey-milovidov — could you review this? |
|
Workflow [PR], commit [99d1e9c] Summary: ❌
AI ReviewSummaryThis PR adds Findings
Final Verdict
|
| /// 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(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
Fixed the test failure on
|
| 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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
CI finish ledger - 99d1e9cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The failure is unrelated to this diff, which touches Session id: cron:our-pr-ci-monitor:20260728-033000 |
|
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 It also covers the I am not closing this myself: the superseding PR is not mine and its author is tracking both. |
Related: #107941
Related: #111930
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Makes
KILL QUERY, andmax_execution_timewith the defaulttimeout_overflow_mode = 'throw', take effect promptly for reads over HTTP (theurl,odbcandjdbctable functions, theURLtable engine, thewebdisk, and HTTP dictionaries whose source runs on the query's own thread).ReadWriteBufferFromHTTPretried an unresponsive server up tohttp_max_triestimes, sleeping up tohttp_retry_max_backoff_msbetween attempts, without ever checking whether the query had been cancelled, so a cancelled query could keep working for several minutes.Description
ReadWriteBufferFromHTTP::doWithRetriesnever consulted query cancellation, and the backoff between attempts is an uninterruptiblesleepForMilliseconds. Against a server that accepts the connection but does not answer, every attempt runs into its own receive timeout, so the worst case ishttp_max_tries * http_receive_timeoutplus 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 setshttp_receive_timeout = 60. Throughout that windowKILL QUERYandmax_execution_timehave no effect, and a pipeline worker plus two waiter threads stay occupied.PipelineExecutorobserves cancellation only between tasks, so it cannot interrupt this single task either.The fix adds two
CurrentThread::checkIfNotCancelledcalls 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 byZooKeeperRetriesControlinZooKeeperRetries.hand by the S3 client inS3/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_timeoutplus 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 QUERYalways marks it, and so does amax_execution_timetimeout with the defaulttimeout_overflow_mode = 'throw'. Withtimeout_overflow_mode = 'break'the cancellation checker deliberately does not mark the query (it callscheckTimeLimit, 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 suppressedCANNOT_PARSE_INPUT_ASSERTION_FAILEDand made02270_errors_in_files_s3flaky. That test'surl()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
ReadWriteBufferFromHTTPconsumer is covered rather than justStorageURLSource, and all three retry entry points (nextImpl,readBigAt, thegetFileInfoHEAD probe) share the single guarded loop. Threads with no query attached are unaffected:checkIfNotCancelledreturns early when there is no current thread status, andthrowIfQueryCanceledreturns 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
directdictionary calls its source inline on the query thread, and theflat/hashedlayouts are loaded throughExternalLoader, which captures the requesting query's thread group (CurrentThread::getGroupinstartLoading, restored byThreadGroupSwitcherindoLoading), so both observe cancellation. Thecachefamily (cache,ssd_cacheand theircomplex_key_variants) instead hands the update to a persistent worker of its ownCacheDictionaryUpdateQueuepool, which attaches no thread group, while the query thread waits separately for up toquery_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 cancelledodbc()query kept retrying for about nine minutes aftermax_execution_time = 60fired: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111930&sha=84788620b746b5c00af1121143172495ae3f13fe&name_0=PR&name_1=Stress%20test%20%28amd_msan%29Relationship to open pull requests in this area, for reviewers deciding where the fix belongs:
CheckCancelledcallback through theReadWriteBufferFromHTTPconstructor,BuilderRWBufferFromHTTPandStorageURLSource. This change is disjoint from it: it touches onlyReadWriteBufferFromHTTP.cpp, changes no signatures, and usesCurrentThread::checkIfNotCancelled, which did not exist when Improve canceling queries with url() function #104089 was written (added inb82d83174e9956, 2026-07-03).ReadBuffer::next#109785 adds a cancellation check at the entry ofReadBuffer::next. It cannot shorten this hang, because the whole retry loop runs inside a singlenextcall that was already entered before cancellation. The two are complementary, and this check would respectCancellationChecksBlockerInThreadif that lands.No new setting and no default change, so
SettingsChangesHistory.cppneeds no entry.