Skip to content

Report cancellation instead of a network error for cancelled S3 requests - #108673

Merged
jkartseva merged 12 commits into
masterfrom
jkartseva/backup-restore-cancel-error
Jul 7, 2026
Merged

jkartseva merged 12 commits into
masterfrom
jkartseva/backup-restore-cancel-error

Conversation

@jkartseva

@jkartseva jkartseva commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

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

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

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 reports BACKUP_CANCELLED/RESTORE_CANCELLED in system.backups.

Version info

  • Merged into: 26.7.1.568 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ef5f275]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
04061_spilling_hash_join_overflow_limits FAIL cidb, issue ISSUE EXISTS
Stateless tests (arm_binary, parallel) FAIL
02346_text_index_parallel_replicas FAIL cidb IGNORED

AI Review

Summary

This PR routes failed S3 outcomes through CurrentThread::checkIfNotCancelled() so cancelled requests are reported as cancellation instead of stale S3/network errors, and it adds backup/restore plus s3() regression coverage. The main failed-outcome paths are covered, but the read contract is still incomplete for GetObject body-stream failures, and one new mock-control helper regresses the integration harness back to an unbounded curl call.

Findings
  • ⚠️ Major: [src/IO/S3/Client.cpp:711] The new cancellation translation only runs when doRequest() gets a failed AWS outcome. After a successful GetObject, the response body is read later in ReadBufferFromS3::nextImpl() / readBigAt(), and that retry loop (ReadBufferFromS3::processException()) 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 body rather than while building the AWS outcome.
    Suggested fix: translate cancellation in ReadBufferFromS3's read retry loop as well, for example by calling CurrentThread::checkIfNotCancelled() before retrying and before returning the final stream-read exception.
  • ⚠️ Major: [tests/integration/helpers/s3_mocks/broken_s3.py:135] setup_slow_get_answers() bypasses _apply() and calls curl without bounded retry or timeout. If the mock is briefly unreachable or overloaded, this helper can fail on the first transient refusal or hang until the container's TCP timeout, which makes the new cancellation tests flaky.
    Suggested fix: reuse _apply(url) here so slow_get gets the same capped retry behavior as the other mock-control endpoints.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 27, 2026
Comment thread src/IO/S3/Client.cpp Resolved
Comment thread src/IO/S3/Client.cpp Resolved
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]>
@jkartseva
jkartseva force-pushed the jkartseva/backup-restore-cancel-error branch from 8674fec to 61b41ab Compare June 27, 2026 01:45
jkartseva and others added 2 commits June 27, 2026 03:11
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]>
Comment thread src/IO/S3/Client.cpp Resolved
`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]>

Copilot AI left a comment

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.

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 HeadObject redirect/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.

Comment thread src/IO/S3/Client.cpp Resolved
@Michicosun Michicosun self-assigned this Jul 2, 2026
jkartseva and others added 2 commits July 3, 2026 03:55
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]>
@jkartseva
jkartseva marked this pull request as draft July 3, 2026 05:22
Comment thread src/Interpreters/ProcessList.cpp Resolved
Comment thread src/Interpreters/ProcessList.cpp Resolved
@jkartseva
jkartseva marked this pull request as ready for review July 4, 2026 02:39

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

LGTM, but maybe we need to remove most of the comments; in most cases, they're not needed since the method names are good enough.

Comment thread src/IO/S3/Client.cpp
if (result.IsSuccess())
return result;

CurrentThread::checkIfNotCancelled();

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.

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.

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.

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(

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 27/32 (84.38%) · Uncovered code

Full report · Diff report

@jkartseva
jkartseva added this pull request to the merge queue Jul 7, 2026
Merged via the queue into master with commit 9728786 Jul 7, 2026
172 of 175 checks passed
@jkartseva
jkartseva deleted the jkartseva/backup-restore-cancel-error branch July 7, 2026 02:29
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-restore-cancel-error

Report cancellation instead of a network error for cancelled S3 requests
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants