Skip to content

Improve canceling queries with the url function - #112930

Merged
alexey-milovidov merged 113 commits into
masterfrom
url-function-cancellation
Sep 26, 2026
Merged

alexey-milovidov merged 113 commits into
masterfrom
url-function-cancellation

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

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 ReadWriteBufferFromHTTP is retrying a request: KILL QUERY, max_execution_time or a disconnected client take effect only after all http_max_tries attempts and the backoffs between them are over, which is minutes with the default settings.

What the change does {#what-the-change-does}

  • doWithRetries waits 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 by StorageURLSource and set from its cancel. 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: CancelledByTimeout only ever comes from the executor's checkTimeLimitSoft polls between the execution steps, so when the only executor thread is the one sleeping in the wait - a single-source query under PullingPipelineExecutor or CompletedPipelineExecutor, for example over the HTTP interface - no one is left to deliver it through the flag's owner (CancellationChecker cancels the query only for the throw overflow mode), and without the poll the deadline would be missed by the remainder of the backoff.
  • After the backoff, and at the terminal exit of the loop - the attempt after which there is nothing left to retry, or one which failed with a non-retriable error - the loop asks the query status whether the query is still alive, via CurrentThread::checkIfNotCancelled, exactly as Client::HeadObject already 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 (the web disk, HTTP dictionaries, the data lake catalogs). The same question is asked once more in the failover loop of StorageURLSource, 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.
  • When the read is cancelled for another reason - the pipeline is being torn down because something else in the query has already failed, or the client has disconnected - the loop stops retrying and rethrows the error of its last attempt, which is the very exception the caller would have got once the attempts were exhausted.
  • StorageURLSource::cancel wakes 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 soft max_execution_time with timeout_overflow_mode = 'break' (CancelledByTimeout, which only ever comes from PipelineExecutor::checkTimeLimitSoft; a timeout with the throw overflow mode kills the query and arrives as CancelledByUser), or a consumer that has enough data (PartialResult) - is remembered, and StorageURLSource::generate then 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::cancel upgrades a PartialResult cancellation to the reason of a later hard one - for example, the first cancel of a client with partial_result_on_first_cancel followed by a KILL 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.
  • A cancellation stops StorageURLSource::initialize even where its helpers swallow the errors of the requests they make: getFirstAvailableURIAndReadBuffer rethrows 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), and ReadWriteBufferFromHTTP::tryGetFileSize / tryGetLastModificationTime rethrow it instead of treating the interrupted HEAD request 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). generate re-checks isCancelled after initialize, so it never pulls a chunk no one needs. initialize itself 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 metadata HEAD request. The check is repeated between the two metadata probes: when the shared HEAD request 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 fresh HEAD of its own.

How the review feedback is addressed {#how-the-review-feedback-is-addressed}

  • "it is really easy to misuse, because you don't get any feedback on the thread that was cancelled, and exit normally. A simple look at ReadWriteBufferFromHTTP::readBigAt shows how trivial is now to hit asserts due to a pipeline cancellation." - there is no silent break anymore: doWithRetries either does its work or throws, so a caller cannot mistake a cancellation for a success. The chassert in readBigAt stays untouched, nextImpl cannot report a cancellation as the end of the stream, and the row count cache cannot be filled from an interrupted read. Consequently StorageURLSource needs none of the isCancelled() 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?".
  • "part of the confusion comes from dealing with query cancellation and pipeline cancellation as the same thing, when they aren't, and how to report this properly both in logs and to the end user." - the two are now separate. Query cancellation is taken from the query status and reported as a cancellation. Pipeline cancellation only stops the retrying and reports the HTTP error that really happened, so it cannot race the exception of a peer source with a wrong message and URI - which is what broke the two reverted attempts. Both cases are logged with the reason at the point where the loop gives up.
  • "We don't propagate any errors here, so I don't understand why we skip the first attempt." - the attempt > 1 condition 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.
  • "we are sleeping without checks, that is, a cancel does not wake up the thread, which means we wait just to exit. We should use a condition variable and wait on it instead." - done, see above.
  • "slow request won't be dealt with, we'll wait until the request either finishes or times out" - still not addressed, as agreed in that review. A request that neither answers nor times out is not interruptible; that needs closing the socket from the outside and is left for a separate change.

Test {#test}

04615_kill_query_url_function starts a server that always answers 503, so that the query really is inside the retry loop - the test in the original pull request always answered 200 and never reached a second attempt. With 30 attempts and a backoff of 1 to 2 seconds, for both the HEAD and the GET request, 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 the 503 of the server as before.

Verified locally against a build of this branch: the killed query ends 3 ms after the KILL and is reported as Code: 394. DB::Exception: Query was cancelled. On an unpatched server the same query stays in system.processes with is_cancelled = 1 and keeps retrying for more than five minutes.

04691_url_function_partial_result_on_break_timeout covers the soft timeout: a glob over a file that the server serves completely and a URL that it always answers with 503, with a backoff of 1 to 2 seconds over 30 attempts. A query with max_execution_time = 1 and timeout_overflow_mode = 'break' succeeds with the rows of the first file in about a second, while the same query without the timeout still reports the 503 of the server. The partial result of the break mode 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_initialize covers a cancellation during initialization, whose helpers swallow the errors of the requests they make. Its server counts the requests to each path: after a soft break timeout interrupts the retries of the metadata HEAD request the data is never downloaded, and after it interrupts the retries of the first failover option of an a|b URL 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_timeout covers the row count cache (use_cache_for_count_from_files): a read of a slowly streaming URL interrupted by a soft break timeout leaves no entry in system.schema_inference_cache, while a complete read still caches the correct row count. generate records the count only when the read genuinely reached the end of the file - it checks the final status of its PullingPipelineExecutor and isCancelled on the source, as StorageMemory mutations 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_cancel covers a cancellation which lands between the failover options, where there is no request in flight for it to interrupt: an empty|data URL with engine_url_skip_empty_files = 1, where the empty file takes longer to be served than the soft break timeout 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 - which generate then discards - only for the soft cancellations, after which the query must still succeed (CancelledByTimeout of the break overflow mode, or PartialResult). 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: getFirstAvailableURIAndReadBuffer returns no buffer and initialize ends the stream, since nobody is left who needs the data.

04824_url_function_kill_after_partial_result_cancel covers a hard cancellation arriving after a soft one: the first cancel of a client with partial_result_on_first_cancel - after which the query must still succeed with its partial result - is followed by a KILL 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 the KILL has 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: its checkTimeLimitSoft poll observes a killed query as a soft timeout, and when that poll wins the race for the one-shot cancel reason of ExecutingGraph, 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_disconnect covers 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::cancel leaves 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 pin parallel_replicas_for_cluster_engines off: the rewrite of url to urlCluster would move the source into remote queries with their own query ids.

04829_url_function_no_metadata_requests_after_cancelled_head covers the fallback for servers which do not support HEAD: ReadWriteBufferFromHTTP::getFileInfo treats 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, which generate discards or fails with depending on the kind of the cancellation. The test answers the metadata HEAD with 400 only after a soft break timeout 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 cancelled HEAD, 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_attempt covers the exit of the retry loop after the attempt which has nothing left to retry. Its reader is the schema inference of the url table 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 its 503 response until the test has killed the query, and http_max_tries is 1, so the read is interrupted exactly where the retrying ends: the query must fail with QUERY_WAS_CANCELLED, while the same query which is not killed must still report the 503 of the server. On the code before the fix the killed query is reported with the 503 instead - which is the assertion the test makes.

05048_url_function_killed_query_while_option_error_unwinds covers the window right after that terminal exit: the kill lands while the error of the only failover option unwinds to the catch of getFirstAvailableURIAndReadBuffer, after the terminal check inside doWithRetries has already passed. The reader is again the schema inference of url, 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 answers 503, the unwinding pauses, the query is killed (visible in system.processes), and only then the source is released. The killed query must fail with QUERY_WAS_CANCELLED, while the same query which is not killed still reports the 503 of the server - on the code before the fix the killed query is reported with the 503, which is the assertion the test makes.

05054_url_function_hard_timeout_while_option_error_unwinds is its sibling for the other half of the same window: instead of a kill, the max_execution_time of the query runs out with the throw overflow mode while the error of the lone option is held on the same failpoint. A killed query is visible to CurrentThread::checkIfNotCancelled, a deadline which has merely passed is not - the asynchronous CancellationChecker turns 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 as TIMEOUT_EXCEEDED rather than with the 503, while the same query given enough time still reports the 503. Unlike the tests above, this one also passes before the fix, because the deadline the test waits for is delivered by the CancellationChecker within its own grid: it pins the contract, while the fix is what closes the window synchronously.

05076_url_function_hard_timeout_after_pull covers the same half of the window after pull in generate: PullingPipelineExecutor::pull polls the time limit only before a step, and the check after it used to ask only CurrentThread::checkIfNotCancelled, which sees a hard max_execution_time only once the CancellationChecker has turned it into a kill - so a deadline which passed while the chunk was being produced let that chunk through to ISource::prepare. The source now asks the query status about the time limit directly, as it already did before starting new I/O in initialize. The test holds the pulled chunk on storage_url_pause_after_pull (the failpoint of 04904) until the deadline of the query has passed and releases it: the query must fail with TIMEOUT_EXCEEDED and emit nothing, while the same query given enough time returns the row. Like 05054, it pins the contract rather than discriminating the fix: by the time the test can see that the deadline has passed, the CancellationChecker has usually turned it into a kill as well.

04843_url_function_no_metadata_probe_after_soft_cancel covers 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 soft break timeout has been delivered to the source (visible in the log), and then serves the file without a Content-Length, so the modification time and the size could only come from a HEAD request. 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 no HEAD request follows - the assertion fails on the code before the fix.

04844_url_function_parse_error_after_soft_cancel covers an error which the cancellation has nothing to do with: the server streams a few good rows, withholds the rest until a soft break timeout 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_cancel covers a cancellation which lands between the two metadata probes of initialize: the server tears down the metadata HEAD request 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 under partial_result_on_first_cancel = 1, so the delivery is under the test's control and cannot race the query the way a short max_execution_time did (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 second HEAD request: the query succeeds with its empty partial result and the server sees exactly one HEAD - the assertion fails on the code before the fix.

04869_url_function_stale_metadata_error_after_soft_cancel covers the opposite side of the same fallbacks: a metadata HEAD request 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 the HEAD request 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 with partial_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 the HEAD request.

04871_url_function_hard_cancel_upgrade_after_interrupted_read covers 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 before generate has 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 with partial_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 to Exception; 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_timeout covers the choosing of the failover option in a read which has no cancellation token at all: the schema inference of url reads without a StorageURLSource behind 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_time expires 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_backoff covers the retry backoff of the same token-less read: the first request fails immediately, a hard max_execution_time - the throw overflow mode - expires while the backoff is pending, and the query has to stop with TIMEOUT_EXCEEDED long before the backoff ends and without issuing the retry. The backoff polls QueryStatus::checkTimeLimit itself, so the stopping does not depend on the asynchronous canceller flipping the killed flag first.

05042_url_function_break_timeout_wakes_retry_backoff covers the polling of the token-backed wait: a query over the HTTP interface - where the pipeline runs under CompletedPipelineExecutor and, with a single url source sleeping in its backoff, no executor thread is left to poll the soft time limit - enters a 60-second backoff, and max_execution_time = 5 with the break overflow 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_finished pins the contract the token-driven exits rely on: a KILL QUERY which arrives after the source has already ended its stream still fails the query. PipelineExecutor::finalizeExecution calls checkTimeLimit before it looks at its own execution status, and QueryStatus::checkTimeLimit throws for a query whose cancelQuery has 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 while sleepEachRow still holds the rest of the pipeline; it must fail with QUERY_WAS_CANCELLED instead of returning a partial result.

05231_url_function_parallel_read_soft_cancel covers the same discard through the background workers of a ParallelReadBuffer, which FormatFactory::getInput uses for a large, seekable remote file. A worker woken from ReadWriteBufferFromHTTP::readBigAt by the cancellation stores its ReadInterruptedException as the background exception of the buffer, and ParallelReadBuffer::nextImpl rethrows it into reader->pull with its type intact, so a break-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's executeJob caught the exception of a processor by value, which sliced it to Exception, and rethrew the copy. The copy is there so that the same exception - several threads can rethrow one std::exception_ptr - is not modified in place, but it was made even when nothing was added to it, and checkCanAddAdditionalInfoToException adds nothing to a QUERY_WAS_CANCELLED. Since the interrupted read is thrown inside the source's own pipeline, StorageURLSource::generate always 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: copyMutableException rethrows through the virtual Poco::Exception::rethrow, which throws a plain Exception for a type that does not override it. The background tasks of the native Parquet reader use it, in Parquet::Prefetcher::rethrowException and Parquet::ReadManager::read, so a softly cancelled positional read of a column chunk reached StorageURLSource::generate unrecognizable and failed the query. ReadInterruptedException now overrides clone and rethrow, and 05232_url_function_parquet_soft_cancel pins it with a server which reports a real Parquet file as seekable and then holds the range requests of the column chunks.

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):

KILL QUERY, query timeouts and client disconnects now stop a query that reads over HTTP (for example over the url table 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

  • Merged into: 26.10.1.708-master (included in 26.10 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a4f1df4]

Summary: ✅


AI Review

Summary

This PR makes url/HTTP reads react promptly and correctly to cancellation, soft and hard timeouts, disconnects, and failover races, including the positional-read and background-reader paths. I re-checked the current head against the prior review threads and the final code in ReadWriteBufferFromHTTP, StorageURLSource, and ExecutionThreadContext; the remaining soft-cancel resource-retention issue is fixed by releasing the reader from prepare() on terminal Finished states, and I did not find a new correctness issue on top of the current head.

Final Verdict

✅ Approve

LLVM Coverage Report

Measured on commit a4f1df4.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 297/311 (95.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 1, 2026
Comment thread src/IO/ReadWriteBufferFromHTTP.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@Algunenano, your review of #104089 is addressed here - the description lists the points one by one, but in short:

  • The silent break is gone. doWithRetries now always either does its work or throws, so a cancellation can no longer look like a success to a caller. That leaves the chassert in readBigAt alone, and removes the need for the cancellation checks after every buffer operation in StorageURLSource.
  • Query cancellation and pipeline cancellation are no longer treated as the same thing. A killed or timed out query is reported through the query status with CurrentThread::checkIfNotCancelled (the same thing Client::HeadObject does for S3), so the user gets QUERY_WAS_CANCELLED, TIMEOUT_EXCEEDED or the client-disconnect exception. A pipeline that is being torn down after an error elsewhere only stops the retrying and rethrows the error of the last attempt, so nothing fabricates a cancellation that could race the real exception of a peer source.
  • The backoff waits on a condition variable, so a cancellation wakes the thread instead of being noticed after the wait has expired. Locally the killed query now ends 3 ms after the KILL, where an unpatched server keeps retrying for more than five minutes with is_cancelled = 1.
  • The attempt > 1 condition is gone: the check sits where the loop decides to wait and try again, which can only be reached after an attempt has failed.
  • Slow requests are still not interruptible, as you did not expect that one to be addressed here.

@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.

Comment thread src/Storages/StorageURL.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

`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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI red was Stress test (arm_msan): Logical error: 'or_argument_nodes.size() > 1' from the AST fuzzer in LogicalExpressionOptimizerPass. It is unrelated to this change (url cancellation) and is already tracked: #112654 - it also fires on master and on unrelated PRs.

Also merged master and addressed the AI review blocker about the soft break timeout.

Comment thread src/Storages/StorageURL.cpp Resolved
…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.
Comment thread src/Storages/StorageURL.cpp Resolved
alexey-milovidov and others added 2 commits August 4, 2026 18:20
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit 4df663a - all three reds are unrelated to this change (url cancellation code is not involved in any of them):

@groeneai, investigate the last one - the merge(REGEXP) planning livelock that ignores cancellation: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112930&sha=4df663ab92d95eae28fa0c990234fb044ad89c81&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 - and provide a fix in a separate PR. If a fix is already in progress, link it here.

Master is merged and the review finding is addressed in 360bd3a, so the next CI run is on the updated branch.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Confirmed, and confirmed from the artifact rather than by agreement. hung_check.log has exactly two rows, and they are two different classes.

Row 1 is your fuzzed merge(REGEXP('.+'), '') JOIN: is_cancelled: 1, elapsed: 2682.3 s, read_rows: 0, single thread 15241. Its stack is plan-time throughout, and your two frames are there verbatim: ensureColumnMembershipSetsArePopulated -> tryResolveIdentifierFromTableExpression -> tryResolveIdentifierFromJoinTree -> QueryAnalysisPass::run -> ReadFromMerge::getModifiedQueryInfo -> createChildrenPlans (StorageMerge.cpp:849) -> applyFilters (:1790) -> optimizePrimaryKeyConditionAndLimit -> QueryPlan::optimize (:812) -> buildQueryPipeline (InterpreterSelectQueryAnalyzer.cpp:415). Nothing on it belongs to this PR: your diff is 10 files under ReadWriteBufferFromHTTP / StorageURL plus url tests, none reachable from QueryPlan::optimize.

Row 2 is the UNDROP TABLE test_3.t busy-wait, so #113263 covers it. The two rows differ in kind, which matters below: row 2 has three blocking frames (clock_nanosleep under DatabaseCatalog::undropTable), row 1 has none.

Three things I had not measured before:

It is not only KILL that is ignored, the query's own deadline is too. Row 1 ran with max_execution_time = 10 and stopped at 2682 s, 268x over. That limit is only ever checked from execution-side code (ReadProgressCallback.cpp:51, PipelineExecutor::execute -> checkTimeLimit at :201, PullingPipelineExecutor), and QueryPlan::optimize runs inside buildQueryPipeline, before all of it. So no deadline of any kind applies during planning, and the timeout is only observed at the boundary afterwards. This is a cheaper acceptance oracle than KILL: max_execution_time = 1 on this query should fail in about a second, and currently does not.

The ProfileEvents on that row understate the stuck time by about 170x, so they are not a usable diagnostic for this family. They read QueryAnalysisMicroseconds 7.78 s, QueryPlanBuildMicroseconds 4.53 s, QueryPlanOptimizeMicroseconds 4.07 s, roughly 16 s against 2682 s elapsed. ProfileEventTimeIncrement increments in its destructor (ElapsedTimeProfileEventIncrement.h:35), so the iteration currently stuck inside optimize has contributed nothing yet, and the stack shows executeASTFuzzerQueries, so what is there is the sum over earlier completed variants of the same query_id. What actually places the time before execution is the stack plus read_rows: 0 and the total absence of execution-side counters, not the timers.

The msan amplification has a specific site. Below your two frames the leaf is msan's own __sanitizer_dtor_callback_fields -> PoisonMemory -> StackDepotBase::Put, under DB::Identifier::~Identifier(). The StorageMerge.cpp:1062 loop constructs one Identifier per required column per source table, so msan pays a stack-depot insert on every destructor.

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 checkTimeLimit|throwIfKilled|isCancelled|is_killed), so once it merges this query becomes linear yet stays uninterruptible for however long analysis takes. I searched for an open PR adding a plan-time cancellation check and found none. Of the issues, #113003 is the closer match: it shares the enclosing frames exactly and its second point asks for precisely this checkpoint. #47272 is a different mechanism, threads blocked in a syscall to be woken so they return EINTR, which fits row 2 but not row 1.

For the fix shape the precedent is already inside QueryPlan::optimize: JoinOrderOptimizer::checkLimits (joinOrder.cpp:461-467) takes query_status from CurrentThread::tryGetQueryContext() -> getProcessListElementSafe() (:317) and calls checkTimeLimit() from its enumeration loop. It is the only cancellation check in all of src/Processors/QueryPlan/Optimizations; src/Analyzer and src/Planner have none. The :1062 loop already has context in scope, so the same call fits there and in the per-source-table loop in createChildrenPlans. A fix task owns this gap at full effort and I will post its PR link here when it opens.

Nothing needed from me on the other two reds; #96656 and #107619 cover them.

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

99 object files changed (+65.88 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageURL.cpp.o 1.19 MiB 1.21 MiB +24.35 KiB (+2.00%)
src/CMakeFiles/clickhouse_common_io.dir/IO/ReadWriteBufferFromHTTP.cpp.o 263.89 KiB 286.72 KiB +22.82 KiB (+8.65%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

9328 translation units recompiled, 11426 s compile time in total, 9044 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR for the ReadFromMerge::createChildrenPlans plan-time cancellation hung check on my
CI finish ledger: #113415 (external, open).

I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical
guard at the identical call site, so I dropped mine rather than open a duplicate. My analysis and
the one coverage gap I measured are in
#113415 (comment).

alexey-milovidov and others added 3 commits August 5, 2026 11:22
`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]>
Comment thread src/Storages/StorageURL.cpp Resolved
…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]>
alexey-milovidov and others added 2 commits September 21, 2026 04:38
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the run on 30bed7e322c2fed4cd02f62513bdc12511e2c383 - one red was ours and is fixed, the other two are unrelated and tracked.

Stateless tests (amd_debug, flaky check) - 05232_url_function_parquet_soft_cancel was ours and is fixed in 2bb4119268ee. It failed one run out of 25 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 after 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 among 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: the footer and the metadata of a Parquet file live in the last bytes of the file, so a range that begins before that tail is a read of the data and is always held. Measured with a probe of the requests the query makes, on a 16995018-byte file: HEAD, then bytes=16929482-16995017 and bytes=16993467-16994077 (the tail reads of Reader::readFileMetaData, which reads the last 64 KiB), then bytes=4-3997578 - the read of the data, which is the one that is held. The structure of the url table function is now given explicitly, because schema inference reads the whole file sequentially in a request without a Range header, which the server must answer in full. max_execution_time is raised from 3 to 10 seconds, above the metadata phase even on a loaded sanitizer runner, and http_max_tries to 20, so that the retry budget of the held read stays far above the limit and the read is still being retried when the limit fires.

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 curl processes off the runner on which the query is being timed.

Verified locally against a build of this branch: 5/5 PASS with randomized settings, 13 s each, and all 33 url tests of this branch pass. The previous version fails deterministically here in the way the CI observed once the data read is served in full.

The two other reds are unrelated:

The AI review on the previous head reported ✅ No new findings on the current head, and the single unresolved thread is the answered catch (...) { throw; } question (the code was removed in b3da8a6a1d1b).

Related: #121129
Related: #120462

Comment thread src/Storages/StorageURL.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the ⚠️ Request changes verdict on 2bb41192 in bb23a5019a85.

Minimum required action - release the inner pipeline and read buffer on every cancel-induced exit of StorageURLSource::generate: adopted. The teardown is now a release_reader lambda which runs on every exit from the loop; the only direct return {} left in the loop - the one for an exhausted list of URI options - is a break now, so it goes through it too. The finding is correct: ISource::work only marks the source finished and the processor is destroyed when the whole query is, so on a soft cancellation - a max_execution_time with the break overflow mode, which returns the partial result, or a consumer which has enough data - the decode and prefetch tasks of the native Parquet reader (only asked to stop by ParquetV3BlockInputFormat::onCancel, drained by shutdownTasks or by destruction), the HTTP session and its buffers stayed alive for the rest of the query.

Changelog category: adopted as well, Improvement -> Bug Fix (user-visible misbehavior in an official stable release). The entry stands: a KILL QUERY, a timeout or a client disconnect could leave a query stuck in the HTTP retries for minutes in stable releases.

Verified locally against a build of this branch: ninja clickhouse with zero errors and zero warnings, and 33/33 of the branch's url tests pass with randomized settings, including 05229_url_function_kill_after_source_finished, 05231_url_function_parallel_read_soft_cancel and 05232_url_function_parquet_soft_cancel, which are the ones that exercise the soft-cancel paths the finding is about.

The branch was merged with master earlier today and no check had failed on 2bb41192 when this was pushed, so there is nothing else outstanding here.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Sep 21, 2026
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the run on bb23a5019a85 — the one real red was ours and is fixed in 1a80fe54b903; the second is its cascade.

Build (arm_tidy) was ours. clang-tidy failed the build with

src/Storages/StorageURL.cpp:612:13: error: ambiguous call to 'reset()' on a pointee of a smart pointer,
prefer more explicit approach [readability-ambiguous-smartptr-reset-call,-warnings-as-errors]

pipeline is a std::unique_ptr<QueryPipeline> and both std::unique_ptr::reset and QueryPipeline::reset exist, so pipeline->reset() is ambiguous to the check. The release_reader lambda added in bb23a5019a85 for the previous review round wrote it in the short form; the end-of-file teardown it replaced used (*pipeline).reset(), which is what it uses now — same call, QueryPipeline::reset on the pointee, so there is no behaviour change.

Control-proved with clang-tidy restricted to that single check against this build tree: it reports the error verbatim on the previous form and is clean with the new one. The translation unit also recompiles with no errors and no warnings.

Finish Workflow / new_tests_check is a cascade of the above: Bugfix validation (functional tests, amd64/aarch64) were DROPPED (Dropped due to previous failure [Build (arm_tidy)]), so no per-arch bugfix-validation job could report OK. It will clear once the build passes.

Everything else on that run is green, and the AI review on bb23a5019a85 reports ✅ Approve with no remaining findings.

… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for 1a80fe54b903, and what a4f1df44948c changes.

Pushed: the AI Review follow-up on the soft-cancel teardown thread is adopted - the teardown is now the member function StorageURLSource::releaseReader, and StorageURLSource::prepare runs it whenever ISource::prepare reports Finished, because a cancellation which lands after a chunk was buffered finishes the source from prepare without generate ever running again. Details in the thread. Local: ninja clickhouse 4729 targets, 0 errors 0 warnings; 05229, 05231, 05232 all PASS.

The two reds on 1a80fe54b903 are not this PR:

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Very interesting.

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit e0800b3 Sep 26, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the url-function-cancellation branch September 26, 2026 00:58
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants