Skip to content

Improve canceling queries with url() function - #104089

Closed
rvasin wants to merge 13 commits into
ClickHouse:masterfrom
arenadata:ADQM-4520
Closed

rvasin wants to merge 13 commits into
ClickHouse:masterfrom
arenadata:ADQM-4520

Conversation

@rvasin

@rvasin rvasin commented May 5, 2026

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Improve canceling queries with url() function by checking query cancellation between HTTP retry attempts.

This PR fixes reverted PRs #102801 and #104014

@rvasin

rvasin commented May 5, 2026

Copy link
Copy Markdown
Contributor Author

@Algunenano @murphy-4o @vdimir I have fixed the cancellation callback in ReadWriteBufferFromHTTP::doWithRetries. Please assign can be tested probably after merging the reverting PR #104077

@vdimir vdimir added the can be tested Allows running workflows for external contributors label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0ee276]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Trying to execute PLACEHOLDER action (STID: 1611-343c) FAIL cidb, issue
Stress test (arm_msan) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 5782-3461) FAIL cidb
BuzzHouse (amd_debug) FAIL
Logical error: Mutation of Memory table produced incomplete output: A (STID: 2380-2e8c) FAIL cidb

AI Review

Summary

This PR wires a cancellation callback into ReadWriteBufferFromHTTP and uses it from StorageURLSource so url reads can stop retrying after pipeline cancellation. The current shape still makes doWithRetries return normally on cancellation, leaving callers to infer cancellation with ad hoc checks, and the new stateless test does not exercise the retry path changed by this PR.

Findings

⚠️ Majors

  • [src/IO/ReadWriteBufferFromHTTP.cpp:328] doWithRetries still treats cancellation as a normal helper return: the callback only breaks the retry loop, so nextImpl, readBigAt, and metadata callers cannot distinguish “cancelled between retries” from EOF, a short read, or missing metadata unless every caller remembers to check the same cancellation flag immediately afterwards. That violates the retry helper contract because cancellation becomes an implicit side channel rather than an explicit outcome, and future or existing call sites can easily observe it as successful completion. Suggested fix: make doWithRetries propagate an explicit result, for example Completed / Cancelled, and require each caller to handle Cancelled before returning EOF, short reads, or cacheable state.
Tests
  • ⚠️ [tests/queries/0_stateless/04078_kill_query_url_function.sh:34] The regression test still does not force a retriable failure, so doWithRetries never reaches attempt > 1, which is the only place this PR checks the new cancellation callback. Sleeping in do_HEAD or do_GET only covers cancellation during an in-flight request, not cancellation between HTTP retry attempts. Please make the server fail the first request in a retriable way, then issue KILL QUERY while the retry loop is waiting or about to start the next attempt.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: propagate cancellation from doWithRetries explicitly instead of returning normally, and add a focused test that actually enters a second HTTP retry attempt before cancellation.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 5, 2026
Comment thread src/IO/ReadWriteBufferFromHTTP.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/IO/ReadWriteBufferFromHTTP.cpp Resolved
@rvasin

rvasin commented May 8, 2026

Copy link
Copy Markdown
Contributor Author

Failed test is not related.

@rvasin

rvasin commented May 12, 2026

Copy link
Copy Markdown
Contributor Author

@Algunenano do you have any suggestions about improvement of this PR? I think the comment from AI about "free" port is not critical and instead of throwing an exception I have implemented silent loop exiting (and it seems working according to several CI runs).

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The problem that I see right now is that 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. I think 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.

Another related issue that we should address is that 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.

And finally, but this one I don't expect to address in this PR, is that slow request won't be dealt with, we'll wait until the request either finishes or times out.

for (size_t attempt = 1; attempt <= read_settings.http_max_tries; ++attempt)
{
/// Check cancellation since the second attempt to let the original HTTP errors propagate correctly on the first attempt.
if (attempt > 1 && cancellation_check && cancellation_check())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We don't propagate any errors here, so I don't understand why we skip the first attemp.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In fact the main reason why both of my PRs #104014 and #102801 because 02270_errors_in_files_s3 was failed. In have found in logs of the test that CANNOT_PARSE_INPUT_ASSERTION_FAILED was thrown. I reported it here. But I have to test it again to be sure. On my current "silent" approach when exiting on the first attempt some other s3 storage related tests were failed (because url() is used for minio in these tests). But all tests work fine when we exit on since the second attempt.

current_uri_options.size() == 1,
[this]() { return isCancelled(); });

/// getFirstAvailableURIAndReadBuffer makes HTTP request in ReadWriteBufferFromHTTP.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not check at the start of the loop?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is because inside getFirstAvailableURIAndReadBuffer there is the HTTP request:

            if (context_->getSettingsRef()[Setting::engine_url_skip_empty_files] && res->eof() && option != std::prev(end))

In fact res->eof() makes the request. AI reviewer have noticed it.
But it also make sense to add cancellation chat at the beginning of the loop. Or even before the loop.


curr_uri = uri_and_buf.first;
current_file_last_modified = uri_and_buf.second->tryGetLastModificationTime();
/// Check for cancellation because tryGetLastModificationTime makes HTTP request in buffer.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Another way could be throwing the exception. But we decided not to do that. Right now I don't see other simple variants. What do you think?

@rvasin

rvasin commented May 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@Algunenano thank you for reviewing this PR.

Let's create a TODO plan what should be done before merging this PR. Because it's not clear for me. Sorry for asking many questions I just want to be sure I have 100% understood you.

First of all I have implemented 2 approached and both have passed CI successfully:

  1. throwing exception (which is recommended now by AI reviewer).
  2. "silent" exit doWithRetries and then processing it with cancellation checks in StorageURLSource::StorageURLSource.

I suppose you are talking about improving/refactoring the 2nd approach (to make it more reliable)?
Because I don't see any 3rd or 4th approaches.

The problem that I see right now is that 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. I think 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.

What do you suggest to do? From my side I see 3 variants:

variant 1. we may make doWithRetries returning bool bool ReadWriteBufferFromHTTP::doWithRetries instead of void.
Then:

bool ReadWriteBufferFromHTTP::doWithRetries(std::function<void()> && callable,
                                            std::function<void()> on_retry,
                                            bool mute_logging) const
{
    // skip
    for (size_t attempt = 1; attempt <= read_settings.http_max_tries; ++attempt)
    {
        if (attempt > 1 && cancellation_check && cancellation_check())
            return false; 
        

// then in  ReadWriteBufferFromHTTP::readBigAt:
    if (doWithRetries(...))
        chassert(total_bytes_copied == initial_n || is_canceled);
    return total_bytes_copied;

variant 2. pass a cancellation parameter to doWithRetries() like is_canceled parameter in copyFromIStreamWithProgressCallback(*result.response_stream, to, n, progress_callback, &bytes_copied, &is_canceled);,
Then:

void ReadWriteBufferFromHTTP::doWithRetries(std::function<void()> && callable,
                                            std::function<void()> on_retry,
                                            bool mute_logging,
                                            bool * is_canceled) const
{
    // skip
    for (size_t attempt = 1; attempt <= read_settings.http_max_tries; ++attempt)
    {
        if (attempt > 1 && cancellation_check && cancellation_check())
            *is_canceled = true;
            break;
            
// then in ReadWriteBufferFromHTTP::readBigAt:
    cancelled_during_retries = doWithRetries(...)
    chassert(total_bytes_copied == initial_n || is_canceled || cancelled_during_retries);
    return total_bytes_copied;

variant 3:
Leave code of ReadWriteBufferFromHTTP::doWithRetries as it is then in ReadWriteBufferFromHTTP::readBigAt:

    doWithRetries(...)
    
    if (!is_canceled && cancellation_check && cancellation_check())
        is_canceled = true;
    chassert(total_bytes_copied == initial_n || is_canceled);

I think this 3rd variant may be better because- we already have cancellation_check as class member of ReadWriteBufferFromHTTP
So why should be add additional parameter to doWithRetries as in variant 2 or make it returning bool as in variant 1?

Another related issue that we should address is that 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.

You are absolutely right. I did not think at first that we are still waiting on retry. My primary purpose was to stop the retries on cancellation. So usage of the conditional variable will improve the cancellation speed even more.
Do you think I should implement it directly in this PR? I am afraid to break something it it. So I tried to make the changed minimal in this PR.

And finally, but this one I don't expect to address in this PR, is that slow request won't be dealt with, we'll wait until the request either finishes or times out.

Yes. Let's don't make to much changes in one PR. Probably it should be noted as TODO.

@Algunenano

Copy link
Copy Markdown
Member

@rvasin Please have a look at #104929

@rvasin

rvasin commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@rvasin Please have a look at #104929

It looks interesting. The cancellation problem itself is not easy and some more deeper-level refactoring is required as you suggested in the RFC. The question is cost as pointer by Sergey. I will try to take a closer look on Monday.

def do_HEAD(self):
if HEAD_SLEEP > 0:
time.sleep(HEAD_SLEEP)
self.send_response(200)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new test does not actually exercise the retry path this PR changes.

doWithRetries checks cancellation only on attempt > 1, but this handler always returns 200 for both HEAD and GET, so no retriable failure is generated and the code never enters a second attempt.

Please make the test force at least one retriable failure before success (for example, close the socket / return a retriable response on the first request), then KILL QUERY while the retry loop is active so this patch's behavior is actually covered.

@rvasin

rvasin commented May 26, 2026

Copy link
Copy Markdown
Contributor Author

@Algunenano what do you think is remaining to make in this PR? For sleep function I think it should be done in a separate PR. As written in your RFC we should use common sleeping functions sleepOrKilled / waitForOrKilled.

@Algunenano

Copy link
Copy Markdown
Member

@rvasin I'm sorry, but I don't want to keep adding partial workarounds in random places, so I'm not prioritizing this right now

@rvasin

rvasin commented May 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@Algunenano Improvement of query cancellation for url() function has two major ways:

  1. Exit early in the loop to avoid 10 retries. This is implemented now in PR and it was the original purpose of this PR. According to your RFC it's implemented now in the correct way. Please confirm. I could not find in the RFC statements against used approach.
  2. in ReadWriteBufferFromHTTP::doWithRetries replace sleepForMilliseconds(milliseconds_to_wait) with sleeping using conditional variable. I may implement it in my way because sleepOrKilled / waitForOrKilled is not yet ready (it's not clear when RFC is going to be accepted). I may implement my own implementation of sleepOrKilled in `ReadWriteBufferFromHTTP. Let me know.

@rvasin

rvasin commented May 26, 2026

Copy link
Copy Markdown
Contributor Author

@rvasin I'm sorry, but I don't want to keep adding partial workarounds in random places, so I'm not prioritizing this right now

So please explain what are the partial workarounds. List all items/tasks to be corrected and I will correct it.

@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 50/58 (86.21%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

@rvasin

rvasin commented May 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@vdimir, @devcrafter, @rschu1ze, @serxa, @yariks5s, @alexey-milovidov what do you think about this PR? The implemented loop exiting logic in ReadWriteBufferFromHTTP::doWithRetries is not the workaround solution. The similar approach is already used in ExpressionTransform/ExpressionActions and even mentioned in RFC as acceptable approach.

Thus is not workaround/temporal solution but it's production code. Without this PR ClickHouse should iterate in the loop through all 10 retries until it finally exits. Hence in current master it takes more than 10 minutes to cancel the query with url() on slow/unresponsive connections.

The additional improvement proposed by @Algunenano to replace current waiting sleepForMilliseconds(milliseconds_to_wait) by sleepOrKilled proposed by him RFC is a good idea. But RFC must first be accepted and it may take weeks or months. While after merging this PR ClickHouse may benefit from early retry loop exiting already now.

As we don't implement many things in one PR it's better to make improvements on replacing sleepForMilliseconds(milliseconds_to_wait) in the next PR (accompanied by new unit tests). Also the test written for this PR is production-ready test because it handles almost all aspects of unresponsive connections, also after several CI runs it was never failed. Thus.the test may be used without changes even in the next PR when the sleepForMilliseconds will be replaced.

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Dear @Algunenano, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@Algunenano Algunenano self-assigned this Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Dear @Algunenano, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

MemorySanitizer: use-of-uninitialized-value (STID: 5782-3461)

That's very bad :(

@alexey-milovidov

Copy link
Copy Markdown
Member

Status update on the red CI checks: all three are from the May 28 run (commit c0ee276) and are unrelated to this change.

  • AST fuzzer: Logical error: Trying to execute PLACEHOLDER action — was tracked in Logical error: Trying to execute PLACEHOLDER action (STID: 1611-343c) #105501, fixed and closed on 2026-06-21, so merging master clears it.
  • Stress test (arm_msan): MemorySanitizer: use-of-uninitialized-value in WriteBufferFromFileDescriptorDiscardOnFailure::nextImpl — this is the QueryProfiler signal handler writing a trace while the signal interrupted the MSan allocator; it does not touch the HTTP retry code changed here, and CIDB shows zero occurrences of this failure in the last 30 days.
  • BuzzHouse: Logical error: Mutation of \Memory` table produced incomplete output — also unrelated (StorageMemory` mutation path) and has zero occurrences in CIDB in the last 30 days.

@rvasin the branch now conflicts with master in src/IO/ReadWriteBufferFromHTTP.h. Maintainer edits are disabled on the fork, so we cannot push a resolution — please merge the latest master to resolve the conflict and get a fresh CI run. The open design question raised by @Algunenano (partial workaround vs. the approach in #104929) still needs a maintainer decision before this can move forward.

@rvasin

rvasin commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

MemorySanitizer: use-of-uninitialized-value (STID: 5782-3461)

That's very bad :(

@alexey-milovidov
I have left the branch in unstable state because at the beginning the branch was stable (all tests were passed, no memory leaks etc) and we had some discussions with Raul and I have implemented several suggestions, then I asked some questions and I had to answer so I started to implement many clickhouse-gh-suggested corner cases/paths, as result the branch became dirty (with memory leaks).

I asked what was left to implement, but with lack of answer I switched working on other query cancellation improvement tasks while still waiting for maintainer's feedback.

So I may restart working on the task because query cancellation in ReadWriteBufferFromHTTP is important because it is used in more that 8 parts of ClickHouse codebase.

Now I understand that for future tasks in case of waiting the answer from reviewer it's better to not leave the branch in unstable state.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @rvasin thanks for picking this back up — that plan sounds right.

Two concrete things to unblock the mechanical side, since maintainer edits are disabled on arenadata/ClickHouse so we cannot push the resolution for you:

1. The only merge conflict with current master is trivial. It is in src/IO/ReadWriteBufferFromHTTP.h: your branch adds CheckCancelled and master (getCurrentURI / redirect-callback work) adds RedirectCallback at the same spot. It is a pure both-added conflict — keep both sides:

    using CheckCancelled = std::function<bool()>;
    using RedirectCallback = std::function<void(const Poco::URI &, const Poco::URI &)>;

    const Poco::URI & getCurrentURI() const { return current_uri; }

Everything else (ReadWriteBufferFromHTTP.cpp, StorageURL.cpp, StorageURL.h) auto-merges. I did this merge locally and syntax-checked both src/IO/ReadWriteBufferFromHTTP.cpp and src/Storages/StorageURL.cpp against current master — they compile.

2. The one substantive unresolved finding is about the test. tests/queries/0_stateless/04078_kill_query_url_function.sh never reaches a second attempt: doWithRetries checks cancellation only for attempt > 1, but the test handler answers 200 to both HEAD and GET, so no retriable failure is produced and the changed code path is not covered. The handler needs to fail retriably at least once (e.g. close the socket or return a retriable status on the first GET) before KILL QUERY is issued.

The design question raised by @Algunenano (this vs. the approach in #104929) is still a maintainer call and unchanged by the above.

@alexey-milovidov

Copy link
Copy Markdown
Member

since maintainer edits are disabled

We can't work on PRs where edits are disabled.

@alexey-milovidov

Copy link
Copy Markdown
Member

Superseded by #112930, which resubmits these changes from a branch in the main repository so that we can continue working on them (the commit keeps @rvasin as the author). Thank you, @rvasin!

Closing this one as superseded; the outstanding review feedback from @Algunenano is carried over to the new pull request.

alexey-milovidov pushed a commit that referenced this pull request Aug 1, 2026
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]>
pull Bot pushed a commit to weiyilai/ClickHouse that referenced this pull request Sep 26, 2026
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 ClickHouse#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
ClickHouse#102801 and
ClickHouse#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants