Repository navigation
Improve canceling queries with the url function - #112930
Conversation
Check query cancellation between HTTP retry attempts, so that `KILL QUERY` and client disconnects stop a query over the `url` table function instead of waiting until all the retries are exhausted. `ReadWriteBufferFromHTTP` accepts an optional cancellation callback and, from the second attempt on, leaves `doWithRetries` by `break` instead of throwing, so the original HTTP error is still reported on the first attempt. `StorageURLSource` passes `isCancelled` down to the buffer and checks for cancellation after every step of its lazy initialization that can issue an HTTP request. This is a resubmission of #104089 by Roman Vasin (@rvasin) into the main repository, so that we can continue to work on it. That pull request in turn fixes the reverted #102801 and #104014. Differences from the original pull request: a comment in `ReadWriteBufferFromHTTP::initialize` that a bad merge had garbled is restored, the condition of the `chassert` in `readBigAt` is parenthesized, and the test is renumbered to `04615` because `04078` is taken on `master`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [a4f1df4] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ Approve LLVM Coverage ReportMeasured on commit a4f1df4.
Changed lines: Changed C/C++ lines covered: 297/311 (95.50%) · Uncovered code |
Reworks the previous commit after the review of the original pull request #104089 by @Algunenano. `doWithRetries` no longer leaves its loop with a `break`, which returned normally and so looked like success to every caller: `readBigAt` could trip its `chassert`, `nextImpl` could report a cancellation as the end of the stream, and the row count cache could be filled from an interrupted read. Instead, the loop waits for the backoff on a cancellation flag - a condition variable, so a cancellation interrupts the wait instead of being waited out - and then either reports the query as cancelled or rethrows the error of the last attempt. Which of the two it does now depends on the reason, because query cancellation and pipeline cancellation are not the same thing. A killed or timed out query is reported through the query status by `CurrentThread::checkIfNotCancelled`, exactly as `Client::HeadObject` does it for S3, so the user gets `QUERY_WAS_CANCELLED`, `TIMEOUT_EXCEEDED` or the exception recorded for a disconnected client instead of whatever network error was at hand. That part needs no plumbing, so it also covers the other users of the buffer, which pass no cancellation flag. When the pipeline is merely being torn down because something else in the query has already failed, the error of the last attempt is rethrown - the very exception the caller would have got once the attempts were exhausted - so nothing fabricates a cancellation that races the real exception of a peer source with a wrong message and URI. Because the loop always either does its work or throws, `StorageURLSource` needs none of the cancellation checks after each buffer operation, and the `chassert` in `readBigAt` is left alone. The condition on the attempt number is gone as well: the check now sits where the loop decides to wait and try again, which can only be reached after an attempt has failed, so a genuine first failure is never masked. `StorageURLSource::cancel` sets the flag only for `CancelledByUser`, `CancelledByTimeout` and `Exception`. A consumer which simply has enough data (`CancelReason::PartialResult`, or the read limits with the `break` overflow mode) does not interrupt the retries, because such a read may still succeed and still be needed. `getFirstAvailableURIAndReadBuffer` also stops probing the failover options of a query that has been killed meanwhile. The test now makes the server answer `503` so that the query really is inside the retry loop - the previous version always answered `200` and never reached a second attempt - kills it, and checks that it stops within seconds and reports an error, plus that the same query still reports the error of the server when it is not killed. Locally the killed query ends 3 ms after the `KILL`, while an unpatched server keeps retrying for more than five minutes with `is_cancelled = 1`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@Algunenano, your review of #104089 is addressed here - the description lists the points one by one, but in short:
@rvasin, this is your change - thank you; the first commit keeps you as its author. Please have a look if you disagree with anything in the rework. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code |
`CancelReason::CancelledByTimeout` at the processor level only comes from `PipelineExecutor::checkTimeLimitSoft`, that is from `max_execution_time` with `timeout_overflow_mode='break'`, where the query is not killed and must return the data it has read so far. Waking the retry backoff there made `ReadWriteBufferFromHTTP::doWithRetries` rethrow the last HTTP error and turned a partial result into a failure. A timeout with the `throw` overflow mode kills the query and arrives as `CancelReason::CancelledByUser`, which is still handled.
|
🕵 The only CI red was Also merged |
…d any teardown wakes the retry backoff Wake the retry backoff of `ReadWriteBufferFromHTTP` on every cancellation reason, including `Unknown`, which `QueryPipeline::cancel` forwards on the `BlockIO` teardown paths (`onCancelOrConnectionLoss`, `onException`), so a client disconnect no longer leaves the backoff sleeping. For the reasons after which the query must still succeed with the data it has already read - `CancelledByTimeout`, i.e. a soft `max_execution_time` with `timeout_overflow_mode = 'break'`, and `PartialResult` - the interrupted read still ends with its last HTTP error (`doWithRetries` keeps its data-or-exception contract), but `StorageURLSource::generate` now discards that error and ends the stream, so the query returns its partial result instead of failing. Add a test: a glob over a file that succeeds and a URL that always answers 503 with a huge retry backoff; a query with a soft timeout of one second returns the rows of the first file quickly, while a query without the timeout still reports the HTTP error of the server.
…wallow `StorageURLSource::initialize` calls helpers which swallow the errors of the requests they make: `getFirstAvailableURIAndReadBuffer` turns a failure into probing the next failover option, and `ReadWriteBufferFromHTTP::tryGetFileSize` / `tryGetLastModificationTime` return `nullopt` for a file without metadata. The error of a request whose retry backoff was woken by a cancellation (see `doWithRetries`) went the same way, so initialization could keep probing options, making `HEAD` requests, and even download the data after the source was cancelled with `CancelReason::Unknown`, `PartialResult`, or a soft `CancelledByTimeout`. Now the helpers rethrow when the read has been cancelled (`Cancellation::isCancelled`), and `generate` re-checks `isCancelled` after `initialize` so it never pulls a chunk no one needs. The new test asserts, via a request-counting HTTP server, that after a soft `break` timeout interrupts the retries neither the data nor the next failover option is requested, while an uninterrupted query still treats the failing metadata `HEAD` request as non-fatal. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 CI triage for commit 4df663a - all three reds are unrelated to this change (
@groeneai, investigate the last one - the Master is merged and the review finding is addressed in 360bd3a, so the next CI run is on the updated branch. |
|
Confirmed, and confirmed from the artifact rather than by agreement. Row 1 is your fuzzed Row 2 is the Three things I had not measured before: It is not only The ProfileEvents on that row understate the stuck time by about 170x, so they are not a usable diagnostic for this family. They read The msan amplification has a specific site. Below your two frames the leaf is msan's own On ownership: the cost half is your #113140, which batches that per-column loop into a single pass. The interruptibility half is separate and still unfixed. #113140 adds no checkpoint (87 added lines, 0 matches for For the fix shape the precedent is already inside Nothing needed from me on the other two reds; #96656 and #107619 cover them. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes99 object files changed (+65.88 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9328 translation units recompiled, 11426 s compile time in total, 9044 of them have a recent master baseline. |
|
Fixing PR for the I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical |
`StorageURLSource::generate` treats `pull` returning `false` as the end of the file and records `total_rows_in_file` in the count cache (`use_cache_for_count_from_files`). Guard that write so a read ended by a cancellation - such as the soft `max_execution_time` with the `break` overflow mode - can never record the rows it happened to read as the row count of the file, following the same `getExecutionStatus` pattern as `StorageMemory` mutations. Today the inner pipeline of the source has no process list element, so its `PullingPipelineExecutor::pull` cannot return `false` on the soft time limit, and every cancellation path in `generate` breaks out before the cache write - verified empirically: an interrupted read leaves no cache entry even without this guard. The guard makes the EOF-vs-cancellation distinction explicit and keeps the invariant if that wiring ever changes. The new test `04811_url_function_no_count_cache_poisoning_on_break_timeout` pins it down. Co-Authored-By: Claude Fable 5 <[email protected]>
On a loaded runner the soft timeout can fire before the first file has streamed anything, leaving a valid but empty partial result: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112930&sha=360bd3a086cf15d5652720204b35562489241074&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 (#112930). Retry the timed query until the rows make it through; the guarantees under test (the query succeeds and returns quickly) must hold on every attempt. Co-Authored-By: Claude Fable 5 <[email protected]>
…est count The test failed once in `Stateless tests (amd_debug, flaky check)` with `FAIL: no read of the parquet data was in flight`, while both of the checks that matter - the discard of the interrupted background read and the partial result of the query - passed. The server held a request only once it had already served `SERVED_IN_FULL = 3` of them, assuming the footer and the metadata take exactly three reads. How many reads they take, and how the reader splits the reads of the data, depend on the build and on the randomized settings, so on that run the read of the column chunk was one of the first three and was served in full: it was in flight - slow enough on a loaded runner for the cancellation to land inside it, which is why the other two checks passed - but the counter of the held reads stayed at zero. The decision is now keyed on the offset instead: the footer and the metadata of a `Parquet` file live in the last bytes of the file, so a read that begins before that tail is a read of the data and is always held. The test no longer polls the server while the query runs - the counter is cumulative, so it is read once after the query - which also keeps 600 `curl` processes off the runner the query is being timed on. `max_execution_time` is raised from 3 to 10 seconds, above the time the metadata phase needs on a loaded sanitizer runner, and `http_max_tries` is raised to 20 so that the budget of the retries of the held read - 20 attempts of `http_receive_timeout 6` - stays far above the limit and the read is still being retried when the limit fires. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…parquet_soft_cancel` With the hold of the server keyed on the offset, the very first request of the query is the one that must not be held: schema inference reads the whole file sequentially, in a request without a `Range` header, and holding it fails the query with `CANNOT_EXTRACT_TABLE_STRUCTURE` before any column chunk is read. The structure is therefore given explicitly - the query reads no more than the metadata and the data - and a request without a `Range` header is answered in full in any case, since it is not a positional read of the reader. Measured with the probe of the requests: the query now makes a `HEAD`, two reads of the tail of the file (`bytes=16929482-16995017` and `bytes=16993467-16994077` for a 16995018-byte file) and one read of the data (`bytes=4-3997578`), which is the one that is held. The test passes 5/5 with randomized settings, in 13 seconds each, and all 33 `url` tests of this branch pass. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…soft_cancel` No change in behaviour. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Triage of the run on
The server held a request only after it had already served The decision is now keyed on the offset: the footer and the metadata of a The test also no longer polls the server while the query runs - the counter of the held reads is cumulative, so it is read once after the query - which keeps 600 Verified locally against a build of this branch: 5/5 PASS with randomized settings, 13 s each, and all 33 The two other reds are unrelated:
The AI review on the previous head reported |
…orageURLSource::generate` Address review: the exits added for the cancellation paths ended the stream without the teardown which the ordinary end of a file runs, and `ISource::work` only marks the source finished - the processor itself is destroyed when the whole query is. A query cancelled softly keeps running afterwards: a `max_execution_time` with the `break` overflow mode returns the partial result, and a consumer which has enough data lets the rest of the pipeline finish. Until the reader is released the background work of the format - the decode and prefetch tasks of the native `Parquet` reader are only asked to stop by `ParquetV3BlockInputFormat::onCancel`, they are drained by `shutdownTasks` or by destruction - the HTTP session and its buffers stay pinned for the rest of the query, which is what the cancellation asked to stop. The teardown is now a `release_reader` lambda and it runs on every exit from the loop, including the one for an exhausted list of URI options, which used to return directly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Addressed the Minimum required action - release the inner pipeline and read buffer on every cancel-induced exit of Changelog category: adopted as well, Verified locally against a build of this branch: The branch was merged with |
`readability-ambiguous-smartptr-reset-call` fires on `pipeline->reset()` in the new `release_reader` lambda of `StorageURLSource::generate`, because both `std::unique_ptr::reset` and `QueryPipeline::reset` exist. Use the explicit `(*pipeline).reset()` form, which is what the end-of-file teardown this lambda replaced already used. Control-proved with `clang-tidy` restricted to that check: it reports the error on the previous form and is clean with this one. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112930&sha=bb23a5019a85b5b9edb5856c9d2e6512df37c325&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: #112930 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Triage of the run on
Control-proved with
Everything else on that run is green, and the AI review on |
… in `generate` A cancellation does not have to come back through `StorageURLSource::generate` for the source to end. `ISource::work` stores the chunk it pulled in `current_chunk`, and when a cancellation - a `PartialResult` one, or `max_execution_time` with the `break` overflow mode - lands before the next `ISource::prepare`, that `prepare` pushes the buffered chunk and finishes the source on `isCancelled` without calling `work` again. The teardown added in `bb23a5019a85` lives at the exits of the reading loop, so on that path it never ran and `reader`, `input_format` and `read_buf` stayed pinned for the rest of a query which keeps running - the very resource retention that teardown was added to stop. The same holds for a downstream which finishes its input, such as a satisfied `LIMIT`. The teardown is therefore a `releaseReader` member function now, and `StorageURLSource::prepare` calls it whenever `ISource::prepare` reports `Finished`. All three ways for it to report `Finished` - a finished source, a finished output port and a cancelled source - are terminal, so nothing is going to read again, and `releaseReader` is idempotent for the ordinary end of a file, where the loop has already run it. `prepare` runs in the executor thread exclusively with `work`, so the reader is never released from under an ongoing read. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 CI triage for Pushed: the AI Review follow-up on the soft-cancel teardown thread is adopted - the teardown is now the member function The two reds on
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
Very interesting.
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Resubmission of #104089 by Roman Vasin (@rvasin) into a branch of the main repository, with the review feedback from @Algunenano addressed. The original pull request is closed as superseded.
Related: #104089
Related: #102801
Related: #104014
A query which reads over HTTP does not react to cancellation while
ReadWriteBufferFromHTTPis retrying a request:KILL QUERY,max_execution_timeor a disconnected client take effect only after allhttp_max_triesattempts and the backoffs between them are over, which is minutes with the default settings.What the change does {#what-the-change-does}
doWithRetrieswaits for the backoff on a cancellation flag instead of sleeping, so a cancellation interrupts the wait instead of being noticed after it has expired. The flag (ReadWriteBufferFromHTTP::Cancellation, a one-shot flag with a condition variable) is owned byStorageURLSourceand set from itscancel. The wait also polls the query time limit on the same 100 ms grid as the token-less backoff below and latches a soft timeout into the flag itself:CancelledByTimeoutonly ever comes from the executor'scheckTimeLimitSoftpolls between the execution steps, so when the only executor thread is the one sleeping in the wait - a single-source query underPullingPipelineExecutororCompletedPipelineExecutor, for example over the HTTP interface - no one is left to deliver it through the flag's owner (CancellationCheckercancels the query only for thethrowoverflow mode), and without the poll the deadline would be missed by the remainder of the backoff.CurrentThread::checkIfNotCancelled, exactly asClient::HeadObjectalready does it for S3. A killed or timed out query is therefore reported with its own proper error (QUERY_WAS_CANCELLED,TIMEOUT_EXCEEDED, or the exception recorded for a disconnected client) instead of the network error that happens to be at hand. This part needs no plumbing, so it works for every user of the buffer, including those that pass no cancellation flag (thewebdisk, HTTP dictionaries, the data lake catalogs). The same question is asked once more in the failover loop ofStorageURLSource, where the error of a failed option unwinds to, before the error is reported - the check at the terminal exit of the retries does not cover a kill landing while the error unwinds - so a killed query whose only option has just failed is reported as cancelled there too, with or without a cancellation flag.StorageURLSource::cancelwakes the backoff for every cancellation reason - no one is left to wait for the remaining attempts. A cancellation after which the query must still succeed with what it has already read - a softmax_execution_timewithtimeout_overflow_mode = 'break'(CancelledByTimeout, which only ever comes fromPipelineExecutor::checkTimeLimitSoft; a timeout with thethrowoverflow mode kills the query and arrives asCancelledByUser), or a consumer that has enough data (PartialResult) - is remembered, andStorageURLSource::generatethen discards the error of the interrupted read and ends the stream, so the query returns its partial result instead of failing with the HTTP error. Only the interruption of the read is discarded: the sites which report an error because of the cancellation - the retry loop when it stops retrying, the failover loop when it stops probing the options - mark it (Cancellation::markReadInterrupted), and an error the cancellation has nothing to do with, for example a parse error of the data that had already been downloaded when it arrived, fails the query the same way it would with no cancellation at all. What is remembered is the effective kind of the cancellation:ExecutingGraph::cancelupgrades aPartialResultcancellation to the reason of a later hard one - for example, the first cancel of a client withpartial_result_on_first_cancelfollowed by aKILL QUERY- and after the upgrade the read is not soft anymore, so nothing is discarded or synthesized - and nothing built under the soft state escapes either: an error of the interrupted read that was already in flight when the upgrade landed is suppressed rather than rethrown, because under a hard cancellation the query fails for a reason of its own - the error of the failed peer, the kill reported by the process list, or a disconnected client with no one left to report to - and the stale error must not mask it.StorageURLSource::initializeeven where its helpers swallow the errors of the requests they make:getFirstAvailableURIAndReadBufferrethrows the error of a cancelled read instead of probing the next failover option (the check precedes the single-option fast path, so the rethrown error of a lone option is marked as the interruption of the read too, instead of masking a cancellation which landed while it was unwinding, and no longer probes them for a killed query at all, including a query killed right after its last option has failed, which is reported as cancelled instead of with the aggregate network error, and a cancellation which lands where no request is in flight for it to interrupt - between the options, or after the last one has failed - stops the choosing of the URI with the same two outcomes, a discarded cancellation error for a soft one and no buffer at all for a hard teardown, so the aggregate error can never stand in for the failure that really happened), andReadWriteBufferFromHTTP::tryGetFileSize/tryGetLastModificationTimerethrow it instead of treating the interruptedHEADrequest as a file without metadata (the rethrow is keyed off the mark the interrupted request leaves -Cancellation::markReadInterrupted- not off the cancellation flag at the moment the fallback runs, so an error that had already happened when the cancellation arrived stays swallowed, and a soft cancellation cannot turn a metadata failure the query would have survived into a failure of the query).generatere-checksisCancelledafterinitialize, so it never pulls a chunk no one needs.initializeitself ends the stream when the cancellation arrives after the URI has been chosen but before the metadata of the file - the modification time and the size - is requested, so a cancelled source does not start a fresh metadataHEADrequest. The check is repeated between the two metadata probes: when the sharedHEADrequest has failed with a network error before the cancellation arrived, the probe of the modification time has nothing to remember, and the probe of the file size would otherwise send a freshHEADof its own.How the review feedback is addressed {#how-the-review-feedback-is-addressed}
ReadWriteBufferFromHTTP::readBigAtshows how trivial is now to hit asserts due to a pipeline cancellation." - there is no silentbreakanymore:doWithRetrieseither does its work or throws, so a caller cannot mistake a cancellation for a success. ThechassertinreadBigAtstays untouched,nextImplcannot report a cancellation as the end of the stream, and the row count cache cannot be filled from an interrupted read. ConsequentlyStorageURLSourceneeds none of theisCancelled()checks the original pull request added after each buffer operation - which also answers "I don't understand the pattern of doing the HTTP request, and then checking if the pipeline is cancelled. Shouldn't it be the other way around?" and "Why not check at the start of the loop?".attempt > 1condition is gone. The check now sits where the loop decides to wait and try again, which by construction can only be reached after an attempt has failed, so the error of a genuine first failure is never masked.Test {#test}
04615_kill_query_url_functionstarts a server that always answers503, so that the query really is inside the retry loop - the test in the original pull request always answered200and never reached a second attempt. With 30 attempts and a backoff of 1 to 2 seconds, for both theHEADand theGETrequest, the query would retry for minutes; the test kills it and checks that the client stops within seconds and reports an error. It also checks that the same query, when it is not killed, still reports the503of the server as before.Verified locally against a build of this branch: the killed query ends 3 ms after the
KILLand is reported asCode: 394. DB::Exception: Query was cancelled. On an unpatched server the same query stays insystem.processeswithis_cancelled = 1and keeps retrying for more than five minutes.04691_url_function_partial_result_on_break_timeoutcovers the soft timeout: a glob over a file that the server serves completely and a URL that it always answers with503, with a backoff of 1 to 2 seconds over 30 attempts. A query withmax_execution_time = 1andtimeout_overflow_mode = 'break'succeeds with the rows of the first file in about a second, while the same query without the timeout still reports the503of the server. The partial result of thebreakmode consists of the rows already streamed to the consumer - a cancelled aggregation returns nothing even for regular tables - so the test asserts the streamed rows.04759_url_function_cancel_during_initializecovers a cancellation during initialization, whose helpers swallow the errors of the requests they make. Its server counts the requests to each path: after a softbreaktimeout interrupts the retries of the metadataHEADrequest the data is never downloaded, and after it interrupts the retries of the first failover option of ana|bURL the second option is never probed - while an uninterrupted query still treats the failing metadata request as non-fatal and reads the data. Both assertions fail on the code before the fix.04811_url_function_no_count_cache_poisoning_on_break_timeoutcovers the row count cache (use_cache_for_count_from_files): a read of a slowly streaming URL interrupted by a softbreaktimeout leaves no entry insystem.schema_inference_cache, while a complete read still caches the correct row count.generaterecords the count only when the read genuinely reached the end of the file - it checks the final status of itsPullingPipelineExecutorandisCancelledon the source, asStorageMemorymutations do - so a cancelled read can never record the rows it happened to read as the row count of the file.04812_url_function_no_fallback_probe_after_soft_cancelcovers a cancellation which lands between the failover options, where there is no request in flight for it to interrupt: anempty|dataURL withengine_url_skip_empty_files = 1, where the empty file takes longer to be served than the softbreaktimeout of the query. Once the empty file is skipped, the loop checks the cancellation flag before constructing and probing the next option, so the query succeeds with no rows and the data URL receives no requests - the assertion fails on the code before the fix. An uninterrupted query still skips the empty file and reads the next option. This between-options check is reason-aware: it reports the interruption with a cancellation error - whichgeneratethen discards - only for the soft cancellations, after which the query must still succeed (CancelledByTimeoutof thebreakoverflow mode, orPartialResult). A pipeline torn down because something else in the query has already failed, or a disconnected client, must not be reported with a fabricated cancellation that could reach the user in place of the failure that really happened - and needs no synthetic error at all:getFirstAvailableURIAndReadBufferreturns no buffer andinitializeends the stream, since nobody is left who needs the data.04824_url_function_kill_after_partial_result_cancelcovers a hard cancellation arriving after a soft one: the first cancel of a client withpartial_result_on_first_cancel- after which the query must still succeed with its partial result - is followed by aKILL QUERY, both landing while the source is blocked in a request that a cancellation cannot interrupt (an empty file ahead of a failover option, whose response the test server withholds until the test releases it after theKILLhas returned - the kill delivers the cancellation to the processors synchronously, so no timing can release the source early). The killed query must fail with the cancellation error instead of discarding it as if its result were partial, and must not probe the next failover option - the discard assertion fails on the code before the fix. The reason the executor delivers may understate a kill: itscheckTimeLimitSoftpoll observes a killed query as a soft timeout, and when that poll wins the race for the one-shot cancel reason ofExecutingGraph, the kill's own hard broadcast never reaches the source - so before discarding, the source additionally asks the process list, and a killed query fails with the proper cancellation error under either delivery order.04825_url_function_no_next_option_after_disconnectcovers a hard teardown which does not kill the query, landing between the failover options: the client of a query blocked in the request for a held empty first option disconnects (kill -9), the test waits until the delivery of the resulting cancellation to the source is visible in the log (StorageURLSource::cancelleaves a debug trace of every delivered cancellation and its reason), and only then lets the server answer the held request. The source finds the empty file, and must end the stream instead of probing the next option, which would succeed - the assertion fails on the code before the fix. The tests which kill their query or assert on its log pinparallel_replicas_for_cluster_enginesoff: the rewrite ofurltourlClusterwould move the source into remote queries with their own query ids.04829_url_function_no_metadata_requests_after_cancelled_headcovers the fallback for servers which do not supportHEAD:ReadWriteBufferFromHTTP::getFileInfotreats a non-retriable 4xx response as "the server cannot answer this" and reports no metadata - and used to do so even when the request had been interrupted by a cancellation, so the initialization completed as if the file simply had no metadata instead of failing with the error of the interrupted read, whichgeneratediscards or fails with depending on the kind of the cancellation. The test answers the metadataHEADwith400only after a softbreaktimeout has been delivered to the source (the request-counting server withholds the response until the delivery is visible in the log): the query succeeds with its empty partial result, no request follows the cancelledHEAD, and the log records that the interrupted read was reported and its error discarded - the last assertion fails on the code before the fix.04837_url_function_killed_query_after_last_attemptcovers the exit of the retry loop after the attempt which has nothing left to retry. Its reader is the schema inference of theurltable function, which passes no cancellation flag, so the query status is the only thing that can tell the read that the query is gone. The server withholds its503response until the test has killed the query, andhttp_max_triesis 1, so the read is interrupted exactly where the retrying ends: the query must fail withQUERY_WAS_CANCELLED, while the same query which is not killed must still report the503of the server. On the code before the fix the killed query is reported with the503instead - which is the assertion the test makes.05048_url_function_killed_query_while_option_error_unwindscovers the window right after that terminal exit: the kill lands while the error of the only failover option unwinds to the catch ofgetFirstAvailableURIAndReadBuffer, after the terminal check insidedoWithRetrieshas already passed. The reader is again the schema inference ofurl, which passes no cancellation flag, so nothing on that path used to ask the query status again and the lone option's stale HTTP error was rethrown over the kill. The window is a few instructions wide, so the test holds the source in it with a failpoint (storage_url_pause_before_handling_option_error, added for the test): the only attempt of the only option fails at once against a server which always answers503, the unwinding pauses, the query is killed (visible insystem.processes), and only then the source is released. The killed query must fail withQUERY_WAS_CANCELLED, while the same query which is not killed still reports the503of the server - on the code before the fix the killed query is reported with the503, which is the assertion the test makes.05054_url_function_hard_timeout_while_option_error_unwindsis its sibling for the other half of the same window: instead of a kill, themax_execution_timeof the query runs out with thethrowoverflow mode while the error of the lone option is held on the same failpoint. A killed query is visible toCurrentThread::checkIfNotCancelled, a deadline which has merely passed is not - the asynchronousCancellationCheckerturns it into a kill on its own schedule - so the catch asks the query status about the time limit directly. The query must be reported asTIMEOUT_EXCEEDEDrather than with the503, while the same query given enough time still reports the503. Unlike the tests above, this one also passes before the fix, because the deadline the test waits for is delivered by theCancellationCheckerwithin its own grid: it pins the contract, while the fix is what closes the window synchronously.05076_url_function_hard_timeout_after_pullcovers the same half of the window afterpullingenerate:PullingPipelineExecutor::pullpolls the time limit only before a step, and the check after it used to ask onlyCurrentThread::checkIfNotCancelled, which sees a hardmax_execution_timeonly once theCancellationCheckerhas turned it into a kill - so a deadline which passed while the chunk was being produced let that chunk through toISource::prepare. The source now asks the query status about the time limit directly, as it already did before starting new I/O ininitialize. The test holds the pulled chunk onstorage_url_pause_after_pull(the failpoint of04904) until the deadline of the query has passed and releases it: the query must fail withTIMEOUT_EXCEEDEDand emit nothing, while the same query given enough time returns the row. Like05054, it pins the contract rather than discriminating the fix: by the time the test can see that the deadline has passed, theCancellationCheckerhas usually turned it into a kill as well.04843_url_function_no_metadata_probe_after_soft_cancelcovers the window after the URI has been chosen and before the metadata of the file is requested: the server withholds the response of the first failover option until a softbreaktimeout has been delivered to the source (visible in the log), and then serves the file without aContent-Length, so the modification time and the size could only come from aHEADrequest. The cancelled source must end the stream instead of probing the metadata no one is left to read: the query succeeds with its empty partial result and noHEADrequest follows - the assertion fails on the code before the fix.04844_url_function_parse_error_after_soft_cancelcovers an error which the cancellation has nothing to do with: the server streams a few good rows, withholds the rest until a softbreaktimeout has been delivered to the source, and only then sends a malformed row. The parse error must fail the query even though the soft cancellation - after which the query would otherwise succeed with its partial result - has already been latched: the file is malformed no matter when the query stopped wanting more of it. On the code before the fix the query succeeds, and the malformed row is discarded together with the interruption of the read.04846_url_function_no_second_metadata_probe_after_cancelcovers a cancellation which lands between the two metadata probes ofinitialize: the server tears down the metadataHEADrequest without a response - a network error which leaves the probe of the modification time with nothing to remember - and the source is held in the window between the probes with a failpoint (storage_url_pause_between_metadata_probes, added for the test: the window is a few instructions wide) until a soft cancellation has been delivered to it - the client is cancelled with SIGINT underpartial_result_on_first_cancel = 1, so the delivery is under the test's control and cannot race the query the way a shortmax_execution_timedid (which made the first version of the test flaky under the sanitizer builds) - and the delivery is visible in the log. The released source must end the stream instead of letting the probe of the file size send a secondHEADrequest: the query succeeds with its empty partial result and the server sees exactly oneHEAD- the assertion fails on the code before the fix.04869_url_function_stale_metadata_error_after_soft_cancelcovers the opposite side of the same fallbacks: a metadataHEADrequest which fails on its own before any cancellation arrives must stay non-fatal even when a soft cancellation lands while its failure is being unwound. The server tears down theHEADrequest without a response, the source is held inside the fallback with a failpoint (http_read_buffer_pause_before_metadata_fallback, added for the test: the window between the failed request and the fallback is a few instructions wide), the test delivers the soft cancellation (SIGINT withpartial_result_on_first_cancel = 1, visible in the log) and only then releases the source. The fallback must swallow the error of the request the cancellation did not interrupt: the query succeeds with its empty partial result and the data is never requested - on the code before the fix the query fails with the stale network error of theHEADrequest.04871_url_function_hard_cancel_upgrade_after_interrupted_readcovers the upgrade of a soft cancellation to a hard one landing in the last window: after the error of the interrupted read has been thrown under the soft state, but beforegeneratehas handled it. One source retries an always-failing URL and is parked right before its second attempt with a failpoint (storage_url_pause_before_retry_attempt), so that the soft cancellation (SIGINT withpartial_result_on_first_cancel = 1) always finds it in the one state in which it throws - a source left to race the cancellation in its backoff can be anywhere, which made the first version of the test hang waiting for a pause which never came; releasing it makes it throw the error of its interrupted read, which is then held in the window with a second failpoint (storage_url_pause_before_handling_interrupted_read_error, added for the test: the window is a few instructions wide). A second source, held by the test server until now, is then released into a parse error - a real failure the cancellation has nothing to do with - which cancels the pipeline hard and upgrades the paused source's reason toException; the test waits until both deliveries are visible in the log, so the upgrade deterministically lands inside the window, and only then releases the source. The stale error of the interrupted read must be suppressed and the query fails with the parse error of the peer - on the code before the fix it fails with the stale HTTP error of the read its own cancellation interrupted.05024_url_function_schema_inference_soft_timeoutcovers the choosing of the failover option in a read which has no cancellation token at all: the schema inference ofurlreads without aStorageURLSourcebehind it, so the soft timeout has nothing to be latched into. The inference is held right before the creation of the first buffer,max_execution_timeexpires while it waits, and it is released into the choosing of the next option, where the latch is - which the test requires to leave the server alive.05029_url_function_schema_inference_hard_timeout_during_backoffcovers the retry backoff of the same token-less read: the first request fails immediately, a hardmax_execution_time- thethrowoverflow mode - expires while the backoff is pending, and the query has to stop withTIMEOUT_EXCEEDEDlong before the backoff ends and without issuing the retry. The backoff pollsQueryStatus::checkTimeLimititself, so the stopping does not depend on the asynchronous canceller flipping the killed flag first.05042_url_function_break_timeout_wakes_retry_backoffcovers the polling of the token-backed wait: a query over the HTTP interface - where the pipeline runs underCompletedPipelineExecutorand, with a singleurlsource sleeping in its backoff, no executor thread is left to poll the soft time limit - enters a 60-second backoff, andmax_execution_time = 5with thebreakoverflow mode expires while the backoff is pending. The query has to return its empty partial result within seconds of the deadline instead of sleeping out the backoff, and it may not issue the retry request after the timeout - on the code before the fix it succeeds only after the whole backoff.05229_url_function_kill_after_source_finishedpins the contract the token-driven exits rely on: aKILL QUERYwhich arrives after the source has already ended its stream still fails the query.PipelineExecutor::finalizeExecutioncallscheckTimeLimitbefore it looks at its own execution status, andQueryStatus::checkTimeLimitthrows for a query whosecancelQueryhas run, so the EOF of the source is never what decides the outcome of a killed query. The test reads the whole response - the request counter of its server proves the source has nothing left to read - and kills the query whilesleepEachRowstill holds the rest of the pipeline; it must fail withQUERY_WAS_CANCELLEDinstead of returning a partial result.05231_url_function_parallel_read_soft_cancelcovers the same discard through the background workers of aParallelReadBuffer, whichFormatFactory::getInputuses for a large, seekable remote file. A worker woken fromReadWriteBufferFromHTTP::readBigAtby the cancellation stores itsReadInterruptedExceptionas the background exception of the buffer, andParallelReadBuffer::nextImplrethrows it intoreader->pullwith its type intact, so abreak-mode timeout landing while both workers are inside their range requests ends the stream with the partial result instead of failing the query. The test asserts that the range requests were in flight, that the discard was logged, and that the query succeeded.Preserving the type of the interrupted read's error across the source's own pipeline needed one change outside
url:ExecutionThreadContext'sexecuteJobcaught the exception of a processor by value, which sliced it toException, and rethrew the copy. The copy is there so that the same exception - several threads can rethrow onestd::exception_ptr- is not modified in place, but it was made even when nothing was added to it, andcheckCanAddAdditionalInfoToExceptionadds nothing to aQUERY_WAS_CANCELLED. Since the interrupted read is thrown inside the source's own pipeline,StorageURLSource::generatealways received it sliced and could not tell it from an unrelated failure. The copy is now made only when there is a message to add, and the original is rethrown otherwise.The same slicing exists on every path which hands an exception over between threads through an
std::exception_ptr:copyMutableExceptionrethrows through the virtualPoco::Exception::rethrow, which throws a plainExceptionfor a type that does not override it. The background tasks of the nativeParquetreader use it, inParquet::Prefetcher::rethrowExceptionandParquet::ReadManager::read, so a softly cancelled positional read of a column chunk reachedStorageURLSource::generateunrecognizable and failed the query.ReadInterruptedExceptionnow overridescloneandrethrow, and05232_url_function_parquet_soft_cancelpins it with a server which reports a realParquetfile as seekable and then holds the range requests of the column chunks.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
KILL QUERY, query timeouts and client disconnects now stop a query that reads over HTTP (for example over theurltable function) while it is retrying a request, instead of waiting until all the retry attempts are exhausted.Workflow [PR]
Sync PR [sync-upstream/pr/112930]
Version info
26.10.1.708-master(included in26.10and later)