Repository navigation
Conversation
|
@Algunenano @murphy-4o @vdimir I have fixed the cancellation callback in |
|
Workflow [PR], commit [c0ee276] Summary: ❌
AI ReviewSummaryThis PR wires a cancellation callback into Findings
Tests
Final VerdictStatus: Minimum required actions: propagate cancellation from |
|
Failed test is not related. |
|
@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
left a comment
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
We don't propagate any errors here, so I don't understand why we skip the first attemp.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
Why not check at the start of the loop?
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
|
@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:
I suppose you are talking about improving/refactoring the 2nd approach (to make it more reliable)?
What do you suggest to do? From my side I see 3 variants: variant 1. we may make 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 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: 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
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.
Yes. Let's don't make to much changes in one PR. Probably it should be noted as TODO. |
| def do_HEAD(self): | ||
| if HEAD_SLEEP > 0: | ||
| time.sleep(HEAD_SLEEP) | ||
| self.send_response(200) |
There was a problem hiding this comment.
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.
|
@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 |
|
@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 |
|
@Algunenano Improvement of query cancellation for
|
So please explain what are the partial workarounds. List all items/tasks to be corrected and I will correct it. |
LLVM Coverage Report
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 |
|
@vdimir, @devcrafter, @rschu1ze, @serxa, @yariks5s, @alexey-milovidov what do you think about this PR? The implemented loop exiting logic in 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 The additional improvement proposed by @Algunenano to replace current waiting As we don't implement many things in one PR it's better to make improvements on replacing |
|
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. |
|
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. |
That's very bad :( |
|
Status update on the red CI checks: all three are from the May 28 run (commit c0ee276) and are unrelated to this change.
@rvasin the branch now conflicts with master in |
@alexey-milovidov 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. |
|
🕵 @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 1. The only merge conflict with current 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 ( 2. The one substantive unresolved finding is about the test. The design question raised by @Algunenano (this vs. the approach in #104929) is still a maintainer call and unchanged by the above. |
We can't work on PRs where edits are disabled. |
|
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. |
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]>
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]>
Changelog category (leave one):
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