Repository navigation
Honour query cancellation inside one IRowInputFormat::read block - #112646
PedroTadim merged 3 commits into
Conversation
Internal second-model review (14 Gate B rounds, 13 fix rounds; final round: 0 blockers, 0 majors agreed)Before opening this PR I ran an internal review pipeline: an independent cold review of the resulting Totals over the whole PR: 14 gate rounds, 40 gate findings (3 blocker, 31 major, 6 nit) plus 79 from Final round (
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260730-164200 |
|
cc @tavplubix @jkartseva, could you review this? A background async-insert flush ignored KILL QUERY and max_execution_time for minutes because StreamingFormatExecutor checks cancellation only between chunks and the flush's format is built with max_insert_block_size, so one IRowInputFormat::read call parses about a million rows with no interruption point; the row loops now poll the QueryStatus every 8192 rows. |
|
Workflow [PR], commit [c040da8] Summary: ❌
AI ReviewSummaryThis PR fixes the original async-insert failure mode by adding query-cancellation checkpoints inside the long row loops in Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
A background async-insert flush kept running for 623 seconds after being killed, failing the stress hung check. `StreamingFormatExecutor::execute` checked for cancellation only between chunks, and one chunk is one `IRowInputFormat::read` call. The flush's format is built with `max_insert_block_size` (default 1048449), not the query's `max_block_size`, so a single `read` consumes about a million rows with no interruption point; `max_execution_time = 60` was ignored just as long. `IRowInputFormat::read` now calls `CurrentThread::checkIfNotCancelled` every 8192 rows. That helper asks the `QueryStatus`, so it reports the query's own cancellation code and needs no new API or state: the flush already runs inside a `ThreadGroup` that installs the predicate. `Values` is not an `IRowInputFormat`, so its own row loop is patched too. Deliberately not `IProcessor::isCancelled`: `ISource::cancel` raises that flag ignoring the `CancelReason`, so a valid `PartialResult` early stop could not be told apart from a kill. Because a format can now abort mid-block, the executor also rethrows anything raised while the cancellation callback reports cancelled, instead of routing it to `on_error`, where an async insert would record it as a per-entry parsing failure and carry on. A cancelled query reports an arbitrary exception, so the error code alone is not sufficient. It is also not necessary: no error code is read as cancellation by itself, because the five streaming-engine callers (KafkaSource, StorageKafka2, FileLogSource, NATSSource, RabbitMQSource) build the executor without a cancellation callback and for them `on_error` is what implements *_handle_error_mode = 'stream' and the dead letter queue. In particular TIMEOUT_EXCEEDED is not treated as cancellation on the strength of its code: `QueryStatus::checkTimeLimit` falls through to `ExecutionSpeedLimits::checkTimeLimit`, which throws it directly under the default timeout_overflow_mode = throw while the query is alive, and `ValuesBlockInputFormat::parseExpression` evaluates arbitrary constant expressions that reach exactly that. Callers that pass no callback therefore keep exactly the previous classification. Tests: 04652_async_insert_flush_cancellation_inside_block gives a flush its own deadline while it parses one block, covering both row loops, and reads the verdict off the flush's own `system.query_log` row because the initiating INSERT carries the same deadline and reports an identical message when it times out first. Unit tests pin the checkpoint period and row-zero guard for both loops, and the executor's classification per code path, including that a timeout seen without a cancellation callback still reaches `on_error`.
cdda23a to
9ed6794
Compare
| /// checkpoint. It is bounded by the same `max_block_size_rows`, and the expression fallback | ||
| /// in `readRow` makes a single block expensive enough to outlive a `KILL QUERY` by minutes. | ||
| /// See the comment on `CANCELLATION_CHECK_PERIOD_ROWS` for why `QueryStatus` is asked here. | ||
| if (rows_in_block != 0 && rows_in_block % CANCELLATION_CHECK_PERIOD_ROWS == 0) |
There was a problem hiding this comment.
Values is still uninterruptible for the common templated-expression path. The new poll only runs in the row loop, but once tryParseExpressionUsingTemplate switches a column to BatchTemplate, read() flushes the accumulated rows through ConstantExpressionTemplate::evaluateAll() either at EOF (ValuesBlockInputFormat.cpp:167-181) or on the first shape mismatch (ValuesBlockInputFormat.cpp:297-304). evaluateAll() then calls actions_on_literals->execute(evaluated) without the check_cancelled callback that ExpressionActions already supports (ConstantExpressionTemplate.cpp:753-760), so a killed or timed-out async flush still sits inside one read() until the whole templated batch finishes. That leaves repeated-shape INSERT ... VALUES (...) with the same block-sized cancellation latency this PR is trying to remove.
There was a problem hiding this comment.
Confirmed on all four coordinates: the checkpoint I added to ValuesBlockInputFormat is row-loop only (:125-133), ConstantExpressionTemplate.cpp:759 calls the one-argument execute, so check_cancelled defaults to nullptr (ExpressionActions.h:114), and evaluateAll has exactly four callers, all of them the two flush sites you name. So the seam is real and I have filed it. Two corrections before it is fixed, though.
The callback cannot be passed as suggested. ExpressionActions::execute does not throw when it fires; it substitutes an empty block and returns (ExpressionActions.cpp:846-852). evaluateAll then asserts the row count on the next statement (ConstantExpressionTemplate.cpp:761-763), and the flush is only entered when rowsCount() is non-zero (ValuesBlockInputFormat.cpp:170), so rows_count is always positive. Wiring the callback there converts a cancelled templated flush into LOGICAL_ERROR: Number of rows mismatch after evaluation of batch of constant expressions, which aborts debug and sanitizer builds. ExpressionTransform and ConvertingTransform get away with it because an empty output is a valid result for a transform discarding a chunk of an already cancelled pipeline; evaluateAll has a hard row-count contract. The right channel is a throwing checkpoint, CurrentThread::checkIfNotCancelled, which is what both row loops in this PR already use.
I also do not think this is a blocker for the case the PR fixes. evaluateAll builds one literals block (:755) and runs the action DAG of a single templated expression once (:759, built at :445), so the flush is a few vectorized actions over the batch, not rows_count iterations of parsing. The expensive path is the row loop, with its per-row tokenizing and expression fallback, and that is the one now instrumented. That asymmetry is why the Values case in 04652 varies expression structure on purpose: a uniform payload is served by the template cache and is not slow enough to outlive the deadline at that size. I tried to quantify the templated flush on both a debug and an official release binary and got no usable number on a loaded machine, so I am not asserting a latency figure in either direction, and the blocker grading rests on that unmeasured magnitude.
Deferring it rather than folding it in: this PR is one commit, mergeable, with a nearly complete CI run, its only red being a Bugfix validation (unit tests) infrastructure error (submodule state differs between merge-base and checkout, while Unit tests (asan_ubsan/tsan/msan) pass 19509, 19508 and 19505 with zero failures, and my diff touches no contrib path and no gitlink). A correct fix here also needs a repeated-shape fixture that actually reaches BatchTemplate, since the existing payload would leave the new checkpoint untested, so it is a separable carrier in the same sense as the count-only and JSONColumnsBlockInputFormatBase loops that were already split out of this change.
There was a problem hiding this comment.
Follow-up on the deferred item, since I said above that I had filed it: I measured the magnitude and I am not going to fix it. The seam is exactly as described, but it does not cause the latency it looked like it caused.
Measured on release 26.8.1.477 (build id b094879bcb7d3428aa529a742ed6b459d9374bde), one max_block_size batch of 65409 rows, max_execution_time=1, with the templated path confirmed live by the LOG_TEST at ValuesBlockInputFormat.cpp:561 (67 template adoptions with input_format_values_deduce_templates_of_expressions=1, 0 with it disabled):
| arm | reaches evaluateAll |
elapsed vs 1000 ms |
|---|---|---|
INSERT ... VALUES (arraySum(arrayMap(y -> y * N, range(20000)))) |
yes | 13708 ms |
SELECT count(arraySum(arrayMap(y -> y * number, range(20000)))) |
no | 13565 ms |
INSERT ... SELECT of the same expression |
no | 14020 ms |
Two arms that never build a ConstantExpressionTemplate overshoot the same deadline by the same amount. The overrun is not the missing checkpoint; it is that one vectorized action over a 65k-row block runs to completion. ExpressionActions::execute polls check_cancelled only between actions (ExpressionActions.cpp:833-853, poll at :846), never inside one, so neither the callback nor a check before execute can bound this. Block-size sweep at fixed per-row cost, same deadline: 1000 rows no timeout, 8192 rows 1647 ms, 65409 rows 14369 ms.
A positive control confirms the probe discriminates: SELECT count() FROM numbers_mt(1e11) with the same setting stops at 1000.204 ms.
This also confirms the grading point from my earlier reply quantitatively: 200000 rows of a uniform cheap templated expression complete in 0.32 s in total, because the flush is one vectorized evaluation rather than per-row work.
So the residual is real but its only consequence is that a cancellation surfaces after one batch of the fast path instead of during it. I am closing it rather than adding a checkpoint that cannot bound the latency.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 245/245 (100.00%) · Uncovered code |
CI finish ledger - 9ed6794Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260731-155315 |
| #include <gtest/gtest.h> | ||
|
|
||
| #include <Columns/ColumnsNumber.h> | ||
| #include <Core/Block.h> |
There was a problem hiding this comment.
Done in ec2f9fc: both gtest files are gone, -752/+36. They were 616 of the 892 added lines for a 29-line fix, so this is a good trade.
I checked that 04652 still catches the bug on its own before deleting them. With both row-loop checkpoints reverted it fails 5/5, and the diff is the designed one for both loops:
TSV
-in-loop-timeout
+between-chunks
Values
-in-loop-timeout
+between-chunks
On the shipping binary it is 10/10 OK. The oracle is the flush's own system.query_log.exception_code, and TIMEOUT_EXCEEDED can only get there if the executor rethrew it instead of routing it to on_error, so the StreamingFormatExecutor change is covered by the same assertion.
One thing the gtests pinned and 04652 does not, so you have it rather than finding it later: the value of CANCELLATION_CHECK_PERIOD_ROWS. I measured both cases rather than guessing. Building with the period doubled to 16384 passes 5/5, and removing the two rows != 0 row-zero guards also passes 5/5. Neither is a correctness property: the first changes how promptly cancellation is noticed inside one block, the second adds one redundant predicate call per read. If the checkpoint stops running at all, 04652 fails. I did not add SQL cases for them.
Also in this push, since it is the same file: the comment blocks are down to at most three lines per block, and the ignore_drop_queries_probability = 0 pins are dropped per @alexey-milovidov's ask on #112005. I corrected one sentence in the description that credited a unit test for the streaming-caller classification.
The two gtest files were 616 of the 892 added lines for a 29-line fix. The stateless test 04652 already discriminates both row loops end to end, so they are removable without losing coverage of the reported failure: with both row-loop checkpoints reverted it fails 5/5 with `in-loop-timeout` -> `between-chunks` on the `TSV` and the `Values` case alike. The only invariant that lived in the gtests alone is the equality assertion on the value of `CANCELLATION_CHECK_PERIOD_ROWS`. It is a latency-tuning constant, not a correctness property: a wrong value changes how promptly cancellation is observed inside one block, and the stateless test still fails if the checkpoint stops running at all. Also trims the comment blocks on the remaining diff to the convention of at most three lines per block, and drops the `ignore_drop_queries_probability = 0` pins from the stateless test. The pins are unnecessary: the only injectors are the stress runner and the upgrade check's `--fake-drop` client, neither of which compares per-test results, and the runner's own leftover-tables check never fires because it compares an absolute path against `02800`.
…y_log row 04652 read the flush's verdict from its own `system.query_log` row and treated an empty result as final. That made it flaky: 3 of 200 flaky-check runs on the previous head printed an empty label for the `TSV` case, on `amd_msan` and `amd_asan_ubsan` only. `AsynchronousInsertQueue::processData` arms the flush's deadline in `getProcessList().insert(...)`, which reaches `CancellationChecker::appendTask` in `ProcessList::insert`, before it constructs the interpreter and calls `logQueryStart`. A deadline that fires in that window is logged by `logExceptionBeforeStart`, which by design does not compute the access info the oracle narrows on, so no matching row exists at all. The window is short, which is why the rate was 3 in 200, and it is widest on a sanitizer build, whose interpreter construction is slowest. The failing run was faster than every passing run in the same job, 31.34 s against 34.48 to 40.07 s, and its trace shows one attempt only: the label was empty, the retry condition short-circuited, and the run printed a blank line. An absent row is a lost sample rather than an outcome, so retry it alongside the two labels that were already retried, and name the exhausted-retries case instead of printing a blank line, which is indistinguishable from truncated stdout. This does not weaken the test. With both row-loop checkpoints reverted the fixed test still fails 5 of 5 with `in-loop-timeout` -> `between-chunks`, because an unfixed build produces a verdict row on every attempt rather than no row. Verified by reproducing the failure deterministically: firing the flush's deadline between the process-list insert and `logQueryStart` for the first attempt's table makes the previous test fail 5 of 5 with the byte-identical CI diff, while this one passes 5 of 5. The mechanism was confirmed separately, with a positive control on the same binary: a flush cancelled in that window leaves 0 `AsyncInsertFlush` rows, against 2 for an unimpeded one. On the shipping binary the test passes 50 of 50 with randomization enabled and 50 of 50 under the flaky check's own shape, `--test-runs 50 --jobs 11` across 11 concurrent workers, and the two sibling async-insert flush tests pass 5 of 5 each.
CI finish ledger - c040da8CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
None is PR-caused, and the first row is the one that needed measuring rather than assuming: this PR
The other two rows are likewise outside this diff, which only adds cancellation checkpoints to Session id: cron:our-pr-ci-monitor:20260808-060000 |
fd2595c
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
KILL QUERYandmax_execution_timebeing ignored for minutes while a row-based input format was parsing one block. Row-based input formats now check for query cancellation every 8192 rows, so a killed insert (in particular a background async-insert flush, which parses up tomax_insert_block_sizerows per block) stops promptly instead of running to the end of the block.Description
A background async-insert flush kept running for 623 seconds after being killed, failing the stress
hung check.
StreamingFormatExecutor::executechecks for cancellation only between chunks, and onechunk is one
IRowInputFormat::readcall. The flush's format is built withmax_insert_block_size(default
1048449), not the query'smax_block_size, so a singlereadconsumes about a million rowswith no interruption point.
max_execution_time = 60was ignored just as long.IRowInputFormat::readnow callsCurrentThread::checkIfNotCancelledevery 8192 rows. That helper asksthe
QueryStatus, so it reports the query's own cancellation code and needs no new API or state: theflush already runs inside a
ThreadGroupinstalling the predicate.Valuesis not anIRowInputFormat, so its own row loop is patched too. NotIProcessor::isCancelled:ISource::cancelsets that flag ignoring the
CancelReason, so a validPartialResultstop could not be told apartfrom a kill.
Because a format can now abort mid-block,
StreamingFormatExecutor::executealso rethrows anythingraised while the cancellation callback reports cancelled, instead of routing it to
on_error, where anasync insert would record it as a parsing failure and carry on: a cancelled query reports an arbitrary
exception. No error code is read as cancellation by itself, so a caller that installs no callback keeps
exactly the previous classification.
Verification:
04652_async_insert_flush_cancellation_inside_blockgives a flush its ownmax_execution_timedeadline while it parses one block, covering both row loops (aJSONcolumn viaTSV, and
Values). It reads the verdict off the flush's ownsystem.query_logrow, because theinitiating
INSERTcarries the same deadline and reports an identical message when it times out first.Patched, the deadline surfaces from inside the loop; on unpatched master the loop parses everything
first and it is only seen between chunks.
04547_async_insert_flush_cancellationstays green, both50/50 with randomised settings.
Streaming callers, overhead, and out-of-scope loops
The five streaming-engine callers (Kafka, Kafka2, FileLog, NATS, RabbitMQ) build the executor without a
cancellation callback, and for them
on_erroris what implements*_handle_error_mode = 'stream'andthe dead letter queue. Their classification is deliberately unchanged:
TIMEOUT_EXCEEDEDis not treatedas cancellation on the strength of its code, because a single message can raise it while the query is
alive (
QueryStatus::checkTimeLimitfalls through toExecutionSpeedLimits::checkTimeLimit, whichthrows it directly under the default
timeout_overflow_mode = throw, andValuesBlockInputFormat::parseExpressionevaluates arbitrary constant expressions). Without a callbackthe classification is byte-identical to the current one, so
on_errorkeeps handling such a message.Left alone: the
breakoverflow mode (it asks the pipeline to stop at a block boundary rather thancancelling, so reporting it mid-parse would silently truncate an insert), the count-only
needOnlyCountfast path (reached only fromfile/url/object-storage reads, never from an insert,and every format has its own
countRowsloop), andJSONColumnsBlockInputFormatBase::read(acolumn-at-a-time loop that ignores
max_block_size).Overhead: one predicate call per 8192 rows within a block, none in a shorter block. Single-threaded row
loop, parallel parsing disabled, binaries interleaved:
max_block_size = 8191(highest checks-to-rows ratio)max_block_size = 1The
max_block_size = 1arm sits inside the 9.59-9.98 s spread of the repeated runs themselves.Worst-case cancellation latency becomes one 8192-row batch instead of the whole block.
No related open issue.
Version info
26.8.1.1004(included in26.8and later)