Skip to content

Throw cancellation in WriteBuffer::next - #109786

Draft
Michicosun wants to merge 4 commits into
masterfrom
throw_cancellation_in_write_buffer_next
Draft

Michicosun wants to merge 4 commits into
masterfrom
throw_cancellation_in_write_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 WriteBuffer::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 [724fa7f]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel, 1/2) FAIL
Server died FAIL cidb
04061_completion_hint_selection_crash UNKNOWN cidb
03549_system_query_metric_log_with_queries_with_same_query_id UNKNOWN cidb
04338_kill_quorum_insert UNKNOWN cidb
01317_no_password_in_command_line UNKNOWN cidb
04409_skip_index_build_cancellation UNKNOWN cidb
04039_merge_tree_snapshot_teardown_race UNKNOWN cidb
03985_kill_query_dict_load UNKNOWN cidb
Stateless tests (amd_asan_ubsan, distributed plan, parallel, 2/2) FAIL
Server died FAIL cidb
00956_sensitive_data_masking UNKNOWN cidb
02366_cancel_write_into_file UNKNOWN cidb
04410_primes_source_cancellation UNKNOWN cidb
04028_kill_query_expression_cancelled UNKNOWN cidb
03984_kill_query_with_fill UNKNOWN cidb
OOM in dmesg FAIL cidb
Stateless tests (amd_llvm_coverage, 3/3) FAIL
Server died FAIL cidb
01019_parallel_parsing_cancel UNKNOWN cidb
01317_no_password_in_command_line UNKNOWN cidb
04099_detach_database_sync_cancellation UNKNOWN cidb
04335_distributed_plan_cancel UNKNOWN cidb
00417_kill_query UNKNOWN cidb
03549_system_query_metric_log_with_queries_with_same_query_id UNKNOWN cidb
04117_detach_database_kill_query UNKNOWN cidb
04095_wait_fp_pause_disable UNKNOWN cidb
Scraping system tables FAIL cidb
Integration tests (amd_llvm_coverage, 2/8) FAIL
test_postgresql_kill_query/test.py::test_kill_query_when_postgresql_cancel_connection_fails FAIL cidb
test_postgresql_kill_query/test.py::test_kill_infinite_query FAIL cidb
test_postgresql_kill_query/test.py::test_kill_query_during_generation FAIL cidb
Integration tests (amd_llvm_coverage, 3/8) FAIL
test_refreshable_mat_view_replicated/test.py::test_long_query_cancel FAIL cidb
test_refreshable_mat_view_replicated/test.py::test_query_fail FAIL cidb
test_refreshable_mat_view_replicated/test.py::test_query_retry FAIL cidb
test_refreshable_mat_view_replicated/test.py::test_circular_dependencies_survive_restart FAIL cidb
test_oom_canary/test.py::test_failpoint_confirmed_oom FAIL cidb
test_refreshable_mat_view_replicated/test.py::test_dependent_sees_latest_data_other_replica[True] FAIL cidb
test_refreshable_mat_view_replicated/test.py::test_dependent_sees_latest_data_other_replica[False] FAIL cidb
test_postgresql_protocol/test_kill_query.py::test_kill_query_during_output FAIL cidb
test_shutdown_wait_unfinished_queries/test.py::test_shutdown_wait_unfinished_queries FAIL cidb
Integration tests (amd_llvm_coverage, 4/8) FAIL
test_mysql_protocol/test_kill_query.py::test_kill_query_during_output FAIL cidb
test_build_sets_from_multiple_threads/test.py::test_set FAIL cidb
Integration tests (amd_llvm_coverage, 6/8) FAIL
test_refreshable_mat_view/test.py::test_long_query_cancel FAIL cidb
test_refreshable_mat_view/test.py::test_query_fail FAIL cidb
test_refreshable_mat_view/test.py::test_query_retry FAIL cidb
test_s3_cluster/test.py::test_iceberg_s3_cluster_read_task_failpoint FAIL cidb
test_refreshable_mv/test.py::test_refreshable_mv_in_replicated_db FAIL cidb
test_profile_max_sessions_for_user/test.py::test_profile_max_sessions_for_user_tcp FAIL cidb
test_profile_max_sessions_for_user/test.py::test_profile_max_sessions_for_user_postgres FAIL cidb
test_refreshable_mv/test.py::test_refresh_vs_shutdown_smoke FAIL cidb
test_inserts_with_keeper_retries/test.py::test_query_timeout_with_zk_down[ReplicatedMergeTree-default] FAIL cidb
test_refreshable_mv/test.py::test_pause FAIL cidb
15 more test cases not shown
Integration tests (amd_llvm_coverage, 8/8) FAIL
test_checking_s3_blobs_paranoid/test.py::test_query_is_canceled_with_inf_retries FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_adaptive_timeouts[node_with_inf_s3_retries] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_insert_to_s3_cancel_reports_cancellation FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_select_from_s3_cancel_reports_cancellation FAIL cidb
test_sqlite_kill_query/test.py::test_kill_query FAIL cidb
test_sqlite_kill_query/test.py::test_cancel_query FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL
Stateless tests (arm_asan_ubsan, targeted) ERROR

AI Review

Summary

This PR makes WriteBuffer::next a cancellation point, adds a thread-local blocker in TCPHandler::skipData, and adds new cancellation logging in QueryStatus. The main transport regression is still present: post-cancellation native-protocol writes still run on a cancelled query thread, so timeout / KILL QUERY handling can drop the socket instead of sending the final response and preserving the connection. There is also new unconditional error-level stack-trace logging on the common cancellation path. Verdict: block until the response path is exempted from the new cancellation point and the logging is removed or gated.

Missing context / blind spots
  • ⚠️ The PR motivation is still unclear from the description: it says only that it adds a cancellation point to WriteBuffer::next and asks “how many tests will fail”, so it is hard to tell which post-cancellation behavior changes are intentional versus accidental.
Findings

❌ Blockers

  • [src/Server/TCPHandler.cpp:1024-1143, src/IO/WriteBuffer.cpp:21] WriteBuffer::next now checks CurrentThread::checkIfNotCancelled, but the handler still flushes sendLogs, sendException, sendEndOfStream, and finalizeOut on the same cancelled query thread after TIMEOUT_EXCEEDED / QUERY_WAS_CANCELLED is already pending. The first of those flushes rethrows the cancellation, falls into cancelOut(out), and closes the socket instead of delivering the timeout / kill result or keeping the session reusable.
    Suggested fix: block cancellation checks around the whole post-cancellation response / cleanup section, or move the new cancellation point to a narrower layer that excludes protocol writes which must still complete after cancellation.

⚠️ Majors

  • [src/Interpreters/ProcessList.cpp:636-640] QueryStatus::throwProperExceptionIfNeeded is the common throw path for cooperative timeouts and KILL QUERY. Logging LOG_ERROR with a full StackTrace here means every worker thread that notices the cancellation emits an error-level stack trace for an expected control-flow event. On parallel or distributed queries this will flood server logs and add avoidable work exactly when queries are already timing out or being killed.
    Suggested fix: remove these logs before merge, or keep them behind a temporary debug-only guard that is off by default.
Tests
  • ⚠️ Add a focused native-TCP regression test that triggers TIMEOUT_EXCEEDED or KILL QUERY after some data has already been written, then verifies the client still receives the final packet and can reuse the same connection for a second query. None of the modified files add coverage for the response / connection-preservation path this PR changes.
Final Verdict

Status: ❌ Block
Minimum required actions:

  1. Exempt post-cancellation native-protocol writes from the new WriteBuffer::next cancellation point, or narrow the change so those writes still complete.
  2. Remove or gate the new cancellation stack-trace logging.
  3. Add focused regression coverage for timeout / kill response delivery on the native protocol.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 8, 2026
@CheSema CheSema self-assigned this Jul 8, 2026
@Michicosun
Michicosun marked this pull request as draft July 8, 2026 14:50
@Michicosun Michicosun added the no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test label Jul 8, 2026
Comment thread src/IO/WriteBuffer.cpp

void WriteBuffer::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.

WriteBuffer::next is now a cancellation point for every flush, but the TCP handler still uses out->next() to deliver the result of a server-side cancellation on the same query-attached thread. After a timeout or KILL QUERY, the outer handler reaches sendException / finalizeOut (src/Server/TCPHandler.cpp:1095-1143, 3056-3065, 3133-3141), and those paths flush through out->next(). With this new check, CurrentThread::checkIfNotCancelled() throws again before the packet is written, so we fall into the catch (...) { cancelOut(out); return; } path and drop the socket instead of sending the timeout / kill response or preserving the connection.

CancellationChecksBlockerInThread in skipData only fixes the post-error drain. We still need to exempt the protocol writes that must happen after cancellation (sendException, sendEndOfStream, finalizeOut), or keep this cancellation point at a narrower layer than generic WriteBuffer::next.


if (cancel_reason == CancelReason::TIMEOUT)
{
LOG_ERROR(getLogger("QueryStatus"), "Throwing TIMEOUT_EXCEEDED. Stack:\n {}", StackTrace().toString());

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.

QueryStatus::throwProperExceptionIfNeeded is the common cooperative-cancellation path, so this new LOG_ERROR + StackTrace fires for every ordinary timeout and for every worker that notices a KILL QUERY. On a parallel or distributed query that can produce many full stack traces for an expected control-flow event, flooding clickhouse-server.log and adding avoidable work exactly when the query is already timing out. Please keep this behind a temporary debug-only guard or drop it before merge; the same issue applies to the QUERY_WAS_CANCELLED log a few lines below.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@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.

@clickhouse-gh clickhouse-gh Bot added comp-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

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-io IO library: ReadBuffer / WriteBuffer and their implementations over files and memory, read and wr... no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test 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