Skip to content

Handle query cancellation in S3 reads and part recovery - #116257

Open
otselnik wants to merge 151 commits into
ClickHouse:masterfrom
otselnik:fix/prefetch-query-cancellation
Open

otselnik wants to merge 151 commits into
ClickHouse:masterfrom
otselnik:fix/prefetch-query-cancellation

Conversation

@otselnik

@otselnik otselnik commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

MergeTree prefetch and asynchronous marks loading could continue issuing S3 reads after max_execution_time with timeout_overflow_mode = 'throw', or after KILL QUERY. Cancellation raised during metadata reads could also enter corruption recovery, reporting or detaching healthy parts or treating a valid backup as damaged.

Cancellation is checked before scheduling work, when a task starts, after range refinement, and before subsequent S3 reads or retries. A worker that observes cancellation starts no further S3 request; an in-flight network call is allowed to complete.

The recovery changes also affect shared MergeTree code: CHECK TABLE, part and projection loading during ATTACH TABLE, index loading and rebuilding, and validation of restored parts. These paths preserve cancellation instead of classifying it as corruption. Mandatory transaction rollback, index publication, and synchronous outdated-part cleanup can finish after cancellation, including metadata reads needed for cleanup. Genuine storage failures retain their existing recovery behavior.

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

Stop outstanding MergeTree prefetch and asynchronous marks-loading work from issuing additional S3 reads after query timeout or KILL QUERY cancellation is observed. Preserve cancellation during CHECK TABLE, part and index loading, and restore validation without reporting healthy parts or backups as damaged. Allow required rollback and cleanup to complete after cancellation.


Workflow [PR]
Sync PR [sync-upstream/pr/116257]

@antonio2368 antonio2368 added the can be tested Allows running workflows for external contributors label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [adbdae5]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR stops additional S3 reads after query timeout or KILL QUERY, preserves cancellation through MergeTree part and index recovery, and protects mandatory cleanup. Reviewed head adbdae5759c0f6f59b7e5bd0d3428f0d274baa76 and all prior discussion. No new actionable findings or remaining bot-authored findings were identified in the current code.

Missing context / blind spots
  • ⚠️ Focused cancellation suites have no published results for this head yet; ASan builds are still running. Regression coverage is present, but runtime validation depends on the pending CI jobs. CI report.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ac288a450 with master 8157275d8 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

2100 object files changed (+94.75 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/FailPoint.cpp.o 680.22 KiB 708.18 KiB +27.96 KiB (+4.11%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

4718 translation units recompiled, 16651 s compile time in total, 4718 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +969.4 s (+6%) in total before that adjustment.

Job report

Comment thread src/IO/ReadBufferFromS3.cpp Resolved
Return explicit query-cancellation exceptions from `ReadBufferFromS3::processException` before incrementing `ReadBufferFromS3RequestsErrors` or logging an S3 failure. Cover the pre-request cancellation path in the S3 integration test.

PR: ClickHouse#116257
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
@otselnik

This comment was marked as outdated.

Comment thread src/IO/ReadBufferFromS3.cpp Resolved
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
Mark the non-Poco exception handlers in `QueryStatus` with `Ok:`
comments for `catch_all`, and suppress `bugprone-empty-catch` only
for the intentionally empty handler. Pointer identity still handles
exceptions shared by `copyMutableException`; runtime behavior is unchanged.

Related: ClickHouse#116257
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116257&sha=e08ab5b35cf51acf08ad17834417ce09aa9f3764&name_0=PR

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

Please build the cached TIMEOUT_EXCEEDED message with the elapsed time regardless of which thread throws first, and add a test for it.

Comment thread src/Interpreters/ProcessList.cpp Resolved
Comment thread src/Interpreters/ProcessList.cpp Resolved
@cla-assistant

cla-assistant Bot commented Nov 11, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ otselnik
❌ codex
You have signed the CLA already but the status is still pending? Let us recheck it.

Comment thread src/IO/ReadBufferFromS3.cpp Resolved
Distinguish an `ABORTED` raised by a merge or mutation cancellation predicate from a storage error. In `ReadBufferFromS3`, classify the caught error before checking cancellation for a retry.

Extend the existing `05621_s3_drop_outdated_parts_cancellation` test to stop a background merge before `GetObject` and check its `system.part_log` counters.

Review: ClickHouse#116257 (comment)

Related: ClickHouse#116257
Use `clickhouse_test_time_left` alongside the 60-second limit when polling `system.part_log`. Fail if the merge record is missing when the wait expires.

Related: ClickHouse#116257

@clickhouse-gh clickhouse-gh Bot 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.

AI review approves this commit, see the AI Review comment.

Skip the entire `QUERY_WAS_CANCELLED_BY_CLIENT` log record, including its
stack trace. The previous line filter removed the exception header but
printed constructor frames from `ReadBuffer::cancel` to the test output.
Resume exception checks at the next log record so unrelated failures
remain visible.

Validated shell syntax and 17 filter cases, including all 19 cancellation
records from the three CI failures and unexpected-exception cases.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116257&sha=6fa6e70ae03116ca18750f7a9255dfca984f8b49&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20targeted%29

Related: ClickHouse#116257

@clickhouse-gh clickhouse-gh Bot 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.

AI review approves this commit, see the AI Review comment.

…reading

Check cancellation before constructing the rebuild pipeline. Disable parallel replicas and distributed plans for this internal single-part read so server profile settings cannot turn a cancelled or ordinary rebuild into a broken part.

Validated `05621_s3_index_cancellation` with S3 and plan-based parallel replicas: the original binary detaches the part, while the patched binary passes all six scenarios.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116257&sha=40fd49ca3b81f67dc30875f3b21a05e86fa61c8a&name_0=PR

Related: ClickHouse#116257
}

/// Try to read a next portion of data.
checkIfNotCancelled();

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.

Each S3 read buffer that observes cancellation now writes a debug log record with a symbolized stack trace.

There is an edit in 02340 that hides this instead of fixing it, so I suppose that it is intended?

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.

  • nextImpl calls checkIfNotCancelled() before impl->next(). Before, the check ran only inside the catch block, after a read error.
  • So cancellation is now thrown from inside nextImpl. ReadBuffer::next catches it and calls cancel(). That calls tryLogCurrentException which formats the stack trace.

One query with one column already produced several such records per run in CI.

Comment thread src/IO/ReadBufferFromS3.cpp Outdated
if (client_ptr->isClientForDisk())
ProfileEvents::increment(ProfileEvents::DiskS3GetObject);
FailPointInjection::pauseFailPoint(FailPoints::s3_read_before_get_object);
fiu_do_on(FailPoints::s3_pause_merge_before_get_object,

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.

A test-only failpoint in production code matches a hard-coded table name inside the query ID. It works only in Ordinary databases. Merge query IDs come from StorageID::getShortName(). In an Atomic database that is the table UUID, so the ".s3_pause_merge_before_get_object::" substring never matches.

Pause all reads before `GetObject` on the dedicated test server, then
cancel the target merge and check its counters in `system.part_log`.
This also exercises `Atomic` without matching a table name in S3 code.

## Changelog

Category: Not for changelog

Related: ClickHouse#116257
Use the same exception check for buffer diagnostics and S3 read errors.
Retain the stack trace for independent I/O failures. Cover both paths
in the S3 integration tests and restore the original `02340` log filter.

## Changelog

Category: Improvement

Cancelling a query or background merge no longer writes a debug stack
trace for each affected read buffer.

Related: ClickHouse#116257
Keep the cancellation failpoint before the serialization metadata read in
`checkDataPart` and use upstream's read helper so local direct I/O stays
enabled when requested.

Related: ClickHouse#116257

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

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants