Skip to content

Throw cancellation in ReadBuffer::next - #109785

Draft
Michicosun wants to merge 4 commits into
masterfrom
throw_cancellation_in_read_buffer_next
Draft

Michicosun wants to merge 4 commits into
masterfrom
throw_cancellation_in_read_buffer_next

Conversation

@Michicosun

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

This patch adds a cancellation point to ReadBuffer::next, let's check how many tests will fail :)

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [10a3784]

Summary: ❌

job_name test_name status info comment
Build (arm_fuzzers) FAIL
Build ClickHouse FAIL cidb
Stateless tests (amd_msan, WasmEdge, sequential, 2/2) FAIL
Server died FAIL cidb
00992_system_parts_race_condition_zookeeper_long UNKNOWN cidb
00933_test_fix_extra_seek_on_compressed_cache UNKNOWN cidb
Logical error: Part A with metadata version B contains column C that is absent in table D with metadata version E (STID: 5052-4746) FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) FAIL
02122_join_group_by_timeout FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) FAIL
test_backup_restore_on_cluster/test.py::test_required_privileges FAIL cidb
test_backup_restore_on_cluster/test.py::test_system_users FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_shutdown_cancels_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_error_leaves_no_trash FAIL cidb
test_backup_restore_on_cluster/test_disallow_concurrency.py::test_concurrent_backups_on_different_nodes FAIL cidb
test_backup_restore_on_cluster/test_disallow_concurrency.py::test_concurrent_restores_on_same_node FAIL cidb
test_backup_restore_on_cluster/test_disallow_concurrency.py::test_concurrent_restores_on_different_node FAIL cidb
Integration tests (arm_binary, distributed plan, 1/4) FAIL
test_backup_restore_on_cluster/test.py::test_required_privileges FAIL cidb
test_backup_restore_on_cluster/test.py::test_system_users FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_shutdown_cancels_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_error_leaves_no_trash FAIL cidb
Integration tests (arm_binary, distributed plan, 4/4) FAIL
test_disable_insertion_and_mutation/test.py::test_disable_insertion_and_mutation FAIL cidb
Integration tests (amd_tsan, 1/6) FAIL
test_backup_restore_on_cluster/test.py::test_required_privileges FAIL cidb
test_backup_restore_on_cluster/test.py::test_system_users FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_shutdown_cancels_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_error_leaves_no_trash FAIL cidb
Integration tests (amd_msan, 1/8) FAIL
test_backup_restore_on_cluster/test.py::test_required_privileges FAIL cidb
test_backup_restore_on_cluster/test.py::test_system_users FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_shutdown_cancels_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_error_leaves_no_trash FAIL cidb
Integration tests (amd_llvm_coverage, 1/8) FAIL
test_backup_restore_on_cluster/test.py::test_required_privileges FAIL cidb
test_backup_restore_on_cluster/test.py::test_system_users FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_shutdown_cancels_backup FAIL cidb
test_backup_restore_on_cluster/test_cancel_backup.py::test_error_leaves_no_trash FAIL cidb
LLVM Coverage ERROR

AI Review

Summary

This PR adds a cancellation check to ReadBuffer::next, exempts the native TCP skipData cleanup path, and replaces the per-call cancellation lookup with a cached QueryStatusPtr. The TCP regression from the first revision is fixed, but the broader ReadBuffer::next contract change still breaks HTTP request draining after a cancelled or timed-out upload, so I would not merge this as-is.

Findings

⚠️ Majors

  • [src/IO/ReadBuffer.cpp:106, src/Server/HTTP/sendExceptionToHTTPClient.cpp:44, src/Server/HTTPHandler.cpp:567] Cancelled or timed-out HTTP uploads now lose keep-alive even when the unread body is still drainable. drainRequestIfNeeded reaches input_stream->ignoreAll(), which drives ReadBuffer::next(). The new unconditional CurrentThread::checkIfNotCancelled() throws before any more bytes are drained, the catch in drainRequestIfNeeded flips Keep-Alive off, and the connection is closed instead of being reused. TCPHandler::skipData got a CancellationChecksBlockerInThread, but the analogous HTTP cleanup path did not. Suggested fix: block cancellation checks around the HTTP drain as well, or narrow the new ReadBuffer::next check so cleanup drains can still resynchronize the connection.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 8, 2026
Comment thread src/IO/ReadBuffer.cpp Resolved
@CheSema CheSema self-assigned this Jul 8, 2026
@Michicosun
Michicosun marked this pull request as draft July 8, 2026 14:50
Comment thread src/IO/ReadBuffer.cpp

bool ReadBuffer::next()
{
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.

This changes the cleanup contract for every ReadBuffer, but only TCPHandler::skipData got an exemption. The HTTP exception path still drains unread POST bodies through the same ReadBuffer before reusing the socket (src/Server/HTTP/sendExceptionToHTTPClient.cpp:28-51, called from src/Server/HTTPHandler.cpp:567 and src/Server/HTTPHandler.cpp:586). After KILL QUERY or a timeout in throw mode, input_stream->isCanceled() is still false, so ignoreAll() reaches ReadBuffer::next() and this new checkIfNotCancelled() rethrows instead of draining. The catch there then flips Connection: close, so canceled or timed-out HTTP uploads lose keep-alive even though the body was still drainable. TCPHandler now blocks cancellation around skipData; HTTP needs the same treatment (or this check needs to be narrower) to avoid regressing connection reuse.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
pull Bot pushed a commit to weiyilai/ClickHouse that referenced this pull request Sep 21, 2026
A query killed or detached while loading skip-index marks kept reading from
object storage for minutes afterwards, because nothing between the marks
loader and S3 observes QueryStatus::is_killed. Reported by alexey-milovidov
on ClickHouse#113011: a query from 04010_text_index_incompelete_granules.sql sat for
~815 s with is_cancelled = 1 and read_rows = 0, tripping the hung check.

In that run's hung_check.log the query thread waits on the marks-load future
during skip-index analysis while the marks pool thread is inside
ReadBuffer::next below MergeTreeMarksLoader::loadMarksImpl, in
ReadBufferFromRemoteFSGather -> CachedOnDiskReadBufferFromFile -> S3.
throwIfKilled and checkIfNotCancelled appear zero times in the gather,
cached, encrypted-file and file-view read buffers, and under the thread
fuzzer every buffer fill costs an injection sleep.

Two nearer candidates do not work. The loader's own is_canceled flag is
written only by ~MergeTreeMarksLoader, which cannot run while loadMarks() is
on the stack, so it can only drop a task still queued in the pool. And the
granule loop in loadMarksImpl runs at most 26 trivial iterations over a
~624 byte marks file in this carrier, while the whole wait sits inside one
reader->eof() several frames lower. The interruption point therefore has to
be in the read buffer.

ReadBufferFromRemoteFSGather::readImpl now calls throwIfKilled before
current_buf->next(). readImpl is the complete set of blocking-fill sites: it
has exactly two callers, both in nextImpl, and everything nextImpl does
before the first is non-blocking, so a check at the top of nextImpl would be
redundant. The short-forward-seek drain in seek() is covered transitively,
since ReadBuffer::ignore loops on next -> nextImpl -> readImpl. The throw
precedes the SwapHelper, so the buffer is never left partially advanced.

The check is gated on an opt-in ReadSettings flag that only
makeIndexReaderStream sets, on its own copy of the settings, so every other
read is byte-identical. That scoping is required rather than stylistic:
QUERY_WAS_CANCELLED is not in isRetryableException, so an unscoped throw
makes CHECK TABLE plus KILL delete a healthy part, and ATTACH plus KILL
rename one broken-on-start. The generic form of this change, ClickHouse#109785, had to
invent a thread-local blocker for exactly those reads.

The QueryStatusPtr is resolved in ReadPipeline::build on the calling thread
and threaded in, beside the existing query_id hoist that exists for the same
reason: gather creators run lazily and may execute on threadpool workers
with no query context, where tryGetQueryContext returns null and the check
would be silently inert.

The new test is deterministic via a PAUSEABLE failpoint placed inside the
opt-in branch, so reaching it also proves the marks reader asked for
interruptible reads: park the marks read, KILL, single-step exactly one fill
with SYSTEM NOTIFY FAILPOINT, then assert the read unwinds instead of
fetching another buffer. Removing only throwIfKilled, and removing only the
opt-in, each redden it with a distinct message.

Index-analysis cancellation granularity as a whole, and the experimental
use_reader_executor path, are deliberately out of scope. This removes the
"ignores cancellation" half only, so it does not on its own clear the hung
check class.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @Michicosun, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

This branch has not been deployed

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

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants