Skip to content

Report mutation cancellation instead of stopping nested pipelines silently - #114463

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-cancellation-report-not-ready-set
Aug 17, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-cancellation-report-not-ready-set

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

Fixed a Not-ready Set is passed as the second argument for function 'in' error when a mutation whose predicate contains IN (subquery) is cancelled, for example by KILL MUTATION or DETACH DATABASE, while the subquery's set is still being built. Related: #107619.

Description

Reported by @ alexey-milovidov on #112152 (comment) after a Stress test (amd_debug) run aborted this way.

buildSetInplace materializes the right side of IN (subquery) through a nested CompletedPipelineExecutor and polls the mutation's interactive-cancel callback. That callback returned a bare bool, so on cancellation the executor called cancel() and the poll loop returned normally: Set::finishInsert never ran, while build() had already moved the source plan out. buildSetsForDAG returns void, so getMinMaxCountProjectionBlock evaluated the filter in the same call and FunctionIn threw. A constant left-hand side (1 IN (...)) makes this the first materialization attempt: it maps to no key column, so primary-key analysis returns first.

The callback now throws ABORTED, mirroring MergeTask::checkOperationIsNotCanceled, which reports the merge path the same way and is likewise used as a nested-pipeline callback. MergeTreeBackgroundExecutor already treats ABORTED as a normal outcome and logs it at DEBUG. Only the mutation installs this callback shape, so the installers in TCPHandler and LocalConnection are untouched and client cancellation still returns QUERY_WAS_CANCELLED quietly.

Validation: KILL MUTATION and DETACH DATABASE mid-build abort the server before the change and are clean after it, and the table stays mutatable. New test 04865_cancel_mutation_in_subquery_minmax_projection, 50 of 50 runs. The other cancellation routes and overflow modes checked are listed in the validation gate comment below.

Out of scope: a caller that executes a filter DAG synchronously still does not check set readiness, and buildSetInplace still leaves the set unbuildable if some future path stops it silently. I found no input reaching either independently of this cancellation.

Note for review: #113939 rewrites the same lambda for the S3 read path but keeps the interactive callback non-throwing, so it does not fix this. The two conflict textually; a resolution must keep both the throw and that PR's cancellation persistence.

groeneai and others added 2 commits August 12, 2026 07:47
…ently

A mutation whose predicate contains `IN (subquery)` materializes the right-hand
side through `FutureSetFromSubquery::buildSetInplace`, which runs a nested
`CompletedPipelineExecutor` and polls the mutation's interactive-cancel callback.
The callback returned a bare `bool`, so on cancellation the executor called
`cancel()` and the poll loop returned normally: `CreatingSetsTransform::generate`
and therefore `Set::finishInsert` never ran, leaving the set uncreated while
`build()` had already moved the source plan out. `buildSetsForDAG` returns void,
so `getMinMaxCountProjectionBlock` went on to evaluate the filter in the same
call and `FunctionIn` threw "Not-ready Set is passed as the second argument for
function 'in'" - a server abort in debug and sanitizer builds.

Reported by @ alexey-milovidov on
ClickHouse#112152 (comment)
after a Stress test (amd_debug) run aborted this way. `DETACH DATABASE` during a
running mutation is the trigger seen in CI; `KILL MUTATION` reproduces it.

The callback now throws `ABORTED` on cancellation, mirroring
`MergeTask::checkOperationIsNotCanceled`, which reports the merge path the same
way and is likewise wired into nested pipelines.
`MergeTreeBackgroundExecutor` already treats `ABORTED` as a normal outcome and
logs it at DEBUG. Only the mutation installs this callback shape; the two
interactive installers in `TCPHandler` and `LocalConnection` are untouched, so
client-side cancellation still returns `QUERY_WAS_CANCELLED` quietly.

Instrumented measurement of the cancel path before the fix: of three mutating
parts, one returned from `execute()` with no exception and an uncreated set,
while the other two observed the `UNKNOWN_EXCEPTION` that
`~CreatingSetsTransform` sets on the shared promise - so the loud report was a
race, not a contract.

A readiness guard at the projection site was measured and deliberately not
added: with the cancellation reported, no user-runnable input reaches that sink.

Related: ClickHouse#107619

Co-Authored-By: Claude Fable 5 <[email protected]>
The test previously checked only side effects that outlive the abort: merges
draining to zero, the cancelled UPDATE not applying, and a later mutation
succeeding. All four hold on a build where LOGICAL_ERROR is caught rather than
fatal, because MutatePlainMergeTreeTask logs and rethrows it and the background
executor contains it, while KILL MUTATION has already removed the mutation
entry. The oracle was therefore live only on debug and sanitizer builds.

Assert instead that the cancelled mutation recorded ABORTED in system.part_log,
which is the outcome the fix produces and the unfixed code cannot: a silently
stopped set build leaves no such row. Poll for it, since the part log entry is
queued asynchronously, and fail loudly on timeout rather than passing vacuously.

Measured on the pre-fix binary: no ABORTED row, the poll times out, and the
server aborts with two "Not-ready Set" records at
getMinMaxCountProjectionBlock via isStorageTouchedByMutations.

Scoped by currentDatabase() and the table name so parallel copies of the test
cannot observe each other's part log rows.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open blockers)

Reviewed cold at 19e9c156e495aea (base 91687a7d610e6eec), then re-reviewed after one fix round.
The src/ change is 5 added lines in one lambda; everything else is the new test.

Round 1 -- 1 major, agreed and fixed

⚠️ cancel-oracle: the new test's only oracle was "the server survives", which is live only in
debug/sanitizer builds. Exception.cpp:96-116 aborts on LOGICAL_ERROR just when
debug_or_sanitizer_build || abort_on_logical_error, so a release build catches the Not-ready Set
throw, MutatePlainMergeTreeTask logs and rethrows it, and the background executor contains it --
and because KILL MUTATION has already erased the mutation entry, every reference row could still
match on a reverted release build. Fixed by asserting the cancellation is reported: a bounded poll
for a MutatePart row with errorCodeToName(error) = 'ABORTED' in system.part_log, failing loudly
on timeout.

The fix round changed test files only; git diff <base> HEAD -- src/ is byte-identical across the
two rounds (sha256 a2b8904f295c2280).

Round 1 -- 1 major, disagreed with evidence

❌ The same finding also asked for "zero non-ABORTED mutation errors for this table". That
assertion would be flaky. enable_sharing_sets_for_mutations defaults on, so the parts of one
mutation share a PreparedSetsCache entry; only the promise owner runs the pipeline, and when it
dies ~CreatingSetsTransform (CreatingSetsTransform.cpp:33-47) sets UNKNOWN_EXCEPTION on the
shared promise, which each waiter rethrows as Code: 1002 (:151-153). Measured: 1 silent + 2 x
1002 across 3 parts, and promise ownership is a race. Only the race-free existence form was adopted.

Round 2 -- Gate B clean

0 findings on the delta, with coverage over both mutation callers, the nested executor and set
construction, projection filtering, cancellation lifecycles, replicated handling, sibling guards and
the related tests.

Verified independently rather than taken from the plan

  • All 12 consumers of the interactive-cancel callback are throw-safe: no noexcept function and no
    destructor invokes it, and joinOrder.cpp:362 already documents throwing from it. Both executors
    cancel-then-join in their destructors (CompletedPipelineExecutor.cpp:29-33, :110-123).
  • Completeness of the carrier set: the other silent-stop route (soft time-limit break) needs a
    process_list_element, which a mutation's task context never gets, and
    transfer_overflow_mode='break' still reaches finishInsert.
  • MutateFromLogEntryTask shares mutatePartToTemporaryPart, and
    ReplicatedMergeMutateTaskBase.cpp:71-75 already special-cases ABORTED. Needs nothing.
  • 💡 The EXPLAIN probe pins projection settings on the client while the mutation runs on a
    background context (getBackgroundContext() + makeQueryContextForMutate). Randomized settings
    reach only client argv, so the mutation is not exposed to the 5% optimize_use_projections=0 draw
    and the probe cannot desynchronize it. Noted, not blocking.
  • 💡 LOG_ERROR on a reported ABORTED is pre-existing: MutateTask.cpp:1700-1706 already throws
    the identical exception through the same handler. No new logging behaviour.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2dabd5]

Summary: ✅


AI Review

Summary

This PR makes the mutation query context throw ABORTED when a nested IN (subquery) set build is cancelled, which fixes the reported KILL MUTATION / DETACH DATABASE path and adds a focused regression test around the minmax_count projection repro. That mutation-specific change looks correct, but the broader "silent stop leaves an unbuilt set behind" invariant is still reachable through the remaining boolean interactive-cancel callbacks, so I do not think the change is ready to merge yet.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp:506] This only fixes the mutation-installed callback. LocalConnection still returns a bare true from its interactive-cancel callback, and TCPHandler does the same for partial_result_on_first_cancel; FutureSetFromSubquery::buildSetInplace still treats that silent stop as success and buildSetsForDAG can still run into FunctionIn with an uncreated set. That leaves the same Not-ready Set failure reachable for local queries and first-cancel partial results instead of reporting cancellation.
    Suggested fix: either make the remaining callback installers report cancellation via exception too, or make buildSetInplace / its synchronous callers detect an uncreated set and stop before FunctionIn.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: close the remaining boolean-callback path (LocalConnection, and ideally the partial_result_on_first_cancel TCP path too) so cancelled IN (subquery) set builds cannot still fall through to Not-ready Set.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

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

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro ALTER TABLE t UPDATE b = 0 WHERE 1 IN (SELECT number FROM numbers(10000000) WHERE sleep(1) = 0) on a PARTITION BY a % 3 table, then KILL MUTATION once system.merges shows it running. Aborts every run on a debug build. DETACH DATABASE reproduces the same way and is the trigger seen in CI.
b Root cause explained The mutation's interactive-cancel callback returned a bare bool, so CompletedPipelineExecutor::execute cancelled the nested set-build pipeline and its poll loop returned normally. Set::finishInsert never ran, build() had already moved the source plan out, and buildSetsForDAG returns void, so getMinMaxCountProjectionBlock evaluated the filter in the same call and FunctionIn threw.
c Fix matches root cause The callback reports the cancellation instead of stopping the pipeline silently. Not a guard at the crash site: a readiness guard there was measured unreachable by any user-runnable input once the cancellation is reported, so it was not added.
d Test intent preserved / new test New 04865_cancel_mutation_in_subquery_minmax_projection. No existing test weakened. It asserts the outcome rather than only the side effects that outlive an abort: the cancelled mutation must record ABORTED in system.part_log, which a silently stopped set build never writes, so the oracle is live on release builds too and not only where LOGICAL_ERROR is fatal. Both its wait loops fail loudly rather than passing vacuously, so it cannot pass by cancelling a merely queued mutation or by never observing the part log row.
e Both directions demonstrated Server aborts before the change (signal 6, Not-ready Set, stack through getMinMaxCountProjectionBlock and isStorageTouchedByMutations); clean after it. On the pre-fix binary the new test fails with a stated failure mode: no ABORTED part log row is ever written, the poll times out, and the server then aborts. On the fixed binary it passes.
f General across code paths Carriers of "a cancelled background operation must report itself": the mutation callback (fixed), MergeTask::checkOperationIsNotCanceled (already throws ABORTED, the model followed here), and the two interactive installers in TCPHandler and LocalConnection, which must stay quiet and are untouched. setInteractiveCancelCallback has exactly three installers.
g Generalizes across inputs Type wrappers are not a dimension here: the predicate is cancellation state, not a value. Swept instead over cancellation routes (KILL MUTATION, DETACH DATABASE, DETACH TABLE, DROP TABLE, SYSTEM STOP MERGES, KILL QUERY, clickhouse local interrupt), the transfer/timeout/set break overflow modes, and predicate shapes containing scalar subqueries and JOINs.
h Backward compatible No setting, format or serialization change, so no SettingsChangesHistory.cpp entry. A cancelled mutation already failed; it now fails with ABORTED, which MergeTreeBackgroundExecutor already logs as a normal outcome.
i Invariants and contracts Re-entry checked: after DETACH and ATTACH the interrupted mutation is still listed and killable, and a subsequent mutation completes, so the table is not left unmutatable. The callback holds no lock across the throw, and destruction order in both pipeline executors cancels before joining the worker thread.

Also run: the sibling cancellation test 04516, the kill_mutation family, and the minmax_count projection family. 50 out of 50 runs of the new test pass with randomized settings, and 12 out of 12 concurrent runs pass at -j 4 (the part log query is scoped by currentDatabase() and the table name, so parallel copies cannot see each other's rows).

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @tiandiwonder, could you review this? A mutation's interactive-cancel callback returned a bare bool, so cancelling it stopped the nested IN (subquery) set-build pipeline without an exception, leaving the set unbuilt while its source plan was already moved out, and the minmax_count projection then evaluated a filter over that set. The callback now throws ABORTED, the way MergeTask::checkOperationIsNotCanceled already reports the merge path.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c2dabd5b7 with master 3662ba8a9 (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
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.72 MiB -3.01 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

…nistic

The flaky check failed on amd_msan and amd_tsan with `system.merges` reading 1
instead of 0 after `KILL MUTATION`.

`StorageMergeTree::killMutation` erases the mutation entry and then calls
`MergeList::cancelPartMutations`, which walks the entries present at that instant
and sets `is_cancelled` on them. A mutate task's MergeList entry is inserted in
`MutatePlainMergeTreeTask::prepare()`, which runs when the background executor
gives the task a thread, not when the task is assigned. So a task assigned before
the kill but still queued for a pool slot inserts its entry after the scan and
never gets cancelled. `KILL MUTATION` does not touch `merges_blocker` either, so
both disjuncts of the interactive-cancel predicate stay false for that task and it
runs to completion.

The test's precondition only waited for one running mutation, which does not
establish that every part of the 3-part table already holds an entry. Under the
contended msan/tsan pool one task routinely landed after the kill: CI's part_log
shows 2 parts ABORTED and the third starting after them and completing in 329 s,
so `system.merges` never drained. Locally, constraining the pool reproduces the
precondition directly - 2 of 3 parts hold an entry at kill time.

Put all rows in one partition, so one part means one mutate task and the task the
test waits for is provably the only one `cancelPartMutations` has to find. The
`b` values are unchanged, so the reference file is byte-identical and no assertion
is removed, relaxed or reordered. The drain wait now exits loudly on timeout like
the two sibling waits in the same file, instead of breaking into an assertion that
is then guaranteed to fail with an unexplained diff.

Verified: 31 runs on the fixed binary all pass, and the fixed test still reddens on
the pre-fix binary (server aborts with `Not-ready Set is passed as the second
argument for function 'in'`, sink frames getMinMaxCountProjectionBlock /
isStorageTouchedByMutations), so the oracle is unchanged.
system.part_log is append-only across DROP TABLE, and currentDatabase() is not
unique per invocation when a database is pinned: ci/jobs/scripts/stress/stress.py
passes --database=test_{i} so one database serves every test in that thread, and
--stress-tests reruns the selection until global_time_limit. A prior run's ABORTED
MutatePart row for the same table therefore satisfied the database/table plus
10-minute predicate, and the assertion that pins the cancellation reporting could
pass without this execution having reached the fixed path.

Measured on identical server state, in a pinned database holding a genuine ABORTED
row from an earlier run, with the table re-created and no cancellation performed:
the old predicate returned 1, the new one 0.

The bound is compared against event_time_microseconds rather than event_time:
04604_async_insert_dedup_prewarm_hash_count.sh records that a second-granularity
column truncates below a sub-second bound and drops the current run's own row.
Verified both ways on one bound - an event a microsecond after it is kept, and
would have been dropped by the second-granularity column.

Verification: fixed test on the fixed binary passes 6/6 in a pinned database while
stale rows accumulate, and once in a fresh random database; on the pre-fix binary
with 7 stale rows present it fails with "Cancelled mutation did not record ABORTED
in system.part_log", so the oracle no longer accepts them. The reference file is
byte-identical and no assertion was removed, relaxed or reordered.
The precondition asserts that the minmax_count projection is chosen for the
predicate shape the cancellation below exercises. It queried the table with
`optimize_trivial_count_query` left at whatever the run had, and under the old
analyzer that shortcut wins: the plan becomes `ReadFromPreparedSource
(Optimized trivial count)` and the assertion reports 0, so the job
`Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated,
WasmEdge, parallel, 1/3)` failed 3 of 3 reruns with a one-line `-1 / +0` diff.

The assertion was wrong, not the scenario. The mutation reads a single part
through StorageFromMergeTreeDataPart, which inherits
IStorage::supportsTrivialCountOptimization() == false, so the shortcut can
never apply on the mutation's own count query and the projection is always
reached there. The probe queried the real table, where MergeTreeData returns
true, so it answered a different question than the one under test. Measured on
the pre-fix binary with the old analyzer active server-side: the precondition
printed 0 while the server still aborted with
"Not-ready Set is passed as the second argument for function 'in'", sink frames
getMinMaxCountProjectionBlock and isStorageTouchedByMutations - the bug was
reachable in exactly the config the probe called uninteresting.

The setting is also randomized by the runner (5% chance of 0), so the probe had
a latent flake under the new analyzer too.

Measured, all four arms of {analyzer on, off} x {trivial count on, off}: the
old probe returns 0 for analyzer off with trivial count on and 1 elsewhere; the
pinned probe returns 1 in all four. End to end with the old analyzer set
server-side: fixed test 6/6 pass, old test reproduces CI's exact one-line diff
on the same server and binary, and the pre-fix binary runs the fixed test to a
line 1 of 1 before dying of the bug. Default new-analyzer shape with
randomization on: 3/3 pass.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c2dabd5

CI is fully finished on this head and there are no failures to own: 177 check-runs, 160 success / 17 skipped / 0 failure. Config Workflow and Finish Workflow both success; praktika result_pr.json reports top-level OK with 0 dropped jobs, so the matrix genuinely ran (all 17 skips carry a reason - performance, docker, PGO/BOLT, docs, bugfix-integration). CIDB agrees: 0 FAIL/ERROR rows across 162 checks on this sha.

Check / test Reason Owner / fixing PR
- no failed check on this head -

04865_cancel_mutation_in_subquery_minmax_projection failed on the previous head 65b98b1f in the llvm_coverage old-analyzer job and in the msan/tsan flaky checks. All five of those checks pass here, and the flaky checks are green across asan_ubsan, msan, tsan, debug and binary.

Session id: cron:our-pr-ci-monitor:20260813-193000

@alexey-milovidov alexey-milovidov 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.

The fix is good. Approved.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 87b6367 Aug 17, 2026
181 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 17, 2026
Master now carries ClickHouse#114463, which made the mutation interactive-cancel
callback throw ABORTED instead of returning a bare bool, so that a nested
pipeline stopped mid-build cannot be mistaken for one that completed. This
branch had independently rewritten the same lambda to latch a detected
cancellation and to install the thread group's cancellation predicates, which
is what the S3 retry loop actually polls.

Both properties are required and neither subsumes the other, so the resolution
keeps both: the latching predicate is shared by the interactive-cancel callback
and by the group's predicates, and the throwing wrapper is derived from it once.
Keeping only this branch's side would have silently reverted ClickHouse#114463's throw.
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Aug 30, 2026
`FutureSetFromSubquery::buildSetInplace` materializes the right side of
`IN (subquery)` through a nested `CompletedPipelineExecutor` and polls the
query's interactive-cancel callback. A callback that only returns `true` stops
that pipeline silently: the poll loop cancels the pipeline and returns
normally, so `CreatingSetsTransform::generate` never runs `Set::finishInsert`,
while `build` has already moved the source plan out. A caller that evaluates
its filter in the same call - the `minmax_count` projection, through
`VirtualColumnUtils::filterBlockWithPredicate` - then passes the unbuilt set to
`FunctionIn`, which reports `Not-ready Set is passed as the second argument for
function 'in'`, a `LOGICAL_ERROR`.

`TCPHandler` installs such a callback for `partial_result_on_first_cancel`: the
first cancel only sets `stop_read_return_partial_result` and deliberately does
not cancel through the process list. One cancel of

    SELECT count() FROM t WHERE 1 IN (SELECT number FROM numbers(10000000) WHERE sleep(1) = 0)
    SETTINGS partial_result_on_first_cancel = 1, optimize_use_implicit_projections = 1,
             optimize_trivial_count_query = 0

reproduces it on every run, and a debug or sanitizer build aborts on it. The
other installer, `LocalConnection`, cancels through the process list element,
so its nested pipeline fails rather than stopping silently and the same query
interrupted with `SIGINT` reports `QUERY_WAS_CANCELLED`; it is untouched here.

`buildSetInplace` now records whether the cancel callback fired and reports
`QUERY_WAS_CANCELLED` when the set was left uncreated. Both conditions are
required, so a pipeline stopped for any other reason keeps its behaviour:
`set_overflow_mode`, `transfer_overflow_mode` and `read_overflow_mode = 'break'`
all still reach `generate`, which finishes the set.

Follow-up to ClickHouse#114463, which
reports a cancelled mutation as `ABORTED` from the callback itself and so
covers every nested pipeline a mutation runs, not only `buildSetInplace`.

Co-Authored-By: Claude Fable 5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants