Skip to content

Cancel a mutation's IN-subquery set build on shutdown / KILL MUTATION - #110198

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-51586-cancel-mutation-in-subquery-set-build
Jul 17, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-51586-cancel-mutation-in-subquery-set-build

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

A mutation whose x IN (subquery) right-hand side is materialized during primary-key / skip-index analysis (KeyCondition::buildOrderedSetInplace → FutureSetFromSubquery::buildOrderedSetInplace) runs a nested, blocking CompletedPipelineExecutor to build the set. A background mutation's query context has no process-list element, no progress callback, and no interactive-cancel callback on that speculative build, so a large or slow subquery blocked server shutdown, SYSTEM STOP MERGES, and KILL MUTATION until the whole subquery had finished. (The use_index_for_in_with_subqueries_max_values cap only bounds the retained set elements, not the subquery runtime.)

MergeTreeDataMergerMutator::mutatePartToTemporaryPart now installs an interactive-cancel callback on the mutation's query context that mirrors MutationContext::checkOperationIsNotCanceled (merges_blocker / is_cancelled). The reading context resolves getQueryContext back to this query context (set up by makeQueryContextForMutate), so the nested CompletedPipelineExecutor polls the callback and aborts the set build promptly on cancellation. This covers both plain (MutatePlainMergeTreeTask) and replicated (MutateFromLogEntryTask) mutations.

Verified locally with an A/B build: with the fix KILL MUTATION on an in-flight x IN (slow subquery) set build clears the merge-list entry in ~0.8s; without it the entry lingers for the whole subquery duration. New test 04516_cancel_mutation_in_subquery_set_build reproduces this and complements the existing 03644_cancel_huge_mutation_subquery.

Closes: #51586

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 slow server shutdown and unresponsive KILL MUTATION when a mutation with x IN (subquery) was building the subquery set during primary-key analysis; the set build is now cancelled promptly.

A mutation whose `x IN (subquery)` right-hand side is materialized during
primary-key / skip-index analysis (`KeyCondition::buildOrderedSetInplace`) used
to run that nested set-building pipeline without observing mutation
cancellation. A background mutation's query context has no process list element,
no progress callback, and no interactive-cancel callback on this speculative
build, so a large or slow subquery blocked server shutdown, `SYSTEM STOP
MERGES`, and `KILL MUTATION` until the whole subquery had finished.

`mutatePartToTemporaryPart` now installs an interactive-cancel callback on the
mutation's query context that mirrors `MutationContext::checkOperationIsNotCanceled`
(`merges_blocker` / `is_cancelled`). The reading context resolves `getQueryContext`
back to this query context, so the nested `CompletedPipelineExecutor` in
`FutureSetFromSubquery::buildOrderedSetInplace` polls the callback and aborts the
set build promptly on cancellation.

Closes: #51586

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8fb3108]

Summary: ✅


AI Review

Summary

This PR wires the mutation query context's interactive-cancel callback into nested IN (subquery) set builds, so KILL MUTATION / shutdown can stop the CompletedPipelineExecutor that KeyCondition::buildOrderedSetInplace runs during mutation planning. On the current head, the earlier false-pass test concern and the shared PreparedSetsCache poisoning issue are both addressed, and I did not find any remaining correctness, safety, or coverage gaps in the touched paths.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@tiandiwonder tiandiwonder self-assigned this Jul 13, 2026

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: the description says the new test "also strengthens the existing 03644_cancel_huge_mutation_subquery", but the diff doesn't touch 03644 — "complements" would avoid sending readers looking for a change that isn't there.

Comment on lines +496 to +504
/// Reading and analysis performed while building the mutation pipeline can run nested, blocking
/// pipelines of their own via `CompletedPipelineExecutor` - most notably `buildOrderedSetInplace`
/// in `KeyCondition`, which materializes the right-hand side of `x IN (subquery)` to use it for
/// primary-key / skip-index analysis. Such a build has no way to observe mutation cancellation, so
/// a large set could block server shutdown or `KILL MUTATION` for a long time (see issue #51586).
/// The nested `CompletedPipelineExecutor` polls the query context's interactive-cancel callback, so
/// install one here that mirrors `MutationContext::checkOperationIsNotCanceled`. `context` is the
/// mutation's query context (`makeQueryContextForMutate`), so the callback is reachable from the
/// reading context via `getQueryContext`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: this comment could be tighter — the analysis-mechanism detail reads better in the PR description, and "mirrors MutationContext::checkOperationIsNotCanceled" is subtly off (that function's ?:/|| precedence skips is_cancelled when new_data_part is set, so this lambda is actually stronger).

Suggested change
/// Reading and analysis performed while building the mutation pipeline can run nested, blocking
/// pipelines of their own via `CompletedPipelineExecutor` - most notably `buildOrderedSetInplace`
/// in `KeyCondition`, which materializes the right-hand side of `x IN (subquery)` to use it for
/// primary-key / skip-index analysis. Such a build has no way to observe mutation cancellation, so
/// a large set could block server shutdown or `KILL MUTATION` for a long time (see issue #51586).
/// The nested `CompletedPipelineExecutor` polls the query context's interactive-cancel callback, so
/// install one here that mirrors `MutationContext::checkOperationIsNotCanceled`. `context` is the
/// mutation's query context (`makeQueryContextForMutate`), so the callback is reachable from the
/// reading context via `getQueryContext`.
/// Building the mutation pipeline can run nested blocking pipelines via `CompletedPipelineExecutor` -
/// most notably `KeyCondition::buildOrderedSetInplace` materializing the right side of `x IN (subquery)`.
/// Such a build observes cancellation only through the query context's interactive-cancel callback, so
/// without one it blocks server shutdown and `KILL MUTATION` until the subquery finishes (issue #51586).
/// `context` is this mutation's query context, which the reading context resolves via `getQueryContext`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — you're right that the ?:/|| precedence in checkOperationIsNotCanceled skips the is_cancelled check when new_data_part is set, so this lambda is stronger, not a mirror. I've rewritten the comment along the lines of your suggestion, describing the mechanism directly and dropping the mirrors reference. Also changed "strengthens" to "complements" in the PR description for 03644. Thank you!

The reviewer (tiandiwonder) noted that describing the callback as
mirroring `MutationContext::checkOperationIsNotCanceled` is subtly off:
because `?:` has lower precedence than `||`, that function skips the
`is_cancelled` check whenever `new_data_part` is set, so this lambda
(which always checks both the partition blocker and `is_cancelled`) is
actually stronger. Rewrite the comment to describe the mechanism
directly and drop the inaccurate "mirrors" reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 13, 2026 14:36
… state

The regression test `04516_cancel_mutation_in_subquery_set_build.sh` waited
for the mutation to be running (present in `system.merges` with `elapsed > 2`)
before issuing `KILL MUTATION`, but on timeout it only logged a message and
`break`-ed out of the loop, continuing the test. On a busy worker that left a
false-pass path: `KILL MUTATION` would cancel a still-queued mutation,
`system.merges` would already be empty, and the final `0` / `100` output would
match the reference without ever exercising the in-flight
`CompletedPipelineExecutor` cancellation path this PR fixes.

Make the timeout fail hard with `exit 1` (as `03644_cancel_huge_mutation_subquery.sh`
already does), so the test cannot pass unless the mutation actually reached the
running `system.merges` state that the fix is meant to cover.

Addresses the AI Review "Request changes" verdict on PR #110198.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The two red checks on cbdf5d9a287 are unrelated to this PR, and fixes for both are already in progress:

AI Review is ✅ Approve on the current head.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CH Inc sync red ("tests failed") on 41fb31111fd was unrelated to this PR: the private test_storage_iceberg_with_spark/test_compaction.py suite mass-failed with Spark's Unsupported type: UTF8String, caused by #106952 (Parquet dictionary filter), which this branch had picked up in the previous master merge. That PR was reverted on master by #110354, so I merged master again to pull in the revert — the sync should go green on the new head 52811f85bd4.

The only other red, test_replicated_database::test_replicated_table_structure_alter (Integration tests amd_msan 7/8), is the known flaky #110036 with fix #110145 still open.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only red on 52811f85bd4 — Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) — is unrelated to this PR: the server aborted with a LOGICAL_ERROR ("Arguments of multiply have incorrect data types: n of type Int256, 0.123 of type Float64") from ActionsDAG::evaluatePartialResult while running 03915_exchange_tables_race.sh, which cascaded into "server died" failures for the rest of the shard.

This is the known race tracked in #110133 (fails on master itself, independent of any PR). @groeneai already has a fix open: #109747.

AI Review is ✅ Approve on the current head.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CH Inc sync red ("tests failed") on 52811f85bd4 is unrelated to this PR: the private sync PR (https://github.com/ClickHouse/clickhouse-private/pull/64215) failed on test_distributed_cache/test.py::test_graceful_shutdown, 02539_vertical_merge_compact_parts, and 04150_move_partition_inconsistent_granularity — none of which touch mutation/KeyCondition code this PR changes. Reran the failed jobs.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master into the branch (f8577171081, no conflicts; PR diff unchanged, affected TUs recompiled cleanly).

Rationale: the CH Inc sync red on the previous head was deterministic, not flaky — after the rerun, the private sync PR still failed 04150_move_partition_inconsistent_granularity, because the branch carried that test (from #110535's first landing) while master had already removed it in the revert af1b1f378c8. Merging master pulls in the revert and clears that red.

Remaining known-unrelated flaky reds, both with open fixes not yet on master:

…hared PreparedSetsCache

The AI review of #110198 flagged that installing an interactive-cancel
callback on a mutation's query context lets a nested `IN (subquery)` set
build be stopped mid-flight by `KILL MUTATION` / shutdown - but also by a
per-partition cancellation (`stopMergesAndWaitForPartition` /
`cancelForPartition`, used by `REPLACE`/`MOVE`/`DROP PARTITION`). When such a
build is cancelled, `CreatingSetsTransform`'s destructor stores a
"Failed to build set, most likely pipeline executor was stopped" exception
into the mutation-scoped `PreparedSetsCache` (shared across the part tasks of
one plain `MergeTree` mutation when `enable_sharing_sets_for_mutations` is on,
the default). `PreparedSetsCache::findOrPromiseToBuild` then rethrew that
sticky exception to every later user of the same key, so cancelling one
partition's task could break sibling tasks in partitions that were not
cancelled.

Make a poisoned cache entry rebuildable instead of a permanent failure:
`findOrPromiseToBuild` now treats a ready future that holds an exception the
same way it already treats a ready future holding a null set - it drops the
entry and hands out a fresh promise so the set is rebuilt. This matches the
existing intent documented in `FutureSetFromSubquery::buildOrderedSetInplace`,
where the non-destructive speculative build already avoids sharing through the
cache for exactly this reason. A cancelled sibling part task now fails at most
once and rebuilds the set on its next attempt.

Add `gtest_prepared_sets_cache` covering reuse of a successful set, rebuild of
a null result, and - the regression - rebuild after a builder stored an
exception (both for a later caller and for a concurrent waiter's retry).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI Review "Request changes" finding on ebbb745196c.

The reviewer correctly noted that the new interactive-cancel callback also fires on per-partition cancellation (stopMergesAndWaitForPartition → cancelForPartition, used by REPLACE/MOVE/DROP PARTITION), so cancelling one plain-MergeTree mutation part task could poison the mutation-scoped PreparedSetsCache (shared across the mutation's part tasks under the default enable_sharing_sets_for_mutations) and break sibling tasks in partitions that were not cancelled. Fixed by making a poisoned (exception-holding) cache entry rebuildable in PreparedSetsCache::findOrPromiseToBuild, exactly as it already treats a null result — details in the inline reply. Added gtest_prepared_sets_cache as a regression guard (4 tests, all green locally).

The Stress test (arm_release) red is unrelated: a Block structure mismatch LOGICAL_ERROR in UnionStep::updateOutputHeader during the tryRemoveUnusedColumns query-plan optimization, hit by an AST-fuzzer EXPLAIN query — the known issue #108332, in the plan optimizer, nothing to do with the mutation/KeyCondition/PreparedSetsCache change here.

…romiseToBuild

The `check_catch_all` style check flagged the `catch (...)` added in
`ebbb745196c` (`PreparedSets.cpp:774`) as silently swallowing exceptions.
The catch is intentional — a cached set build that finished by throwing
(e.g. a cancelled `CreatingSetsTransform`) is dropped and rebuilt rather
than rethrown to an unrelated caller — so annotate it with an `Ok`
comment as the check expects, keeping the existing `NOLINT` for
`bugprone-empty-catch`.

This was the sole real failure on `ebbb745196c`: the `catch_all` style
violation dropped the whole PR workflow, which in turn dropped the
per-arch `Bugfix validation (functional tests, ...)` jobs and made the
`new_tests_check.py` gate (`Finish Workflow`) fail. Both jobs passed on
the prior head `f8577171081`, so fixing the style check clears both reds.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Fixed the two reds on ebbb745196c in 8fb3108d687 — both were caused by a single, self-inflicted style-check violation:

  • Style check (catch_all): the catch (...) added for the PreparedSetsCache poison-recovery fix (PreparedSets.cpp:774) was flagged as silently swallowing exceptions. The catch is intentional (a failed/cancelled cached set build is dropped and rebuilt, not rethrown to an unrelated caller), so I annotated it with an Ok comment as check_catch_all expects, keeping the existing NOLINT(bugprone-empty-catch).
  • Finish Workflow (new_tests_check.py): this was a cascade of the above. The catch_all failure dropped the entire PR workflow, which dropped the per-arch Bugfix validation (functional tests, ...) jobs, so the gate could not observe a passing validation. Both FT validation jobs (amd64 445s, aarch64 394s) and Finish Workflow were green on the prior head f8577171081, so clearing the style check restores both.

The AI Review ⚠️ Request changes finding on the shared-PreparedSetsCache poisoning was addressed earlier in ebbb745196c (inline reply on MergeTreeDataMergerMutator.cpp:503, plus gtest_prepared_sets_cache); the Code Review job was DROPPED by the same style-check cascade, so it will re-evaluate on 8fb3108d687.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.10% -0.10%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 17, 2026
Merged via the queue into master with commit e998669 Jul 17, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-51586-cancel-mutation-in-subquery-set-build branch July 17, 2026 15:09
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… state

The regression test `04516_cancel_mutation_in_subquery_set_build.sh` waited
for the mutation to be running (present in `system.merges` with `elapsed > 2`)
before issuing `KILL MUTATION`, but on timeout it only logged a message and
`break`-ed out of the loop, continuing the test. On a busy worker that left a
false-pass path: `KILL MUTATION` would cancel a still-queued mutation,
`system.merges` would already be empty, and the final `0` / `100` output would
match the reference without ever exercising the in-flight
`CompletedPipelineExecutor` cancellation path this PR fixes.

Make the timeout fail hard with `exit 1` (as `03644_cancel_huge_mutation_subquery.sh`
already does), so the test cannot pass unless the mutation actually reached the
running `system.merges` state that the fix is meant to cover.

Addresses the AI Review "Request changes" verdict on PR ClickHouse#110198.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…hared PreparedSetsCache

The AI review of ClickHouse#110198 flagged that installing an interactive-cancel
callback on a mutation's query context lets a nested `IN (subquery)` set
build be stopped mid-flight by `KILL MUTATION` / shutdown - but also by a
per-partition cancellation (`stopMergesAndWaitForPartition` /
`cancelForPartition`, used by `REPLACE`/`MOVE`/`DROP PARTITION`). When such a
build is cancelled, `CreatingSetsTransform`'s destructor stores a
"Failed to build set, most likely pipeline executor was stopped" exception
into the mutation-scoped `PreparedSetsCache` (shared across the part tasks of
one plain `MergeTree` mutation when `enable_sharing_sets_for_mutations` is on,
the default). `PreparedSetsCache::findOrPromiseToBuild` then rethrew that
sticky exception to every later user of the same key, so cancelling one
partition's task could break sibling tasks in partitions that were not
cancelled.

Make a poisoned cache entry rebuildable instead of a permanent failure:
`findOrPromiseToBuild` now treats a ready future that holds an exception the
same way it already treats a ready future holding a null set - it drops the
entry and hands out a fresh promise so the set is rebuilt. This matches the
existing intent documented in `FutureSetFromSubquery::buildOrderedSetInplace`,
where the non-destructive speculative build already avoids sharing through the
cache for exactly this reason. A cancelled sibling part task now fails at most
once and rebuilds the set on its next attempt.

Add `gtest_prepared_sets_cache` covering reuse of a successful set, rebuild of
a null result, and - the regression - rebuild after a builder stored an
exception (both for a later caller and for a concurrent waiter's retry).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-mutation-in-subquery-set-build

Cancel a mutation's IN-subquery set build on shutdown / KILL MUTATION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Slow shutdown: mutation cannot be cancelled in buildOrderedSetInplace

3 participants