Repository navigation
Report cancellation instead of a network error for cancelled S3 requests - #108673
Conversation
|
Workflow [PR], commit [ef5f275] Summary: ❌
AI ReviewSummaryThis PR routes failed S3 outcomes through Findings
Final VerdictChanges requested. |
When a query issuing S3 requests is cancelled mid-request (e.g. by KILL QUERY), the retry loop returned the last network error, so it was reported as S3_ERROR instead of cancelled. This affects any cancelled S3 request, including backups and restores. Surface QUERY_WAS_CANCELLED instead. Closes: ClickHouse/clickhouse-private#45444 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
8674fec to
61b41ab
Compare
Throwing a fresh QUERY_WAS_CANCELLED when the S3 retry loop stops on a killed query loses the real cause: a query cancelled by max_execution_time should be TIMEOUT_EXCEEDED, and a query cancelled with a stored exception (e.g. a backup/restore coordination failure on another host) should rethrow it. Use QueryStatus::throwIfKilled when a process-list element is available, falling back to a fresh QUERY_WAS_CANCELLED only when there is none. Add a max_execution_time backup test that keeps failing S3 uploads (retryable) until the timeout fires, proving the S3 layer reports TIMEOUT_EXCEEDED rather than QUERY_WAS_CANCELLED. Shorten the slow-answer timeouts in the cancellation tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Route HeadObject through headObjectInternal so the wrong-region and redirect retries also report cancellation instead of a stale S3/network outcome. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`throwIfQueryWasCanceled` runs after any failed S3 outcome. It previously called `Context::getProcessListElement`, which throws `LOGICAL_ERROR` when the `Context` still exists but the process-list entry has expired during query start/finish (the same edge that made `Context::isCurrentQueryKilled` use the safe accessor). That could replace the original S3/network error with an unrelated logical exception at a normal query-lifecycle edge. Switch to `getProcessListElementSafe`, which returns a null `QueryStatusPtr` instead of throwing. When the safe element is absent the existing `ThreadStatus::isQueryCanceled` fallback still reports the generic `QUERY_WAS_CANCELLED`, so a real cancellation is preserved while ordinary S3 failures are no longer turned into `LOGICAL_ERROR`. Addresses review feedback on #108673 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This pull request fixes misreporting of cancelled in-flight S3 operations by translating the stale final S3/network failure outcome into a proper query cancellation error (QUERY_WAS_CANCELLED). This improves user-facing error reporting for cancelled S3-backed operations (notably backups/restores).
Changes:
- Add a cancellation check in the S3 client retry/redirect paths to surface query cancellation (and preserve the true cancellation cause via the process-list element when available).
- Wrap
HeadObjectredirect/region handling so failed outcomes also report cancellation correctly. - Add integration regression tests for cancelled async S3 backup/restore, plus a test ensuring timeout cancellations still report
TIMEOUT_EXCEEDED.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
tests/integration/test_backup_restore_s3/test.py |
Adds regression coverage for cancelled async S3 backup/restore and ensures timeout cancellation cause is preserved. |
tests/integration/helpers/s3_mocks/broken_s3.py |
Extends the S3 mock to support slow GET/HEAD responses for reliable in-flight restore cancellation testing. |
src/IO/S3/Client.h |
Declares internal HeadObject helper to centralize retry/redirect handling and enable consistent cancellation surfacing. |
src/IO/S3/Client.cpp |
Implements cancellation surfacing in S3 request loops and HeadObject failure handling, preserving timeout/kill causes via process list. |
Introduce a reusable static method that throws the real cancellation cause of the current query (`TIMEOUT_EXCEEDED`, or an exception stored by `QueryStatus::cancelQuery`) instead of a generic error, falling back to `QUERY_WAS_CANCELLED` when the process-list element is gone. It is backed by a new `ThreadStatus` predicate set alongside `query_is_canceled_predicate`. Review: #108673 (review) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the local `throwIfQueryWasCanceled` helper with the shared `CurrentThread::checkIfNotCancelled`, called after a failed S3 outcome in `headObject` and `doRequestWithRetryNetworkErrors`. Drop the now-unused `ProcessList.h` include and the `QUERY_WAS_CANCELLED` error code, whose logic moved into `CurrentThread`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The fallback in CurrentThread::checkIfNotCancelled consulted the same process-list element as the primary check, so a cancellation was lost once the entry expired during query teardown. Record the killed state on the thread group (which outlives the entry) via QueryStatus::markKilled, and let ThreadStatus::isQueryCanceled consult this durable flag. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| if (result.IsSuccess()) | ||
| return result; | ||
|
|
||
| CurrentThread::checkIfNotCancelled(); |
There was a problem hiding this comment.
CurrentThread::checkIfNotCancelled() only translates failed AWS outcomes returned from doRequest(), but GetObject body reads still bypass it. Once client_ptr->GetObject(req) succeeds, ReadBufferFromS3::nextImpl() / readBigAt() handle stream timeouts and resets in their own retry loop (ReadBufferFromS3::processException()), and that path never checks whether the query was killed before retrying or surfacing the last network error. A KILL QUERY during an in-flight download can therefore still end as S3_ERROR for SELECT FROM s3(...) / RESTORE FROM S3 when the failure happens while consuming the response body rather than while creating the AWS outcome, so the read-path contract of this PR is still incomplete.
There was a problem hiding this comment.
A legit suggestion. The fix belongs in ReadBufferFromS3::processException. I'll take a closer look and file a follow-up PR if needs be, since ReadBufferFromS3 is a different subsystem.
| if count is not None: | ||
| url += f"&count={count}" | ||
|
|
||
| response = self._cluster.exec_in_container( |
There was a problem hiding this comment.
setup_slow_get_answers() bypasses _apply() and invokes curl with no bounded retry or timeout. The rest of MockControl uses _apply() specifically because the mock can be briefly unreachable or overloaded; here the new helper can fail on the first transient refusal or hang until the container's TCP timeout, which makes the new cancellation tests flaky in exactly the failure mode they are trying to exercise. Please route this through _apply(url) as well so the slow_get control path inherits the same capped retry behavior.
There was a problem hiding this comment.
There is no _apply() in broken_s3.py. Every MockControl method – reset, setup_action, setup_fake_puts, and the pre-existing setup_slow_answers this mirrors – issues the same single exec_in_container(["curl", "-s", url], nothrow=True) call.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 27/32 (84.38%) · Uncovered code |
`throwIfQueryWasCanceled` runs after any failed S3 outcome. It previously called `Context::getProcessListElement`, which throws `LOGICAL_ERROR` when the `Context` still exists but the process-list entry has expired during query start/finish (the same edge that made `Context::isCurrentQueryKilled` use the safe accessor). That could replace the original S3/network error with an unrelated logical exception at a normal query-lifecycle edge. Switch to `getProcessListElementSafe`, which returns a null `QueryStatusPtr` instead of throwing. When the safe element is absent the existing `ThreadStatus::isQueryCanceled` fallback still reports the generic `QUERY_WAS_CANCELLED`, so a real cancellation is preserved while ordinary S3 failures are no longer turned into `LOGICAL_ERROR`. Addresses review feedback on ClickHouse#108673 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Introduce a reusable static method that throws the real cancellation cause of the current query (`TIMEOUT_EXCEEDED`, or an exception stored by `QueryStatus::cancelQuery`) instead of a generic error, falling back to `QUERY_WAS_CANCELLED` when the process-list element is gone. It is backed by a new `ThreadStatus` predicate set alongside `query_is_canceled_predicate`. Review: ClickHouse#108673 (review) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-restore-cancel-error Report cancellation instead of a network error for cancelled S3 requests
clickhouse-local ignored max_execution_time for any query whose time was spent inside a blocking call that is not a pipeline task boundary. A query reading from an unresponsive s3 endpoint ran to the end of the S3 retry budget (s3_retry_attempts defaults to 500, which takes minutes) rather than failing at its limit: with max_execution_time = 2 against a port with nothing listening the query did not return within 60 s and printed no error code, where clickhouse server answers the identical query with 159 TIMEOUT_EXCEEDED after 3.5 s. CancellationChecker's worker thread is what turns a max_execution_time expiry into a query cancellation, and CancellationChecker::cancelTask is the only site that reaches QueryStatus::cancelQuery(CancelReason::TIMEOUT), so it is the only writer of the cancellation flag for a timeout. That worker was started in exactly one place in the tree, programs/server/Server.cpp. ProcessList::insert registers the deadline for every query, local included, so in local mode the deadline was registered and then never acted on. The S3 client's retry loop asks for precisely that flag in RetryStrategy::ShouldRetry, so it never learned the query was over its limit and ran its whole budget, while PullingAsyncPipelineExecutor::cancel joined the thread stuck inside it. The observing half was already in place: ClickHouse#108673 wired the S3 client to ThreadStatus::isQueryCanceled. Only the signal was missing. Start that worker in LocalServer::main, on a thread of its own rather than as the BackgroundSchedulePool task the server uses. Hosting it in that pool would create the pool, and local mode does not have one in every mode: DatabaseCatalog::createBackgroundTasks is skipped under --path unless the path already holds metadata, and skipped outright under --only-system-tables, which is the mode 04545_system_background_schedule_pool_no_side_effect uses to assert that the six schedule pools stay uncreated. Measured in that mode, a pool-hosted worker takes GlobalThread from 2 to 19 and BackgroundSchedulePoolSize from 0 to 512. A ThreadFromGlobalPool is not the alternative either. The worker never returns, so it would hold a slot of GlobalThreadPool, which max_thread_pool_size bounds, for the life of the process: measured in the same mode, with max_thread_pool_size = 4 both the pre-change binary and this one answer SELECT 1 in under 0.4 s, while a GlobalThreadPool-hosted worker hangs there and needs 5. A std::thread leaves GlobalThread and BackgroundSchedulePoolSize at their pre-change values, needs no background_schedule_pool_size > 1 guard since it cannot starve a pool of its last worker, and is how src/Interpreters/tests/gtest_cancellation_checker.cpp and src/Functions/tests/gtest_functions_stress.cpp already host workerFunction. Startup cost is unchanged (median over 20 SELECT 1 runs, base and fix). The declaration order relative to the existing SCOPE_EXIT({ cleanup(); }) is load bearing, because the worker parks in cond_var.wait until terminateThread() and cleanup() calls global_context->shutdown(); locals destruct in reverse declaration order, so terminate and join run before that shutdown, on the normal path and on any throw after that point. Getting it backwards would hang every clickhouse-local invocation at exit. Under timeout_overflow_mode = 'break' a stuck read still runs its full retry budget, identically in the server, because that arm calls checkTimeLimit() instead of cancelling; changing that would alter documented partial-result semantics, so it is left alone. Related: ClickHouse#120795 Co-Authored-By: Claude Opus 5 <[email protected]>
clickhouse-local ignored max_execution_time for any query whose time was spent inside a blocking call that is not a pipeline task boundary. A query reading from an unresponsive s3 endpoint ran to the end of the S3 retry budget (s3_retry_attempts defaults to 500, which takes minutes) rather than failing at its limit: with max_execution_time = 2 against a port with nothing listening the query did not return within 60 s and printed no error code, where clickhouse server answers the identical query with 159 TIMEOUT_EXCEEDED after 3.5 s. CancellationChecker's worker thread is what turns a max_execution_time expiry into a query cancellation, and CancellationChecker::cancelTask is the only site that reaches QueryStatus::cancelQuery(CancelReason::TIMEOUT), so it is the only writer of the cancellation flag for a timeout. That worker was started in exactly one place in the tree, programs/server/Server.cpp. ProcessList::insert registers the deadline for every query, local included, so in local mode the deadline was registered and then never acted on. The S3 client's retry loop asks for precisely that flag in RetryStrategy::ShouldRetry, so it never learned the query was over its limit and ran its whole budget, while PullingAsyncPipelineExecutor::cancel joined the thread stuck inside it. The observing half was already in place: ClickHouse#108673 wired the S3 client to ThreadStatus::isQueryCanceled. Only the signal was missing. Start that worker in LocalServer::main, on a thread of its own rather than as the BackgroundSchedulePool task the server uses. Hosting it in that pool would create the pool, and local mode does not have one in every mode: DatabaseCatalog::createBackgroundTasks is skipped under --path unless the path already holds metadata, and skipped outright under --only-system-tables, which is the mode 04545_system_background_schedule_pool_no_side_effect uses to assert that the six schedule pools stay uncreated. Measured in that mode, a pool-hosted worker takes GlobalThread from 2 to 19 and BackgroundSchedulePoolSize from 0 to 512. A ThreadFromGlobalPool is not the alternative either. The worker never returns, so it would hold a slot of GlobalThreadPool, which max_thread_pool_size bounds, for the life of the process: measured in the same mode, with max_thread_pool_size = 4 both the pre-change binary and this one answer SELECT 1 in under 0.4 s, while a GlobalThreadPool-hosted worker hangs there and needs 5. A std::thread leaves GlobalThread and BackgroundSchedulePoolSize at their pre-change values, needs no background_schedule_pool_size > 1 guard since it cannot starve a pool of its last worker, and is how src/Interpreters/tests/gtest_cancellation_checker.cpp and src/Functions/tests/gtest_functions_stress.cpp already host workerFunction. Startup cost is unchanged (median over 20 SELECT 1 runs, base and fix). The guard that stops the worker is registered before the existing SCOPE_EXIT({ cleanup(); }), so unwinding runs cleanup() first. cleanup() stops the protocol listeners a SYSTEM START LISTEN created and then waits up to five seconds for their connections to drain, and those in-flight queries are exactly the ones that still need a cancellation writer; clickhouse-server orders it the same way, terminating the worker only after waitServersToFinish. Measured with an external listener query reading a dead s3 endpoint under max_execution_time = 3 and still in flight when the local session ends: stopping the worker first leaves that query uncancelled for the whole drain and the client gets 32 ATTEMPT_TO_READ_AFTER_EOF after 5.65 s, against 159 TIMEOUT_EXCEEDED after 3.5 s in this order (3 runs each). The last arm of the test covers that; max_execution_time = 2 is what keeps it off the clock, since the S3 backoff is 25, 50 ... 1600 ms and its first 3200 ms sleep cannot begin before 3175 ms, so a two-second deadline is always noticed about a second before the drain expires. Outliving global_context->shutdown() does not hang exit, because the worker parks in cond_var.wait_for on its own mutex and holds nothing from the context: eleven launch shapes return the same status as the pre-change binary, all under 4 s, and the sixteen local-mode listener tests pass. Under timeout_overflow_mode = 'break' a stuck read still runs its full retry budget, identically in the server, because that arm calls checkTimeLimit() instead of cancelling; changing that would alter documented partial-result semantics, so it is left alone. Related: ClickHouse#120795 Co-Authored-By: Claude Opus 5 <[email protected]>
clickhouse-local ignored max_execution_time for any query whose time was spent inside a blocking call that is not a pipeline task boundary. A query reading from an unresponsive s3 endpoint ran to the end of the S3 retry budget (s3_retry_attempts defaults to 500, which takes minutes) rather than failing at its limit: with max_execution_time = 2 against a port with nothing listening the query did not return within 60 s and printed no error code, where clickhouse server answers the identical query with 159 TIMEOUT_EXCEEDED after 3.5 s. CancellationChecker's worker thread is what turns a max_execution_time expiry into a query cancellation, and CancellationChecker::cancelTask is the only site that reaches QueryStatus::cancelQuery(CancelReason::TIMEOUT), so it is the only writer of the cancellation flag for a timeout. That worker was started in exactly one place in the tree, programs/server/Server.cpp. ProcessList::insert registers the deadline for every query, local included, so in local mode the deadline was registered and then never acted on. The S3 client's retry loop asks for precisely that flag in RetryStrategy::ShouldRetry, so it never learned the query was over its limit and ran its whole budget, while PullingAsyncPipelineExecutor::cancel joined the thread stuck inside it. The observing half was already in place: ClickHouse#108673 wired the S3 client to ThreadStatus::isQueryCanceled. Only the signal was missing. Start that worker in LocalServer::main, on a thread of its own rather than as the BackgroundSchedulePool task the server uses. Hosting it in that pool would create the pool, and local mode does not have one in every mode: DatabaseCatalog::createBackgroundTasks is skipped under --path unless the path already holds metadata, and skipped outright under --only-system-tables, which is the mode 04545_system_background_schedule_pool_no_side_effect uses to assert that the six schedule pools stay uncreated. Measured in that mode, a pool-hosted worker takes GlobalThread from 2 to 19 and BackgroundSchedulePoolSize from 0 to 512. A ThreadFromGlobalPool is not the alternative either. The worker never returns, so it would hold a slot of GlobalThreadPool, which max_thread_pool_size bounds, for the life of the process: measured in the same mode, with max_thread_pool_size = 4 both the pre-change binary and this one answer SELECT 1 in under 0.4 s, while a GlobalThreadPool-hosted worker hangs there and needs 5. A std::thread leaves GlobalThread and BackgroundSchedulePoolSize at their pre-change values, needs no background_schedule_pool_size > 1 guard since it cannot starve a pool of its last worker, and is how src/Interpreters/tests/gtest_cancellation_checker.cpp and src/Functions/tests/gtest_functions_stress.cpp already host workerFunction. Startup cost is unchanged (median over 20 SELECT 1 runs, base and fix). The guard that stops the worker is registered before the existing SCOPE_EXIT({ cleanup(); }), so unwinding runs cleanup() first. cleanup() stops the protocol listeners a SYSTEM START LISTEN created and then waits up to five seconds for their connections to drain, and those in-flight queries are exactly the ones that still need a cancellation writer; clickhouse-server orders it the same way, terminating the worker only after waitServersToFinish. Measured with an external listener query reading a dead s3 endpoint under max_execution_time = 3 and still in flight when the local session ends: stopping the worker first leaves that query uncancelled for the whole drain and the client gets 32 ATTEMPT_TO_READ_AFTER_EOF after 5.65 s, against 159 TIMEOUT_EXCEEDED after 3.5 s in this order (3 runs each). The last arm of the test covers that ordering, and takes its verdict from the process's own log: the checker's cancellation record for that query id, stamped after the listeners were already stopped. The client-visible error cannot serve as the verdict there, because it only arrives once the S3 retry loop reaches its next attempt boundary, which the five-second drain does not bound: with the thread fuzzer a stateless flaky check arms (SLEEP_PROBABILITY 0.1, SLEEP_TIME_US_MAX 100000, inherited by every test process) a single attempt against a refused port was measured at 5.0 s, and teardown then closes the connection with no response at all. Outliving global_context->shutdown() does not hang exit, because the worker parks in cond_var.wait_for on its own mutex and holds nothing from the context: eleven launch shapes return the same status as the pre-change binary, all under 4 s, and the sixteen local-mode listener tests pass. Under timeout_overflow_mode = 'break' a stuck read still runs its full retry budget, identically in the server, because that arm calls checkTimeLimit() instead of cancelling; changing that would alter documented partial-result semantics, so it is left alone. Related: ClickHouse#120795 Co-Authored-By: Claude Opus 5 <[email protected]>
clickhouse-local ignored max_execution_time for any query whose time was spent inside a blocking call that is not a pipeline task boundary. A query reading from an unresponsive s3 endpoint ran to the end of the S3 retry budget (s3_retry_attempts defaults to 500, which takes minutes) rather than failing at its limit: with max_execution_time = 2 against a port with nothing listening the query did not return within 60 s and printed no error code, where clickhouse server answers the identical query with 159 TIMEOUT_EXCEEDED after 3.5 s. CancellationChecker's worker thread is what turns a max_execution_time expiry into a query cancellation, and CancellationChecker::cancelTask is the only site that reaches QueryStatus::cancelQuery(CancelReason::TIMEOUT), so it is the only writer of the cancellation flag for a timeout. That worker was started in exactly one place in the tree, programs/server/Server.cpp. ProcessList::insert registers the deadline for every query, local included, so in local mode the deadline was registered and then never acted on. The S3 client's retry loop asks for precisely that flag in RetryStrategy::ShouldRetry, so it never learned the query was over its limit and ran its whole budget, while PullingAsyncPipelineExecutor::cancel joined the thread stuck inside it. The observing half was already in place: ClickHouse#108673 wired the S3 client to ThreadStatus::isQueryCanceled. Only the signal was missing. Start that worker in LocalServer::main, on a thread of its own rather than as the BackgroundSchedulePool task the server uses. Hosting it in that pool would create the pool, and local mode does not have one in every mode: DatabaseCatalog::createBackgroundTasks is skipped under --path unless the path already holds metadata, and skipped outright under --only-system-tables, which is the mode 04545_system_background_schedule_pool_no_side_effect uses to assert that the six schedule pools stay uncreated. Measured in that mode, a pool-hosted worker takes GlobalThread from 2 to 19 and BackgroundSchedulePoolSize from 0 to 512. A ThreadFromGlobalPool is not the alternative either. The worker never returns, so it would hold a slot of GlobalThreadPool, which max_thread_pool_size bounds, for the life of the process: measured in the same mode, with max_thread_pool_size = 4 both the pre-change binary and this one answer SELECT 1 in under 0.4 s, while a GlobalThreadPool-hosted worker hangs there and needs 5. A std::thread leaves GlobalThread and BackgroundSchedulePoolSize at their pre-change values, needs no background_schedule_pool_size > 1 guard since it cannot starve a pool of its last worker, and is how src/Interpreters/tests/gtest_cancellation_checker.cpp and src/Functions/tests/gtest_functions_stress.cpp already host workerFunction. Startup cost is unchanged (median over 20 SELECT 1 runs, base and fix). The guard that stops the worker is registered before the existing SCOPE_EXIT({ cleanup(); }), so unwinding runs cleanup() first. cleanup() stops the protocol listeners a SYSTEM START LISTEN created and then waits up to five seconds for their connections to drain, and those in-flight queries are exactly the ones that still need a cancellation writer; clickhouse-server orders it the same way, terminating the worker only after waitServersToFinish. Measured with an external listener query reading a dead s3 endpoint under max_execution_time = 3 and still in flight when the local session ends: stopping the worker first leaves that query uncancelled for the whole drain and the client gets 32 ATTEMPT_TO_READ_AFTER_EOF after 5.65 s, against 159 TIMEOUT_EXCEEDED after 3.5 s in this order (3 runs each). The last arm of the test covers that ordering, and takes both stamps of its verdict from the process's own log: the checker's cancellation record for that query id, and the line an acceptor thread writes when its listen socket goes down. Reading the second one from the shell's clock instead compares two clocks, and that difference is not hypothetical: on the three jobs where this test failed, the two stamps came back 1 h, 2 h and 12 h apart for events 2 s apart, and a stateless-test job picks the machine time zone at random, so neither the size nor the sign of the difference is fixed. With the shell's zone and the process's zone deliberately made to differ, the earlier form of the arm fails 5 runs out of 5 and this one passes 5 out of 5. The client-visible error cannot serve as the verdict there, because it only arrives once the S3 retry loop reaches its next attempt boundary, which the five-second drain does not bound: with the thread fuzzer a stateless flaky check arms (SLEEP_PROBABILITY 0.1, SLEEP_TIME_US_MAX 100000, inherited by every test process) a single attempt against a refused port was measured at 5.0 s, and teardown then closes the connection with no response at all. Outliving global_context->shutdown() does not hang exit, because the worker parks in cond_var.wait_for on its own mutex and holds nothing from the context: eleven launch shapes return the same status as the pre-change binary, all under 4 s, and the sixteen local-mode listener tests pass. Under timeout_overflow_mode = 'break' the expiry does not cancel the query, identically in the server, because that arm calls checkTimeLimit() instead of cancelling; changing that would alter documented partial-result semantics, so it is left alone. A test arm pins that much and deliberately pins nothing more, because what ends the query instead is not stable. Measured against the same dead endpoint with an eight-attempt budget, the retries run out and S3_ERROR surfaces in 10 runs out of 10, while under the thread fuzzer a pipeline check stops the read first and the query returns an empty result, so an arm that also asserted S3_ERROR failed 8 runs out of 8 there. Asserting only that no timeout is reported and the process does not hang is 10 out of 10 under the fuzzer and 20 out of 20 without it, reddens 3 out of 3 with the mode dropped from the arm, and reads the same on a binary without this change. Related: ClickHouse#120795 Co-Authored-By: Claude Opus 5 <[email protected]>
clickhouse-local ignored max_execution_time for any query whose time was spent inside a blocking call that is not a pipeline task boundary. A query reading from an unresponsive s3 endpoint ran to the end of the S3 retry budget (s3_retry_attempts defaults to 500, which takes minutes) rather than failing at its limit: with max_execution_time = 2 against a port with nothing listening the query did not return within 60 s and printed no error code, where clickhouse server answers the identical query with 159 TIMEOUT_EXCEEDED after 3.5 s. CancellationChecker's worker thread is what turns a max_execution_time expiry into a query cancellation, and CancellationChecker::cancelTask is the only site that reaches QueryStatus::cancelQuery(CancelReason::TIMEOUT), so it is the only writer of the cancellation flag for a timeout. That worker was started in exactly one place in the tree, programs/server/Server.cpp. ProcessList::insert registers the deadline for every query, local included, so in local mode the deadline was registered and then never acted on. The S3 client's retry loop asks for precisely that flag in RetryStrategy::ShouldRetry, so it never learned the query was over its limit and ran its whole budget, while PullingAsyncPipelineExecutor::cancel joined the thread stuck inside it. The observing half was already in place: ClickHouse#108673 wired the S3 client to ThreadStatus::isQueryCanceled. Only the signal was missing. Start that worker in LocalServer::main, on a thread of its own rather than as the BackgroundSchedulePool task the server uses. Hosting it in that pool would create the pool, and local mode does not have one in every mode: DatabaseCatalog::createBackgroundTasks is skipped under --path unless the path already holds metadata, and skipped outright under --only-system-tables, which is the mode 04545_system_background_schedule_pool_no_side_effect uses to assert that the six schedule pools stay uncreated. Measured in that mode, a pool-hosted worker takes GlobalThread from 2 to 19 and BackgroundSchedulePoolSize from 0 to 512. A ThreadFromGlobalPool is not the alternative either. The worker never returns, so it would hold a slot of GlobalThreadPool, which max_thread_pool_size bounds, for the life of the process: measured in the same mode, with max_thread_pool_size = 4 both the pre-change binary and this one answer SELECT 1 in under 0.4 s, while a GlobalThreadPool-hosted worker hangs there and needs 5. A std::thread leaves GlobalThread and BackgroundSchedulePoolSize at their pre-change values, needs no background_schedule_pool_size > 1 guard since it cannot starve a pool of its last worker, and is how src/Interpreters/tests/gtest_cancellation_checker.cpp and src/Functions/tests/gtest_functions_stress.cpp already host workerFunction. Startup cost is unchanged (median over 20 SELECT 1 runs, base and fix). The guard that stops the worker is registered before the existing SCOPE_EXIT({ cleanup(); }), so unwinding runs cleanup() first. cleanup() stops the protocol listeners a SYSTEM START LISTEN created and then waits up to five seconds for their connections to drain, and those in-flight queries are exactly the ones that still need a cancellation writer; clickhouse-server orders it the same way, terminating the worker only after waitServersToFinish. Measured with an external listener query reading a dead s3 endpoint under max_execution_time = 3 and still in flight when the local session ends: stopping the worker first leaves that query uncancelled for the whole drain and the client gets 32 ATTEMPT_TO_READ_AFTER_EOF after 5.65 s, against 159 TIMEOUT_EXCEEDED after 3.5 s in this order (3 runs each). The last arm of the test covers that ordering, and takes both stamps of its verdict from the process's own log: the checker's cancellation record for that query id, and the line an acceptor thread writes when its listen socket goes down. Reading the second one from the shell's clock instead compares two clocks, and that difference is not hypothetical: on the three jobs where this test failed, the two stamps came back 1 h, 2 h and 12 h apart for events 2 s apart, and a stateless-test job picks the machine time zone at random, so neither the size nor the sign of the difference is fixed. With the shell's zone and the process's zone deliberately made to differ, the earlier form of the arm fails 5 runs out of 5 and this one passes 5 out of 5. The client-visible error cannot serve as the verdict there, because it only arrives once the S3 retry loop reaches its next attempt boundary, which the five-second drain does not bound: with the thread fuzzer a stateless flaky check arms (SLEEP_PROBABILITY 0.1, SLEEP_TIME_US_MAX 100000, inherited by every test process) a single attempt against a refused port was measured at 5.0 s, and teardown then closes the connection with no response at all. Outliving global_context->shutdown() does not hang exit, because the worker parks in cond_var.wait_for on its own mutex and holds nothing from the context: eleven launch shapes return the same status as the pre-change binary, all under 4 s, and the sixteen local-mode listener tests pass. Under timeout_overflow_mode = 'break' the expiry does not cancel the query, identically in the server, because that arm calls checkTimeLimit() instead of cancelling; changing that would alter documented partial-result semantics, so it is left alone. A test arm pins that much and deliberately pins nothing more, because what ends the query instead is not stable. Measured against the same dead endpoint with an eight-attempt budget, the retries run out and S3_ERROR surfaces in 10 runs out of 10, while under the thread fuzzer a pipeline check stops the read first and the query returns an empty result, so an arm that also asserted S3_ERROR failed 8 runs out of 8 there. Asserting only that no timeout is reported and the process does not hang is 10 out of 10 under the fuzzer and 20 out of 20 without it, reddens 3 out of 3 with the mode dropped from the arm, and reads the same on a binary without this change. The listener arm compares its two stamps against the start of teardown rather than against `Shutting down TCPServer`. An acceptor thread writes that marker once it is next scheduled after DB::TCPServer::stop() shuts its listen socket, so its distance from the start of teardown is a scheduling delay and not a property of the product: over 82 debug runs under the flaky check's thread fuzzer it stays within 23-218 ms, but on amd_tsan it reached 2.7 s and overran the arm's two-second deadline in 4 runs out of 50. Destroying the local connection is the first thing LocalServer::cleanup() does, and the session it owns logs `Logout` from that same thread, so that line stamps the moment teardown begins: over the same 82 runs it trails the kill by at most 73 ms and precedes the cancellation by 1.838 s at worst. It is also the boundary the guard order is about, because with the two SCOPE_EXITs swapped the checker is terminated before cleanup() runs. The arm reddens 5 runs out of 5 with them swapped, 3 out of 3 on a binary without this change, and still reddens when a replayed log moves the cancellation ahead of teardown, so it goes on asserting the window and not merely the cancellation. Related: ClickHouse#120795 Co-Authored-By: Claude Opus 5 <[email protected]>
When a query issuing S3 requests is cancelled mid-request (e.g. by KILL QUERY), the retry loop returned the last network error, so it was reported as S3_ERROR instead of cancelled. This affects any cancelled S3 request, including backups and restores. Surface QUERY_WAS_CANCELLED instead.
Closes: https://github.com/ClickHouse/clickhouse-private/issues/45444
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A query reading from or writing to S3 that is cancelled (e.g. by
KILL QUERY) while an S3 request is in flight is now reported as cancelled instead of with a misleading network/S3 error. In particular, a cancelled backup or restore to S3 now reportsBACKUP_CANCELLED/RESTORE_CANCELLEDinsystem.backups.Version info
26.7.1.568(included in26.7and later)