Repository navigation
Make column data write during INSERT respond to query cancellation - #108357
tiandiwonder wants to merge 28 commits into
Conversation
`MergeTreeDataPartWriterWide::writeColumn` and `MergeTreeDataPartWriterCompact::writeDataBlock` write a block granule by granule with no cancellation point. The INSERT pipeline only enforces query limits between blocks, so once execution is inside `writeTempPart` -> writer -> column serialization, a cancelled, KILLed or timed-out query keeps serializing the whole block. With a large block of wide/Dynamic/Variant columns this runs for minutes; it is the dominant uninterruptible location behind the chronic `Stress test` "Hung check failed, possible deadlock found" (the server-side AST fuzzer feeds boundary-sized blocks, hung in `writeSingleGranule` serialization). Add `MergeTreeDataPartWriterOnDisk::checkWriteCancellation`, called per granule in both writers. To keep it cheap on this hot path (every column of every INSERT and merge): the query status is fetched once and cached (null outside a query, e.g. background merges, so the check is a no-op there), and `checkTimeLimit` is only called every 65536 rows, so the frequency is decoupled from `index_granularity` and never degenerates to a per-row check. INSERT throughput of `numbers(100000000)` is unchanged within noise. Related: #108212 Related: #108351 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [ed5e3ed] Summary: ✅
AI ReviewSummaryThis PR adds cancellation polling across several long-running writer phases in Findings❌ Blockers
Final VerdictRequest changes. LLVM Coverage ReportMeasured on commit ed5e3ed.
Changed lines: Changed C/C++ lines covered: 163/178 (91.57%) · Uncovered code |
|
Confirmed, and the two are complementary rather than overlapping. #108212 attaches a cancel callback to the fuzzer's In-flight half of #107941 as I read the set:
On your "single pathologically large granule is still not interruptible mid-granule" caveat: in the fuzzer path #108212 caps the read at Together these close the in-flight-hang half of #107941. Makes sense to track #108357 / #108351 / #108353 under #107941 as the in-flight-cancellation fixes alongside #108212. |
Michicosun
left a comment
There was a problem hiding this comment.
Can we instead inject this check into WriteBuffer::next?
The regression test could pass even with the writer-side check removed, and was
flaky on sanitizer builds. Both problems came from cancelling at the wrong phase:
- It cancelled `INSERT INTO ... SELECT randomString(64) FROM numbers(...)` after a
fixed 2s wait, which only proves the query ran for 2s, not that it reached
`MergeTreeDataPartWriterWide::writeColumn`. On slow builds the query could still
be generating the single `randomString` block, an uninterruptible phase, so
`KILL QUERY ... SYNC` blocked until generation finished and tripped the tight
`timeout 5` -- the source of the `KILL QUERY SYNC did not return in time` flake
on `amd_tsan` / `amd_asan_ubsan`.
Rework so the cancel is observed inside a single large `writeColumn`:
- Pre-materialize the high-entropy strings into a plain (fast-to-read) source
table, so the measured `INSERT ... SELECT` spends its time in `ZSTD(22)` column
serialization, not in `randomString` generation.
- Force the whole input into one insert block via `min_insert_block_size_rows`, so
the writer loops over many granules inside one `writeColumn` call -- the only
place the new per-granule check can interrupt (a small block is already
cancellable between blocks).
- Use a deterministic phase signal: wait until `read_rows == ROWS` (source fully
read and squashed, i.e. execution is inside that one big `writeColumn`) before
sending the `KILL`.
- Add `no-random-settings`: the test needs the read/time/memory limits at their
unlimited defaults (a random `max_rows_to_read` / `max_memory_usage` would abort
the INSERT early, and a random `max_execution_time` would terminate it instead of
our `KILL`).
Verified on a local Debug build: with the fix `KILL QUERY ... SYNC` returns in
~0.2s with `QUERY_WAS_CANCELLED` ("killed promptly"); with the writer-side check
removed the same `KILL` blocks on the full-block write and the test prints
"KILL QUERY SYNC did not return in time", so the test now genuinely guards the fix.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108357&sha=88213d47a006f86119aa4c0b81b0423afec399fe&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Michicosun |
The previous revision forced the destination to a Wide part (`min_bytes_for_wide_part = 0`, `min_rows_for_wide_part = 0`), so it only exercised `MergeTreeDataPartWriterWide::writeColumn`. The PR also adds the cancellation check to `MergeTreeDataPartWriterCompact::writeDataBlock`, and that path had no regression coverage -- the test would still pass if the compact-side call were removed. Parameterize the scenario into a `run_case` helper and run it against both a forced-Wide and a forced-Compact destination (the Compact case sets both `min_*_for_wide_part` thresholds above the part size). Each case independently requires `KILL QUERY ... SYNC` to be observed from its writer loop. Verified on a local Debug build: with the fix both cases print "killed promptly" (KILL returns in ~0.2-0.4s; part_type confirmed Wide and Compact respectively); with the Compact `checkWriteCancellation` removed and rebuilt, the wide case still passes but the compact case prints "KILL QUERY SYNC did not return in time", so the test now guards both writer cancellation points.
No, it is not. Throwing there is completely normal; it is not a noexcept method. All code must accept the fact that it can throw. |
Per reviewer feedback (Michicosun), replace the QueryStatus::checkTimeLimit() call in checkWriteCancellation with a direct check of the query's is_killed flag. CancellationChecker sets is_killed both on an explicit KILL QUERY and on a 'throw'-mode max_execution_time timeout, so this single flag covers cancellation and throw-mode timeouts. In 'break' mode the flag stays unset, so the writer finishes the current block and yields the graceful partial INSERT that mode promises.
|
@alexey-milovidov this Stress test (arm_release) failure is a pre-existing trunk bug in the The server-side AST fuzzer mutated a QBit query (origin SELECT id, round(L2DistanceTransposed(vec, _CAST([1.,1.,1.,1.], 'Dynamic(max_types=18)'), 4), 1) AS dist
FROM qbit_param_test ORDER BY id ASC NULLS LASTThe reference vector is Not PR-caused: the same Fix: #105387 (open). Its current HEAD already covers this. The guard now skips the optimization when the reference vector is |
The writer-side cancellation check threw `QUERY_WAS_CANCELLED` for every `is_killed` state. A throw-mode `max_execution_time` also reaches that state (via `CancellationChecker::cancelQuery(CancelReason::TIMEOUT)`), so an `INSERT` that timed out while inside `writeColumn` / `writeDataBlock` was reported as a user cancellation instead of `TIMEOUT_EXCEEDED`, and clients could no longer distinguish a timeout from an explicit `KILL`. Use `QueryStatus::throwIfKilled`, which preserves the recorded cancel reason (`TIMEOUT_EXCEEDED` for a throw-mode `max_execution_time`, `QUERY_WAS_CANCELLED` for a kill). Extend `04411_column_write_cancellation` with a throw-mode `max_execution_time` case that expires inside the column write loop and asserts it is reported as `TIMEOUT_EXCEEDED`. Addresses the AI review on PR #108357. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed The writer-side check now calls The two red checks on the previous commit are unrelated to this change (writer-only, INSERT column data write):
|
A TIMEOUT_EXCEEDED alone does not prove the writer-side throwIfKilled branch ran: on a slow build the 8s deadline can expire while the source is still being read, and the case would pass without exercising the write loop at all. Mirror the KILL cases and report a failure when read_rows never reaches the source size, with a query_log re-check to avoid misjudging a query that exited between polls. Addresses the review comment from 2026-07-06 on #108357
The amd_tsan flaky check hangs on the timeout case: the processlist dump shows the INSERT at elapsed 750s with is_cancelled = 0 and the server log contains no TIMEOUT cancellation at all, so the 8-second max_execution_time was never enforced. CancellationChecker's worker sleeps toward the earliest deadline computed at wait entry; appending a task with an earlier deadline notifies the condition variable, but the wake-up predicate is false and the wait resumes toward the stale deadline, so a deadline can be missed entirely under parallel load. The untracked INSERT then grinds through the whole ZSTD(22) block and trips the 600s harness timeout with 'Processes left in process group'. Bound the wait: give the deadline 60 seconds after the write phase starts, then KILL the query and fail with a diagnostic line, so the test always terminates and reports what actually went wrong. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108357 PR: #108357
… block `MergeTreeDataPartWriterCompact::write` routes a block through `ColumnsBuffer::add` whenever the buffer already holds a partial granule, and that path appended every column with a single unbounded `insertRangeFrom`, so a huge block buffered behind a small one could keep `KILL QUERY` / throw-mode `max_execution_time` waiting for the whole copy. `add` now takes the writer's cancellation check and appends in chunks of `IColumn::CANCELLATION_CHECK_PERIOD_ROWS`, polling before each chunk. The accumulated column's dynamic structure is fixed by `fixDynamicStructure` before the append, so chunked insertion yields the same column as a single call. Verified with `clickhouse local`: `Dynamic` and `JSON` columns merged into Compact parts through 997-row and 20000-row blocks (`OPTIMIZE ... FINAL` with `merge_max_block_size`) hash identically to the `Memory` source. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…z3_codec` Master replaced the generic `allow_experimental_codecs` gate with the per-codec `enable_sz3_codec` setting, so the `CREATE TABLE ... CODEC(SZ3)` in this test failed with `BAD_ARGUMENTS` after merging master. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Status update (2026-09-16):
All four reds of the previous run were infrastructure, not this PR: both `Bugfix validation (functional tests)` jobs died with `Could not find master builds in S3` (and `Finish Workflow` is their collateral), and `Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6)` failed with `Container memory budget exceeded (/docker)`. The fresh run on the merged branch should clear them. |
| /// column, and matching the dynamic structure of a block re-inserts the whole column. Poll | ||
| /// cancellation per column here and hand the same check to the statistics calculation, so a | ||
| /// `KILL QUERY` that arrives while the writer is still preparing the first block is observed. | ||
| auto check_cancellation = [this] { checkWriteCancellation(); }; |
There was a problem hiding this comment.
prepareBlockForWriting is now interruptible, but the ordinary sorted-INSERT path still has an unbounded writer-side window immediately afterwards. MergeTreeDataWriter::writeTempPartImpl passes a permutation for unsorted ORDER BY tables (MergeTreeDataWriter.cpp:1111-1112), and then the writers apply it before the next checkWriteCancellation(): Compact runs permuteBlockIfNeeded(result_block, permutation, nullptr) and Wide permutes PK / skip-index / data columns via getIndexBlockAndPermute / column->permute(*permutation, 0) (IMergeTreeDataPartWriter.cpp:22-45, MergeTreeDataPartWriterWide.cpp:407-445).
Those permute() calls are full-column copies for the heavy types this PR is targeting (ColumnString::indexImpl, ColumnObject::permute, ColumnVariant::permute) and they do not poll cancellation themselves. So a KILL QUERY that arrives after the source is fully read can still sit in the writer for a long time on a normal keyed MergeTree, and the new regressions miss it because they all use ORDER BY tuple() (no permutation). Please make the writer-side permutation stage interruptible too, and add a keyed-table cancellation test that reaches this path.
…uilds
`04827_sz3_dimension_scan_cancellation` failed three of five runs in the tsan flaky check with
`KILL QUERY SYNC did not return in time`. The cancellation point is not at fault: `KILL ... SYNC`
returns when the query is gone, so the bound also covers tearing down the squashed block, which at
4M rows peaks near 2 GiB. Measured from the failing job's own log, the five runs took 13.4, 13.7,
14.6, 15.9 and 16.8 seconds against a 15 second bound - the outcome was decided by which side of the
bound the teardown landed on.
Shrink the block to 1M rows on a sanitizer or debug build rather than widening the bound. The scan
this test is about is proportional to the row count as well, so both sides of the assertion shrink
together and the bound stays a real one. Measured on this branch's tsan build:
with the fix: kill returns in 1.9s, test runs in 22-25s (was ~108s), 4 of 4 runs pass
without the fix: the kill must wait out the whole write, which takes 35.2s at 1M rows
so the 15 second bound still separates the two by more than a factor of two in each direction.
Release builds keep 4M rows and are unaffected.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…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]>
Problem
A cancelled or
KILLedINSERTcan keep writing a data part for a long time while serializing column data — for example a large block of wide /Dynamic/Variantcolumns. The query stays insystem.processeswithis_cancelled = 1and does not stop until the whole block is written. This is the dominant uninterruptible location behind the chronicStress test"Hung check failed, possible deadlock found" (issue #107941): the server-side AST fuzzer feeds boundary-sized blocks and the hung query sits inMergeTreeDataPartWriterWide::writeSingleGranule→ serialization.Root cause
MergeTreeDataPartWriterWide::writeColumnandMergeTreeDataPartWriterCompact::writeDataBlockwrite a block granule by granule with no cancellation point. The INSERT pipeline only enforces query limits between blocks, so once execution is insideMergeTreeDataWriter::writeTempPart→ writer → column serialization, neither cancellation normax_execution_timeis observed until the whole block's columns are written.Fix
Add
MergeTreeDataPartWriterOnDisk::checkWriteCancellation(shared base of both writers) and call it per granule in both column-write loops. Because this is the hottest, most universal writer path (every column of every INSERT and merge), it is kept cheap:checkTimeLimitis called only every 65536 rows, so the check frequency is decoupled fromindex_granularityand never degenerates to a per-row check at small granularity.checkTimeLimithonors both cancellation andmax_execution_time(throw mode). A single pathologically large granule of a slow-serializing column is still not interruptible mid-granule, but the multi-minute hangs are many-granule, so per-granule is sufficient.Performance is unchanged within noise —
INSERT INTO t SELECT number FROM numbers(100000000), 3 runs: before 1.802 / 1.908 / 2.046 s, after 1.747 / 1.872 / 1.943 s.Regression test
04411_column_write_cancellation.sh: a single large block of high-entropy strings withCODEC(ZSTD(22))(so column serialization is the active multi-second phase, on a forcedWidepart with no skip index) is cancelled mid-write; the test requiresKILL QUERY ... SYNCto return within atimeoutbound and the backgroundINSERTto fail withQUERY_WAS_CANCELLED.Relationship to the hung-check umbrella
@groeneai — this is complementary to your #108212. Your fuzzer-executor cancel callback enables cancellation between tasks but (as your analysis notes) cannot interrupt a single in-flight
generate/part-write; this PR makes the column-write part of that in-flight work interruptible at granule granularity, which also helps real (non-fuzzer) largeINSERTs respond toKILL/ timeout. Siblings: #108351 (skip-index build) and #108353 (theprimessource, which was the actual hung query in #108212's own arm_tsan run).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a cancelled or
KILLedINSERTcontinuing to write a data part for a long time while serializing column data (for example a large block of wide orDynamiccolumns). The write now stops promptly when the query is cancelled or itsmax_execution_timeis exceeded.Workflow [PR]
Sync PR [sync-upstream/pr/108357]