Skip to content

Stop the other S3 reads of a failed merge or mutation - #128185

Merged
CheSema merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-failed-merge-cancels-inflight-s3-reads
Nov 6, 2026
Merged

CheSema merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-failed-merge-cancels-inflight-s3-reads

Conversation

@groeneai

@groeneai groeneai commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

A merge or mutation that fails on one S3 read now stops its other S3 reads that are still in flight. They used to keep retrying to their retry budget (about 41 minutes per object with default settings) while the failed task held its source parts and the table, so DROP TABLE waited for it and an OPTIMIZE (also OPTIMIZE ... DRY RUN PARTS) that ran the merge did not return.

Description

Closes: #128164
Related: #113939
Related: #129503

A failed merge or mutation waits for its in-flight reads when it is destroyed. They stop only once the task's thread group cancellation predicates (from #113939) answer true, and those read MergeListElement::is_cancelled, which nothing set on a failure.

  • MergeTask::cancel and MutateTask::cancel set the flag, and every runner cancels a failed task before it destroys it, as MergeTreeBackgroundExecutor does: the executeHere runners (OPTIMIZE on a MergeTree, the projection sub-merges) used to skip it. The entry belongs to one attempt, so the flag never reaches a retry. OPTIMIZE ... DRY RUN PARTS reads and writes in the thread group of its query, so its runner cancels that query (CANCELLED_BY_ERROR) before the task.
  • No pipeline with reads in flight is destroyed as a local before the flag is set: a vertical merge no longer keeps a prefetching column pipeline in a local, MergeTreeSequentialSource no longer prefetches in its constructor (the merge starts them once ctx owns the pipeline), and isStorageTouchedByMutations sets the flag through a new on_exception callback, which its executor calls once, from the first failing thread, before it waits for its other threads (IExecutor::setExceptionCallback), also when the executor itself fails. It records that exception first and rethrows it after the join, not the ABORTED it caused.

Not covered (#129503): reads that a nested wait holds before the failure reaches the executor, e.g. while it builds the set of an IN (subquery) or the prefixes of a JSON column.

Test: test_merge_cancel_s3_read::test_failed_merge_stops_its_other_s3_reads. One read gets 429 while the task fails: on a NoSuchUpload read in background, optimize, dry-run, mutation and mutation-probe (one stream fails while another is blocked in a read; each attempt must report it), on a failpoint in next-column-setup and source-constructor. Without its change each case keeps the failed task in system.merges past 20 s.


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

Version info

  • Merged into: 26.11.1.1534-master (included in 26.11 and later)

groeneai and others added 2 commits October 29, 2026 16:09
A vertical merge on a remote disk prefetches the next column from every
source part while it gathers the current one. When one read fails, the
merge fails, but its other in-flight reads keep retrying to their own
budget (500 attempts with up to 5 s backoff per GetObject by default),
because the S3 retry loop stops only when the thread group's
cancellation predicates answer true, and those read
`MergeListElement::is_cancelled`, which nothing set on a failure. The
failed task waits for every prefetch in its destructor, so it kept its
`system.merges` entry, its source parts and the table (blocking
`DROP TABLE`), and an `OPTIMIZE` that ran the merge did not return.

Set the flag of the root merge list entry in `MergeTask::execute`'s
existing catch, which every runner of a merge task passes through on a
failure: the background executor, `OPTIMIZE` on a `MergeTree` and the
projection sub-merges of `MergeProjectionPartsTask`. The latter two
destroy a failed task without calling `MergeTask::cancel`, so setting
the flag there would leave them unfixed. For mutations set it at the
start of `MutateTask::cancel`: a mutate task runs only under the
executor, which cancels it on every failure before destroying it.

The entry belongs to one task attempt (a retry of the same part is a new
task with a new entry), so the flag cannot leak into a retry.

The test extends `test_merge_cancel_s3_read`: a vertical merge whose read
of `a` fails with a non-retryable error while the prefetches of `b` are
answered with 429, run by the assignee and by `OPTIMIZE`. The S3 mock
gets per-object-key `at_object_get` rules for it.

Closes ClickHouse#128164

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comment in MutateTask::cancel: setting is_cancelled in cancel() is self-explanatory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (codex; 2 findings; no fix round needed).

# Sev Finding Verdict Evidence
1 ⚠️ No test exercises the MutateTask::cancel store DISAGREE Not dead code: a failed mutation's in-flight uploads run in its thread group and MutateTask::cancel waits for them after the store; the issue scopes the test to merges. Noted, not blocking.
2 💡 Category should be Bug Fix DISAGREE It adds a missing cancellation (the reads ended at their retry budget), so Improvement; the entry already backticks DROP TABLE and OPTIMIZE.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261029-172500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin, could you review this and add the can be tested label so CI runs? A failed merge now sets is_cancelled on its merge list entry, so its other in-flight S3 reads, whose retry loop checks that flag through the thread group predicates of #113939, stop at the next retry instead of retrying for up to about 41 minutes.

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [88945cf]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

Reviewed #128185 at 88945cf875d844c1a0084448daa931f1fbef0f9a. Failed merge and mutation runners now publish cancellation before teardown, prefetched column pipelines remain owned by the task, and the executor records the initiating exception before cancelling sibling readers. Earlier findings are addressed except for the explicitly deferred nested-reader limitation below. No new inline findings.

Findings

⚠️ Majors

Missing context / blind spots
  • ⚠️ No local build or integration run: this checkout has no built server. The author reports all 14 module cases passing at the reviewed head, with negative controls for cancellation and exception preservation. The current Praktika report reports no failures, but its fetched integration summaries contain no individual test results; detailed current-head artifacts would independently confirm those runtime claims.
Final Verdict

✅ Approve the explicitly scoped fix. No additional changes required in this PR; retain the accepted nested-reader work in #129503.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 88945cf87 with master ec74a8554 (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.

Compile time of recompiled translation units

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

Job report

A vertical merge moved the current column's pipeline, whose prefetches may
still be in flight, into a local, and then built the next column's pipeline
and moved the pipelines into the task context. If any of that threw (e.g.
`MEMORY_LIMIT_EXCEEDED` while allocating the next column's prefetch buffers,
or in a `QueryPipeline` move assignment), unwinding destroyed the local, and
its readers waited in `AsynchronousBoundedReadBuffer::resetPrefetch` before
the catch in `MergeTask::execute` could set `is_cancelled`, so a retrying S3
read kept the failed merge alive for its whole retry budget.

Move the current pipeline from `ctx->prepared_pipeline` straight into
`ctx->column_parts_pipeline`, then emplace the next one into
`ctx->prepared_pipeline`, so a pipeline with prefetches in flight is always
owned by the task and destroyed with it, after the cancellation is published.

`test_failed_merge_stops_its_other_s3_reads` gets a `next-column-setup` case
driven by the new `merge_task_throw_while_preparing_next_column` failpoint:
with the old code the failed merge stays in `system.merges` past 20 s, with
this change it leaves within one retry backoff. The test now starts its
oracle when the other read reaches S3 rather than on the `part_log` row,
which a merge stuck in unwinding does not write.

Sources of the next column that are already built when a later part's setup
throws are still destroyed inside `QueryPlan::buildQueryPipeline` before the
catch runs; this frame cannot reach them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
groeneai and others added 2 commits October 30, 2026 00:58
`OPTIMIZE ... DRY RUN PARTS` runs its merge task inline, in the thread of
the query, so the prefetches of the vertical merge run in the thread group
of the query, whose cancellation predicates check only whether the query is
killed. Setting `is_cancelled` on the merge list entry when the merge fails
does not reach them, so with one read failed and another retrying, the
query waited for the whole retry budget of that read while it held the
table.

In `MergeTask::execute`'s catch, also cancel the query the task runs in,
with `CANCELLED_BY_ERROR`. Only a dry run has one: the background merges,
`OPTIMIZE` on a `MergeTree` and projection sub-merges run in a context
copied from the background context, which has no process list element. The
query still fails with the original exception.

`test_failed_merge_stops_its_other_s3_reads` gets a `dry-run` case: without
the change the dry run stays in `system.merges` past 20 s, with it the
query returns within one retry backoff with the injected error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d32a3ad

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / ThreadSanitizer: data race (STID: 1003-46d8) not from this PR (its diff does not touch src/Client): ClientBase::onProgress is called by the LocalConnection::sendQuery progress callback on a pipeline thread while another thread writes the same state (11 other PRs since 2026-10-27) #128019 (mine, open)
Mergeable Check, PR praktika rollups of the row above #128019 (mine, open)
CH Inc sync the private sync PR has conflicts CH Inc sync (private, not actionable by me)

test_merge_cancel_s3_read passed in Integration tests (amd_asan_ubsan, flaky) and in every targeted integration job; all five stateless flaky checks are green.

Session id: cron:our-pr-ci-monitor:20261030-070003

@CheSema CheSema self-assigned this Nov 3, 2026

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

Review at head d32a3ad019ba, own changes over #113939. Line numbers refer to that head.

1. MutateTask: set is_cancelled in a catch of execute, not in cancel

MergeTask sets the flag in the catch of MergeTask::execute (MergeTask.cpp:2861). MutateTask sets it at the start of MutateTask::cancel (MutateTask.cpp:3966), so the flag depends on the caller. The executor calls cancel on every failure (MergeTreeBackgroundExecutor.cpp:531), but only after the outer handlers ran: MutatePlainMergeTreeTask writes the part log and calls updateMutationEntriesErrors, and ReplicatedMergeMutateTaskBase::executeStep takes queue.state_mutex. The PR description rejects "rely on cancel" for MergeTask because OPTIMIZE and the projection sub-merges skip it. Please use the same rule for both tasks:

bool MutateTask::execute()
try
{
    ... /// existing body
}
catch (...)
{
    /// Stops the other in-flight reads of this mutation: the thread group's cancellation predicates read this flag.
    (*ctx->mutate_entry)->is_cancelled.store(true, std::memory_order_relaxed);
    throw;
}

The store in cancel is then not needed: KILL MUTATION sets the flag through MergeList, and shutdown or drop goes through merges_blocker.

2. The catch in MergeTask::execute is not always reached before the wait

MergeTreeSequentialSource starts its prefetch in the constructor (MergeTreeSequentialSource.cpp:211). QueryPlan::buildQueryPipeline, called from createPipelineForReadingOneColumn (MergeTask.cpp:2101), creates one source per part, in order:

  1. The source of part 0 starts its prefetch. The prefetch gets 429 and retries.
  2. The constructor of the source of part 1 throws, for example when it loads marks or a serialization prefix from S3, or on a memory limit.
  3. During unwinding, buildQueryPipeline destroys the builder of part 0. Its read buffer waits for the prefetch while is_cancelled is still false.
  4. Only then the catch in execute sets the flag.

The same applies to all three build sites (MergeTask.cpp:2023, 2218, 2235). It is the hazard that 611b6baadbb3 fixed one level up, but here the locals are inside buildQueryPipeline, so reordering locals in MergeTask cannot fix it. Suggestion: build the column pipeline without a prefetch, store it in ctx->prepared_pipeline, and only then start the prefetches of its sources. Then a prefetch is in flight only when ctx owns it, and the catch always runs before the wait. A failpoint that throws in the source constructor of part 1 while the column of part 0 gets 429 would prove it.

3. Naming

Two predicates have the same name as the atomic flag they read and latch: ctx->is_cancelled (MergeTask.h:346, assigned at MergeTask.cpp:1305) and the local is_cancelled lambda (MergeTreeDataMergerMutator.cpp:556). This gives (*merge_entry)->is_cancelled.load() inside a lambda that is also named is_cancelled. MutateTask already uses mutation_cancelled (MutateTask.cpp:3900). Please rename both to merge_cancelled.

The latching predicate is also written three times with different TTL conditions: GlobalRuntimeContext::isCancelled ignores the TTL blocker, prepare captures ttl_cancellable once, and mergePartsToTemporaryPart reads is_removing_expired_values live. One helper can be a follow-up.

4. Tests

  • No test covers the MutateTask change: all four cases of test_failed_merge_stops_its_other_s3_reads are merges. Please add a mutation case to the same module, for example a read of a that fails while the prefetch of b gets 429 with remote_filesystem_read_method = 'threadpool'.
  • Please add the failpoint case from item 2.

groeneai and others added 3 commits November 4, 2026 14:52
`ctx->is_cancelled` in `MergeTask` and the local lambda in
`MergeTreeDataMergerMutator::mergePartsToTemporaryPart` had the name of the
atomic flag they read and latch, so the code read
`(*merge_entry)->is_cancelled.load()` inside a lambda also named
`is_cancelled`. `MutateTask` already calls its predicate
`mutation_cancelled`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Same rule as `MergeTask::execute`: the flag that the mutation's
cancellation predicates read is set in a catch of `MutateTask::execute`,
not in `MutateTask::cancel`, which the executor calls only after the outer
handlers ran (the part log and `updateMutationEntriesErrors` in
`MutatePlainMergeTreeTask`, `queue.state_mutex` in
`ReplicatedMergeMutateTaskBase::executeStep`). Every exception out of
`MutateTask::execute` ends the task, and a later attempt gets a new merge
list entry, so the flag cannot leak into it. The store in `cancel` is
dropped: `KILL MUTATION` sets the flag through `MergeList`, and shutdown or
drop go through `merges_blocker`.

That catch is too late when the mutation fails in
`isStorageTouchedByMutations`, the query that counts the rows a mutation
with a `WHERE` affects: its pipeline is a local there, and destroying it
waits for the reads still in flight before the exception reaches
`execute`. So the probe takes an `on_exception` callback, run while its
executor and pipeline are still alive, and `MutateTask::prepare` sets the
flag there too.

`test_failed_merge_stops_its_other_s3_reads` gets two cases on one part:
`mutation` (`DELETE WHERE id % 2 = 0`, which fails in the mutation's own
pipeline) and `mutation-probe` (`DELETE WHERE a = b`, which fails in the
probe). A read of the sizes of `a` fails while the read of its data
answers 429. With the flag set nowhere (as before this PR) both stay in
`system.merges` past 20 s; with the catch in `execute` but without the
callback, `mutation-probe` still does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s pipeline

`MergeTreeSequentialSource` started its prefetch in its constructor, and
`QueryPlan::buildQueryPipeline` creates one source per part. When the
constructor of a later source threw (for example on a memory limit),
unwinding destroyed the builders of the earlier sources inside
`buildQueryPipeline`, and their read buffers waited for their prefetches
while the merge list entry was not cancelled yet, so a retrying prefetch
held the failed merge until its retry budget ran out. Reordering locals in
`MergeTask` cannot reach those builders.

The sources no longer prefetch on construction (the `prefetch` argument is
removed). The vertical merge stores the pipeline of a column in
`ctx->prepared_pipeline` and only then starts the prefetches of its
sources with `prefetchMergeTreeSequentialSources`, so a prefetch is in
flight only when the task owns it, and the catch in `MergeTask::execute`
publishes the cancellation before any wait.

The new failpoint `merge_tree_sequential_source_throw_in_constructor`
throws in the constructor of the source of any part but the first. The
`source-constructor` case of `test_failed_merge_stops_its_other_s3_reads`
holds the horizontal stage on a read of `id` until it enables the
failpoint, so the failpoint first fires while the vertical stage builds
the pipeline of `a`, with the read of `a` of the first part answering 429.
With the prefetch in the constructor the merge stays in `system.merges`
past 20 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Stop the other S3 reads of a failed merge Stop the other S3 reads of a failed merge or mutation Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. All four points are in the push up to aa0300d:

  1. MutateTask::execute sets the flag in a catch, and the store in cancel is gone (33ae1f4). 04826_kill_mutation_cancels_s3_read, 04238_kill_mutation_subquery_multi_block and 01900_kill_mutation_parallel_long still pass. Writing the mutation case showed that this catch comes too late for a mutation whose WHERE reads columns. Such a mutation first fails in isStorageTouchedByMutations, where the pipeline is a local, so destroying it waits for the other reads before the exception reaches execute. That is the same shape as item 2. isStorageTouchedByMutations now takes an on_exception callback, called while its executor and pipeline are still alive, and MutateTask::prepare uses it to set the flag too.
  2. MergeTreeSequentialSource no longer prefetches in its constructor, and its prefetch argument is removed. At MergeTask.cpp:2023 and 2235 the vertical merge now stores the pipeline in ctx->prepared_pipeline first and then calls prefetchMergeTreeSequentialSources on it (aa0300d). The pipeline at 2218 no longer prefetches.
  3. Both are renamed to merge_cancelled (9def487). As you suggested, the shared latching helper is not in this PR.
  4. test_failed_merge_stops_its_other_s3_reads has three new cases:
    • mutation (DELETE WHERE id % 2 = 0) fails in the mutation's own pipeline, and mutation-probe (DELETE WHERE a = b) fails in isStorageTouchedByMutations. In both, the read of the sizes stream of a fails while the read of its data gets 429, so the case does not depend on the order in which the mutation reads its columns.
    • source-constructor: the new failpoint merge_tree_sequential_source_throw_in_constructor throws in the source of every part except the first. The case keeps the horizontal stage on a 429 read of id until it has enabled the failpoint, so the failpoint first fires while the pipeline of a is built, with the read of a of part 0 getting 429.

Measured locally: with the old code (prefetch in the constructor, no store in MutateTask), all three cases keep the task in system.merges for more than 20 s. With only the catch in execute, mutation-probe still does. With this push the whole module passes (14/14). I also updated the description.

…ins the other threads

The count of the rows a mutation affects (`isStorageTouchedByMutations`) reads the part in
several streams. When one stream fails, `PipelineExecutor` cancels the graph and then waits
in `pool->wait` for the other threads before it rethrows. A thread blocked in an S3 read that
keeps getting 429 does not return, because processor cancellation is invisible to the S3
retry loop, which reads only the thread group's predicates, and the `catch` that set
`is_cancelled` on the mutation entry is reached only after that wait. The failed mutation
kept its part until the sibling read exhausted its retry budget.

`IExecutor::setExceptionCallback` is called from the thread whose exception cancels the
execution, before the other threads are waited for. `PullingAsyncPipelineExecutor` forwards
it, and the probe passes the store of `is_cancelled` through it instead of the `catch`.

The `mutation-probe` case now holds every stream on the sizes of `a`, then lets the first
read pass and fails the next, so one stream fails while another is blocked in the read of
the data of `a`. Before this change the task stayed in `system.merges` for 20 s and more
(2 runs); with it the other reads stop within 0.4 s (4 runs), and the whole module passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CheSema

CheSema commented Nov 4, 2026

Copy link
Copy Markdown
Member

Correction to item 1 of my review above. It replaces the suggestion to add a catch in MutateTask::execute.

MergeTreeBackgroundExecutor already cancels a failed task before it destroys it (MergeTreeBackgroundExecutor.cpp:520-531). That is why the store in MutateTask::cancel works for mutations. The executeHere loops do not do this, so they destroy a failed task without cancel:

  • executeHere(MergePlainMergeTreeTaskPtr) (MergePlainMergeTreeTask.h:104): OPTIMIZE on MergeTree.
  • executeHere(MergeTaskPtr) (MergeTask.h:625): projection sub-merges (MergeProjectionPartsTask.cpp:121) and OPTIMIZE ... DRY RUN PARTS (MergeTreeData.cpp:11750).
  • executeHere(MutateTaskPtr) (MutateTask.h:73): no callers.

Please make every runner follow the rule of the executor: cancel a failed task before you destroy it.

  1. Give each executeHere the catch of the executor:
    try
    {
        while (task->execute()) {}
    }
    catch (...)
    {
        task->cancel();
        throw;
    }
  2. Set is_cancelled in MergeTask::cancel, as MutateTask::cancel does now.
  3. Remove the store from the catch of MergeTask::execute. Keep the MergeFailures metric there.
  4. Move cancelQuery(CANCELLED_BY_ERROR) from MergeTask::execute to the DRY RUN runner in MergeTreeData.cpp. Only that caller reads in the thread group of a query.

With this, the flag is set where cancellation is handled, by one rule for both tasks. The inline runners also get the cleanup that cancel does today only under the executor. A pending task cancelled at shutdown also gets the flag. The timing is the same as a catch in the task, because the frames between the task and the runner hold no prefetching objects.

This does not change item 2. The prefetch still must start only after the column pipeline is stored in ctx.

groeneai and others added 3 commits November 4, 2026 17:58
Both callbacks of isStorageTouchedByMutations' executor are kept:
setExceptionCallback from this PR and setCancelCallback from master.
…ed in cancel

`MergeTreeBackgroundExecutor` cancels a failed task before it destroys it,
but the `executeHere` runners did not: `OPTIMIZE` on a `MergeTree`, the
projection sub-merges and `OPTIMIZE ... DRY RUN PARTS` destroyed a failed task
without `cancel`. Each `executeHere` now cancels a failed task before it
rethrows, like the executor, and `MergeTask::cancel` and `MutateTask::cancel`
set `is_cancelled` on the merge list entry. So the flag is set where
cancellation is handled, by one rule for both tasks, and the inline runners
also get the cleanup that `cancel` does.

The stores in the catches of `MergeTask::execute` and `MutateTask::execute`
are removed; `MergeTask::execute` keeps the `MergeFailures` metric. Cancelling
the query with `CANCELLED_BY_ERROR` moves to the `DRY RUN` runner, the only
caller whose reads run in the thread group of a query.

The probe of `isStorageTouchedByMutations` keeps its exception callback: its
pipeline is a local there, destroyed before the task is cancelled.

Without the catches in the runners, the `optimize` and `dry-run` cases of
`test_failed_merge_stops_its_other_s3_reads` stay in `system.merges` past
20 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MergeTask::cancel` cancels the writers of the task, and cancelling a
`WriteBufferFromS3` waits for its in-flight uploads. A dry run writes in the
thread group of its query, so those uploads observe only the query: it is
cancelled first. `optimizeDryRun` therefore runs the task itself instead of
through `executeHere`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks, done in the push up to 54017b0:

1-3. Every executeHere cancels a failed task before it rethrows, MergeTask::cancel sets is_cancelled like MutateTask::cancel (its store is back), and the stores in the catch of MergeTask::execute and MutateTask::execute are gone; MergeFailures stays (98a348f).
4. cancelQuery(CANCELLED_BY_ERROR) is in the DRY RUN runner. That runner loops over merge_task->execute() itself instead of calling executeHere, so that the query is cancelled before merge_task->cancel(): cancel cancels the writers, and WriteBufferFromS3::cancelImpl waits for its uploads in flight (tryToAbortMultipartUpload -> safeWaitAll), which run in the thread group of the query (7014a20).

The on_exception callback of isStorageTouchedByMutations stays, because its pipeline is a local there. The PR conflicted with master, so I merged it twice: 300a22b (MutationsInterpreter.cpp) and 54017b0 (#129042: I kept allow_remote_fs_prefetch and dropped prefetch_begin_of_range, since the source no longer prefetches in its constructor; 05493_merge_prefetch_limits passes).

test_merge_cancel_s3_read passes 14/14 on 54017b0. Without the catch in the OPTIMIZE runner and the cancelQuery in the DRY RUN runner, optimize and dry-run stay in system.merges past 20 s. The projection sub-merge runner has no case: I measured that the other reads of a failed projection sub-merge are still in flight when the exception reaches the executor, and stop when it cancels the parent task, so that catch only adds the cleanup.

Master renamed the prefetch parameter of the merge sequential source to
prefetch_begin_of_range and added allow_remote_fs_prefetch. This PR no
longer prefetches in the constructor of the source, so the first one is
dropped and the second one is kept.
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
The exception callback of the probe of `isStorageTouchedByMutations` sets
`is_cancelled`, so the other streams of the probe stop their S3 reads with
`ABORTED`. `ExecutorTasks::rethrowFirstThreadException` rethrew the exception
of the lowest-numbered thread, which was often one of those, so a failed
mutation reported `Cancelled mutating parts` instead of its error. For a
`ReplicatedMergeTree` that is worse, since `ABORTED` is not recorded as a
failure of the entry. The executor now rethrows the exception that was set
first.

A worker thread that fails in the executor itself, outside of a processor
(e.g. `MEMORY_LIMIT_EXCEEDED` while pushing tasks to the queue), only stopped
the other threads, so the callback was not called before they were waited for.
It now cancels the execution with `Exception`, like the other failures of the
executor.

The `mutation-probe` case of `test_failed_merge_stops_its_other_s3_reads` checks
that every failed attempt of the mutation reports the injected error: before,
7 of its 14 attempts reported `ABORTED`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 4, 2026 23:15
`executeStepImpl` handles a failure of `spawnThreads`, `renewCPULease` or
`syncMemory` by cancelling the execution and rethrowing, and the exception was
set only later, in the catch of the worker thread. Cancelling with `Exception`
calls the exception callback, so the other streams of the probe of
`isStorageTouchedByMutations` can stop their reads with `ABORTED` and set it
first, and that is the exception rethrown. The exception is now set before the
cancellation, as in the catch of `updateNode`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master moved `WhatIfEmpiricalEstimator.cpp` and `WhatIfProjectionEstimator.cpp`
into `src/Storages/MergeTree/WhatIf/` (3a7f59c). This PR drops the
`prefetch_begin_of_range` argument of `createMergeTreeSequentialSource` there;
the hunks are carried into the new paths, everything else is master's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CheSema

CheSema commented Nov 5, 2026

Copy link
Copy Markdown
Member

Recheck at head 46b79c583e14. The runner rule, the prefetch start after ctx owns the pipeline, the rename and the mutation cases look good. Three points are left.

1. Replace exception_order with an exception recorded once

exception_order (ExecutionThreadContext.cpp:269-274, ExecutorTasks.cpp:83) selects the exception that was set first, with a counter that all executors in the process share. std::call_once gives the same result with less code:

  • Keep an std::once_flag and an std::exception_ptr next to the exception callback in PipelineExecutor.
  • Add one private helper, for example cancelWithException(std::exception_ptr cause). In std::call_once, it records cause and then calls the callback. After that, it cancels as today. The catches pass std::current_exception(). The site at PipelineExecutor.cpp:434 is not in a catch, so it passes context.getException().
  • After the join, rethrow the recorded exception. The join orders the write before the read.
  • Then the exception that cancels the others is always recorded before the callback lets them throw ABORTED. No call site can get this order wrong, which 9bb1aa740675 had to fix by hand in three places.
  • The callback then runs once, from the first failing thread, before the join. That makes the comment of IExecutor::setExceptionCallback exact. Today PipelineExecutor::cancel (PipelineExecutor.cpp:205) calls it on every cancel(Exception), from several threads at a time. Also state there that the callback must not throw: a throw skips finish, and the idle threads never wake up.
  • Keep the exceptions of the threads only for the loop that logs a LOGICAL_ERROR of each thread.

2. Let test_failed_merge_stops_its_other_s3_reads stop when the task is gone

The loop at test.py:803 has no break: every case waits the full FAILED_MERGE_WINDOW_SECONDS (30 s), also when it passes, and optimize and dry-run wait SETTLED_WINDOW_SECONDS (15 s) more. With 7 cases the module waits about 4 minutes, and the integration tests barely fit in their timeout. Please leave the loop when the failed task is gone from system.merges and the OPTIMIZE returned, and keep FAILED_MERGE_MAX_AGE_SECONDS as the deadline. A passing case then takes about 1 s.

3. The open thread about the prefix reads of JSON

The finding is valid, but narrow: only the probe uses the prefix deserialization pool, because the merges and the mutation pipeline read through MergeTreeReaderSettings::createForMergeMutation, which keeps the pool off. The description already lists it under "Not covered". Please open a follow-up issue for nested waits that do not stop the other reads on the first failure (this pool and the sets of IN (subquery)), add it as Related: to the description, and resolve the thread with the link.

…d-merge test as soon as the task is gone

PipelineExecutor now records the exception that cancels the execution in
`cancelWithException`, under `std::call_once`, before it calls the exception
callback, and rethrows that exception after the threads are joined. The
callback can make the other threads throw `ABORTED`; they can no longer be
rethrown instead of the cause, whatever the order of `setException` and
`cancel` at a call site. This replaces the process-wide `exception_order`
counter and the per-site ordering of 9bb1aa7. The callback now runs once,
from the first failing thread; `cancel` no longer calls it. The exceptions of
the threads are kept only to log their `LOGICAL_ERROR`s.

`test_failed_merge_stops_its_other_s3_reads` leaves its loop once every
`system.merges` entry is younger than the failure and the `OPTIMIZE` returned,
with `FAILED_MERGE_MAX_AGE_SECONDS` as the deadline. The 15 s settled window
after the `OPTIMIZE` returned is dropped: the `OPTIMIZE` returns only after its
task is destroyed, and the destructor waits for every read still in flight.
The seven cases take about 4 s each instead of 30-45 s.

Negative control (local only): without the store in `MergeTask::cancel` and
with the old lowest-index rethrow, `background`, `optimize` and
`next-column-setup` fail at the 20 s bound, and every attempt of
`mutation-probe` reports `ABORTED` instead of the injected error.

Requested in ClickHouse#128185 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. All three are in 88945cf875d8.

  1. PipelineExecutor::cancelWithException records the cause and calls the callback in one std::call_once, then cancels as before. All seven cancel(Exception) sites go through it (the one after executeTask passes context.getException()), so the setException calls that 9bb1aa7 added before cancel are gone. execute, executeUntil and the catch of executeImpl rethrow the recorded exception after the join. exception_order is removed, ExecutorTasks::rethrowFirstThreadException is now logLogicalErrors, and cancel no longer calls the callback. The comment of IExecutor::setExceptionCallback now says that it runs once, from the first failing thread, before the join, and must not throw.
  2. The loop ends once every entry in system.merges is younger than the failure and the OPTIMIZE returned, with FAILED_MERGE_MAX_AGE_SECONDS as the deadline. I also dropped the 15 s window after the OPTIMIZE returned: it returns only after its task is destroyed, and the destructor waits for every read in flight, so the return already proves that the reads stopped. A passing case now takes about 4 s.
  3. Nested waits do not stop the other S3 reads on the first failure: prefix deserialization tasks of JSON and sets of IN (subquery) #129503, added as Related:, linked in the thread, which I resolved.

Checked locally: the module passes 14/14. Without the store in MergeTask::cancel and with the old lowest-index rethrow, background, optimize and next-column-setup fail at the 20 s bound, and every attempt of mutation-probe reports ABORTED instead of the injected error, so the shorter loop still catches both. A sample of 273 stateless tests about exceptions and cancellation shows no new failure.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 88945cf

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR: all 100 lines are ILLEGAL_DIVISION intDiv(100, x) While executing TTL from a background merge, the intentionally failing case of 05073_column_ttl_recompute_materialized; the same lines failed the upgrade check on 61 other PRs in 14 days #127731 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127731 (same as above)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261106-000007

@CheSema
CheSema added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit fdd38e4 Nov 6, 2026
183 of 185 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 14, 2026
…eption

Since ClickHouse#128185, `logAndRethrowException` rethrows only the exception recorded by
`cancelWithException`. The poll for pipelines outside of the process list used a
plain `cancel`, so `execute` and `executeUntil` of a cancelled merge or mutation
pipeline returned as if the data had ended, and the mutation saw the cancelled
pipeline as finished. Record the exception like the other executor-side failures.

The gtest runs a pipeline under a thread group that gets cancelled and requires
`PullingPipelineExecutor` and `PullingAsyncPipelineExecutor` to throw `ABORTED`.
It fails with the plain `cancel` and without the poll.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 17, 2026
…ause

When the connection thread of a query failed while the pipeline ran (e.g. it
hit the memory limit itself while sending profile events in the pull loop),
the catch in `TCPHandler::processOrdinaryQuery` called `executor.cancel()`,
which cancels the processors with no cause. A processor reacting to the
cancellation could then throw: the driver of a distributed plan cancels its
in-memory exchanges, and the result reader raises `QUERY_WAS_CANCELLED`
("Distributed query was cancelled before exchange 'final_result__0_0'
transferred all data"). That was the first exception the executor recorded,
and `PullingAsyncPipelineExecutor::cancel` rethrew it from inside the catch,
so the original error was lost. This is how
`05407_distributed_plan_local_start_stage_memory_limit` got 394 instead of 241.

Reuse `PipelineExecutor::cancelWithException`, which records the exception
once and before the processors are cancelled: declare it in `IExecutor`, let
the `cancel` of `PullingAsyncPipelineExecutor`, `PushingAsyncPipelineExecutor`
and `PushingPipelineExecutor` take an optional cause, and pass
`std::current_exception()` from both `TCPHandler` catches (`processInsertQuery`
has the same shape). An exception the pipeline recorded earlier still wins.
Since another thread can now record the cause, `logAndRethrowException` waits
on `cancel_exception_once` before reading it; a cause that arrives after the
execution finished is then not recorded, and the caller's `throw;` reports it.

The displacement predates ClickHouse#128185 but became about 30x more frequent with it
(the executor started to rethrow the first exception recorded in time instead
of the one of the lowest thread index): 2/5000 vs 60/5000 on MasterCI debug
binaries just before and after it.

Measured on a debug build, 05407's first query 5000x at 32 concurrent clients:
136/15000 return 394 on the base, 0/20000 with this change, 76/5000 with only
the `processOrdinaryQuery` line reverted. The two new gtests (renamed file) fail
200/200 when the wrappers ignore the cause and pass 200/200 with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-background-ops Background pools/scheduling for merges, cleanup, maintenance. pr-improvement Pull request with some product improvements 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.

Failed merge does not stop its other in-flight S3 reads

5 participants