Skip to content

Fix a cancelled INSERT not stopping while building a skip index - #108351

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix-skip-index-build-ignores-cancellation
Jun 28, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix-skip-index-build-ignores-cancellation

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A cancelled INSERT can keep running for a long time while it is building a secondary (skip) index. In Stress test (arm_tsan) an AST-fuzzer-mutated INSERT building a set skip index stayed in system.processes with is_cancelled = 1 for ~19 minutes (MergeTreeDataWriterSkipIndicesCalculationMicroseconds ≈ 1145 s), which tripped the 60 s hung-check ("possible deadlock found"). This is not a deadlock — the thread is making forward progress — and a user KILL QUERY cannot abort the build either.

The originating scenario (from 03374_indexes_with_trivial_cast.sql) is a set(0) index with index_granularity = 1:

CREATE TABLE test (`x` String, INDEX idx1 x TYPE set(0) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 1;
INSERT INTO test SELECT number FROM numbers(1000);

With index_granularity = 1, the 1000-row block produces 1000 single-row granules; under arm_tsan each granule's index work is slow enough that the whole build takes ~1145 s. So the long runtime is spread across many granules, not one giant granule.

Root cause

The per-granule skip-index build loop in MergeTreeDataPartWriterOnDisk::calculateAndSerializeSkipIndices has no cancellation point. The INSERT pipeline only enforces query limits between blocks (MergeTreeSink::consume checks isCancelled per block), so once execution is inside MergeTreeDataWriter::writeTempPart → writer → calculateAndSerializeSkipIndices → IMergeTreeIndexAggregator::update, neither cancellation nor max_execution_time is observed until the whole block's index build finishes.

This is not a regression of #107971, which only touches the read side (MergeTreeIndexConditionSet::atomFromDAG); the hang is on the write side (MergeTreeIndexAggregatorSet::update), a pre-existing behavior the fuzzer exposed.

Fix

Fetch the query status once and call checkTimeLimit once per granule inside calculateAndSerializeSkipIndices, mirroring the existing precedent in MergeTreeIndexVectorSimilarity (and the read-side MergeTreeDataSelectExecutor). The check is cheap (an atomic flag plus an elapsed-timer read), lives in the shared writer path so it covers every skip-index type and both wide and compact part writers, and honors both cancellation and max_execution_time in throw mode. set(0) semantics are unchanged.

Per-granule placement is sufficient for the failing scenario: with index_granularity = 1 the build is 1000 single-row granules, so the check effectively runs per row and a cancelled query is observed after at most one granule (~1.1 s under arm_tsan) instead of after the full ~1145 s build. The only case it would not cover is a single pathologically large granule, but that build would be fast and could not produce the multi-minute hang seen here.

Regression test 04409_skip_index_build_cancellation.sh: a single-block INSERT is driven into the skip-index build phase (confirmed via the MergeTreeDataWriterSkipIndicesCalculationMicroseconds profile event), then cancelled; the test requires KILL QUERY ... SYNC to return within a bound. With the fix it returns in ~1 s; without it the KILL blocks until the whole block's build completes. The test is a deterministic reproduction of the underlying defect, not a 1:1 replay of the arm_tsan stress run.

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 cancelled or KILLed INSERT continuing to run for a long time while building a skip index (for example an unbounded set(0) index on a high-cardinality column). The index build now stops promptly when the query is cancelled.

Version info

  • Merged into: 26.7.1.206 (included in 26.7 and later)

Building a secondary (skip) index during an INSERT runs granule by granule in
`MergeTreeDataPartWriterOnDisk::calculateAndSerializeSkipIndices` with no
cancellation point. The INSERT pipeline only enforces query limits between
blocks (`MergeTreeSink::consume`), so once execution is inside `writeTempPart`
-> writer -> skip-index build, a `KILL QUERY` cannot interrupt it. An unbounded
`set(0)` index on a high-cardinality column with a small `GRANULARITY` makes that
build run for minutes, which tripped the 60s hung-check in `Stress test
(arm_tsan)` even though the query was already cancelled (`is_cancelled = 1`).

Check the query status once per granule via `checkTimeLimit`, mirroring the
existing precedent in `MergeTreeIndexVectorSimilarity`. This covers every
skip-index type in one shared place and honors both cancellation and
`max_execution_time` (throw mode). `set(0)` semantics are unchanged.

Related: #107971

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

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe73918]

Summary: ✅


AI Review

Summary

This PR adds a per-granule query-status check while serializing MergeTree skip indices, so a cancelled INSERT can stop during a long skip-index build instead of waiting for the whole block to finish. It also adds a focused stateless regression test that waits until MergeTreeDataWriterSkipIndicesCalculationMicroseconds shows the insert is in the skip-index build phase before issuing KILL QUERY ... SYNC. I did not find an unresolved correctness, safety, or test-coverage issue that warrants an inline finding.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 24, 2026
The stateless test runner injects random query settings; an injected
`max_rows_to_read = 20000000` aborts the test's `INSERT ... SELECT ... FROM
numbers(30000000)` with `TOO_MANY_ROWS` before the skip-index build starts, so
the poll never observes the build phase and the test prints "did not observe the
skip-index build phase" instead of "killed promptly". The same injection (plus a
random `max_execution_time` / `max_memory_usage`) failed the test deterministically
across all stateless shards (amd_debug, amd_tsan, amd_asan_ubsan, arm_binary).

The pre-existing `no-random-merge-tree-settings` tag only pins MergeTree settings,
not query limits. Add `no-random-settings` so the read/time/memory limits stay at
their unlimited defaults, which is what the single large controlled INSERT and the
self-managed `KILL QUERY` need.

Verified on a local Debug build: injecting the limit reproduces `TOO_MANY_ROWS`,
and with default settings the INSERT reaches the build phase and `KILL QUERY ...
SYNC` returns in ~0.2s ("killed promptly").

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108351&sha=248ef255ef8e89d4673b7b07842d3d0857230e45&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ndom

The previous fix added `no-random-settings`, but `04409` kept failing
deterministically on every CI stateless shard with
`Code: 158 ... max_rows_to_read ... max rows: 20.00 million, current rows: 30.00 million`.

Root cause: `max_rows_to_read = 20000000` is set by the fixed `default` test
profile in `tests/config/users.d/limits.yaml`, applied to all CI stateless runs.
It is not a randomized setting, so `no-random-settings` does not relax it. The
test intentionally reads 30M rows in one block to make the skip-index build long
enough to observe and cancel mid-build, so the 30M-row INSERT trips the 20M cap
before the build phase begins.

Override the cap on the INSERT with `--max_rows_to_read 0` and correct the
rationale comment. Reproduced the exact error with `--max_rows_to_read 20000000`
on `numbers(30000000)`; `--max_rows_to_read 0` clears it (client/query settings
override profile defaults).

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

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 9/9 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

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

Perfect, thank you!

@alexey-milovidov alexey-milovidov self-assigned this Jun 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 28, 2026
Merged via the queue into master with commit 74b0388 Jun 28, 2026
167 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-skip-index-build-ignores-cancellation branch June 28, 2026 18:08
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 28, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…uild-ignores-cancellation

Fix a cancelled INSERT not stopping while building a skip index
ylw510 pushed a commit to ylw510/ClickHouse that referenced this pull request Oct 24, 2026
…umns

The column-write loops of `MergeTreeDataPartWriterCompact::writeDataBlock` and
`MergeTreeDataPartWriterWide::writeColumn` iterate over all granules of a block
with no cancellation point. Query limits of an INSERT are checked only between
blocks (`MergeTreeSink::consume`, the pipeline executor), so an INSERT that is
killed, or cancelled for `max_execution_time`, keeps writing its current block
to the end. With small granules and columns with many substreams (JSON,
Dynamic, Variant) or with projections this takes minutes, and the Stress test
hung check reports it (for example 566 s in `SerializationVariant` /
`SerializationDynamic` under `writeProjectionPart` on arm_tsan).

Call `CurrentThread::checkIfNotCancelled` at the start of every granule in
both loops. In a query thread group it throws `QUERY_WAS_CANCELLED` or
`TIMEOUT_EXCEEDED` from the query's `QueryStatus`; in a merge or mutation
thread group it throws the `ABORTED` that `MergeTask` / `MutateTask` already
throw between blocks; with no thread group it does nothing. The part being
written is not committed, as with any other error inside the writer. The
skip-index loop of the same writer already checks per granule (ClickHouse#108351).

This is the column-write-loop part of ClickHouse#108357.

The new test kills a single-block INSERT of 1-row granules while it writes
the part, for both Compact and Wide parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

3 participants