Skip to content

Make INSERT responsive to cancellation when a block creates many partitions - #108062

Closed
alexey-milovidov wants to merge 1 commit into
masterfrom
fix-insert-many-partitions-hung
Closed

alexey-milovidov wants to merge 1 commit into
masterfrom
fix-insert-many-partitions-hung

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

A single INSERT block can be scattered into a very large number of single-partition parts — for example, a high-cardinality partition by expression together with throw_on_max_partitions_per_insert_block = 0. In that case MergeTreeSink::consume and ReplicatedMergeTreeSink::consume wrote every part in one loop without ever returning to the pipeline executor. Because the executor enforces max_execution_time and KILL QUERY only between consume calls, such an INSERT could not be interrupted and ran until all parts were written.

This was found by the AST fuzzer in the stress test: it turned numbers_mt(10) into roughly numbers_mt(1048577) for an insert into a partition by key table, producing about 1048577 single-row parts on object storage. The query ran for over 1400 seconds, the hung check failed, the server could not shut down (the thread was stuck inside consume), and the subsequent restart failed with Address already in use — surfacing as Hung check failed, possible deadlock found, Cannot start clickhouse-server, and Check failed.

The fix checks the query time limit via QueryStatus::checkTimeLimit at the start of each per-partition iteration, so the INSERT honors max_execution_time and KILL QUERY instead of running an uninterruptible loop. This mirrors the pattern already used in StorageMergeTree and StorageReplicatedMergeTree. Normal inserts (one or a few partitions) are unaffected: it is a single cheap check per partition that only throws when a limit is actually reached.

Added a regression test 04358_insert_many_partitions_cancellable that asserts such an INSERT returns TIMEOUT_EXCEEDED instead of hanging.

CI report (master): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a006dbd8a1e92a14b7404c4bfdcd90b6345ab6ee&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

Related: #107941

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 an INSERT that creates a large number of partitions in a single block (for example, a high-cardinality partition by together with throw_on_max_partitions_per_insert_block = 0) being uninterruptible: it now respects max_execution_time and KILL QUERY.

🤖 Generated with Claude Code

…itions

When a single INSERT block is scattered into a large number of single-partition
parts (for example, a high-cardinality `partition by` expression together with
`throw_on_max_partitions_per_insert_block = 0`), `MergeTreeSink::consume` and
`ReplicatedMergeTreeSink::consume` wrote every part in one loop without ever
returning to the pipeline executor. The executor enforces `max_execution_time`
and `KILL QUERY` only between `consume` calls, so such an INSERT could not be
interrupted and ran until all parts were written.

The AST fuzzer in the stress test turned `numbers_mt(10)` into roughly
`numbers_mt(1048577)` for an insert into a `partition by key` table, producing
about 1048577 single-row parts on object storage. The query ran for over 1400
seconds, the hung check failed, the server could not shut down (the thread was
stuck inside `consume`), and the subsequent restart failed with
"Address already in use".

Check the query time limit via `QueryStatus::checkTimeLimit` at the start of each
per-partition iteration, so the INSERT honors `max_execution_time` and `KILL QUERY`
instead of running an uninterruptible loop. This matches the existing pattern used
in `StorageMergeTree` and `StorageReplicatedMergeTree`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a006dbd8a1e92a14b7404c4bfdcd90b6345ab6ee&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

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

clickhouse-gh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ce1958b]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, flaky check) FAIL
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
Too many test failures FAIL cidb
ThreadSanitizer (STID: 1003-358c) FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
04358_insert_many_partitions_cancellable FAIL cidb
Some queries hung FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
02293_selected_rows_and_merges FAIL cidb
Integration tests (amd_msan, 5/6) FAIL
test_paimon_incremental_read/test.py::test_paimon_incremental_read_via_paimon_table_engine FAIL cidb
test_paimon_incremental_read/test.py::test_paimon_to_mergetree_via_refresh_mv FAIL cidb
Stress test (arm_msan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

The PR makes many-partition INSERT into MergeTree and ReplicatedMergeTree check query cancellation/time limits between per-partition temporary part writes, and adds a stateless timeout regression for the plain MergeTree path. The direction is right, but the same consume call can still spend a long time finalizing/committing a delayed batch without checking cancellation, and the replicated sink change lacks focused regression coverage.

Missing context / blind spots
  • ⚠️ The PR CI report fetched from the bot link currently contains zero test results, so CI does not validate the new stateless test or wider insert coverage. A completed PR run would close this.
  • ⚠️ I did not run the stateless test locally because this checkout has no local build* directory with a server/client binary.
Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeSink.cpp:128] The new cancellation check only covers the temporary-part creation loop. The delayed finalization/commit loops (MergeTreeSink::finishDelayedChunk and ReplicatedMergeTreeSink::finishDelayed) can still process a large accumulated batch without consulting the ProcessList, especially when max_insert_delayed_streams_for_parallel_write is raised, so KILL QUERY or throw-mode max_execution_time can still be ignored until the whole batch finishes.
    Suggested fix: add the same per-partition check inside both delayed finalization loops, or make the delayed batch size bounded independently of that setting.
Tests
  • ⚠️ [tests/queries/0_stateless/04358_insert_many_partitions_cancellable.sql:11] The regression test only exercises the plain MergeTree sink, while the PR also changes ReplicatedMergeTreeSink::consume. Add a small ReplicatedMergeTree variant using the same high-cardinality partition by block and max_execution_time assertion.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: cover cancellation inside the delayed finalization/commit phase for both sinks, and add replicated regression coverage for the changed replicated path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 21, 2026
/// cancellation only between `consume` calls. Check it here so such a query stays responsive
/// to `max_execution_time` and `KILL QUERY` instead of running an uninterruptible loop.
if (auto process_list_element = context->getProcessListElement())
process_list_element->checkTimeLimit();

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.

The new check covers the temporary-part creation loop, but the same consume call can still spend a long time in the delayed finalization/commit phase without any cancellation check. finishDelayedChunk iterates delayed_chunk->partitions and finalizes/commits each part without consulting the ProcessList, and the batch can contain many partitions when max_insert_delayed_streams_for_parallel_write is raised (object-storage writes also use delayed batches by default). A KILL QUERY or throw-mode max_execution_time that arrives during that phase is still ignored until the whole delayed batch is done, so the many-partition INSERT can remain stuck inside consume/onFinish.

Please add the same per-partition check inside finishDelayedChunk and the replicated finishDelayed loop, or otherwise make the delayed batch size bounded independently of that setting.

-- the time limit, hanging the query (and the server shutdown) for many minutes.

drop table if exists t_many_partitions_cancel;
create table t_many_partitions_cancel (key Int) engine = MergeTree order by key partition by key;

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.

This PR also changes ReplicatedMergeTreeSink::consume, but the regression test only exercises the plain MergeTree sink. If the replicated check is removed, 04358_insert_many_partitions_cancellable still passes, so the replicated half of the promised fix has no regression coverage.

Please add a small ReplicatedMergeTree variant, either in this test with the appropriate tags or as a separate stateless test, using the same high-cardinality partition by block and max_execution_time assertion.

@clickhouse-gh

clickhouse-gh Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 10/10 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 18 line(s) · Uncovered code

Full report · Diff report

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

duplicate #107929

@Michicosun

Copy link
Copy Markdown
Member

Btw imo the right place to check it is in the low-level data writing functions. Somewhere in the write buffers or in the keeper client. This looks like an ad-hoc single-place fix.

I tried ~ this #89286

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing as a duplicate.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants