Repository navigation
Conversation
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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (codex; 2 findings; no fix round needed).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261029-172500 |
|
cc @alesapin, could you review this and add the |
|
Workflow [PR], commit [88945cf] Summary: ❌
AI ReviewSummaryReviewed #128185 at Findings
Missing context / blind spots
Final Verdict✅ Approve the explicitly scoped fix. No additional changes required in this PR; retain the accepted nested-reader work in #129503. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units99 translation units recompiled, 1136 s compile time in total, 99 of them have a recent master baseline. |
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]>
`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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - d32a3adEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261030-070003 |
CheSema
left a comment
There was a problem hiding this comment.
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:
- The source of part 0 starts its prefetch. The prefetch gets 429 and retries.
- 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.
- During unwinding,
buildQueryPipelinedestroys the builder of part 0. Its read buffer waits for the prefetch whileis_cancelledis stillfalse. - Only then the
catchinexecutesets 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
MutateTaskchange: all four cases oftest_failed_merge_stops_its_other_s3_readsare merges. Please add a mutation case to the same module, for example a read ofathat fails while the prefetch ofbgets 429 withremote_filesystem_read_method = 'threadpool'. - Please add the failpoint case from item 2.
`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]>
|
Thanks for the review. All four points are in the push up to aa0300d:
Measured locally: with the old code (prefetch in the constructor, no store in |
…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]>
|
Correction to item 1 of my review above. It replaces the suggestion to add a
Please make every runner follow the rule of the executor: cancel a failed task before you destroy it.
With this, the flag is set where cancellation is handled, by one rule for both tasks. The inline runners also get the cleanup that This does not change item 2. The prefetch still must start only after the column pipeline is stored in |
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]>
|
Thanks, done in the push up to 54017b0: 1-3. Every The
|
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.
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]>
`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]>
|
Recheck at head 1. Replace
|
…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]>
|
Thanks. All three are in 88945cf875d8.
Checked locally: the module passes 14/14. Without the store in |
CI finish ledger - 88945cfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261106-000007 |
fdd38e4
…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]>
…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]>
Changelog category (leave one):
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 TABLEwaited for it and anOPTIMIZE(alsoOPTIMIZE ... 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::cancelandMutateTask::cancelset the flag, and every runner cancels a failed task before it destroys it, asMergeTreeBackgroundExecutordoes: theexecuteHererunners (OPTIMIZEon aMergeTree, the projection sub-merges) used to skip it. The entry belongs to one attempt, so the flag never reaches a retry.OPTIMIZE ... DRY RUN PARTSreads and writes in the thread group of its query, so its runner cancels that query (CANCELLED_BY_ERROR) before the task.MergeTreeSequentialSourceno longer prefetches in its constructor (the merge starts them oncectxowns the pipeline), andisStorageTouchedByMutationssets the flag through a newon_exceptioncallback, 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 theABORTEDit 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 aJSONcolumn.Test:
test_merge_cancel_s3_read::test_failed_merge_stops_its_other_s3_reads. One read gets 429 while the task fails: on aNoSuchUploadread inbackground,optimize,dry-run,mutationandmutation-probe(one stream fails while another is blocked in a read; each attempt must report it), on a failpoint innext-column-setupandsource-constructor. Without its change each case keeps the failed task insystem.mergespast 20 s.Workflow [PR]
Sync PR [sync-upstream/pr/128185]
Version info
26.11.1.1534-master(included in26.11and later)