Skip to content

Honour query cancellation inside one IRowInputFormat::read block - #112646

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-flush-cancellation-json-parse
Aug 8, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-flush-cancellation-json-parse

Conversation

@groeneai

@groeneai groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixes KILL QUERY and max_execution_time being 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 to max_insert_block_size rows 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::execute checks 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 installing the predicate. Values is not an
IRowInputFormat, so its own row loop is patched too. Not IProcessor::isCancelled: ISource::cancel
sets that flag ignoring the CancelReason, so a valid PartialResult stop could not be told apart
from a kill.

Because a format can now abort mid-block, StreamingFormatExecutor::execute 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 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_block gives a flush its own
max_execution_time deadline while it parses one block, covering both row loops (a JSON column via
TSV, and Values). It 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.
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_cancellation stays green, both
50/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_error is what implements *_handle_error_mode = 'stream' and
the dead letter queue. Their classification is deliberately unchanged: TIMEOUT_EXCEEDED is not treated
as cancellation on the strength of its code, because a single message can raise it while the query is
alive (QueryStatus::checkTimeLimit falls through to ExecutionSpeedLimits::checkTimeLimit, which
throws it directly under the default timeout_overflow_mode = throw, and
ValuesBlockInputFormat::parseExpression evaluates arbitrary constant expressions). Without a callback
the classification is byte-identical to the current one, so on_error keeps handling such a message.

Left alone: the break overflow mode (it asks the pipeline to stop at a block boundary rather than
cancelling, so reporting it mid-parse would silently truncate an insert), the count-only
needOnlyCount fast path (reached only from file/url/object-storage reads, never from an insert,
and every format has its own countRows loop), and JSONColumnsBlockInputFormatBase::read (a
column-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:

workload patched unpatched
10M-row TSV, default block size 0.709-0.759 s 0.705-0.723 s
2M-row TSV, max_block_size = 8191 (highest checks-to-rows ratio) 0.074 s median 0.074 s median
2M-row TSV, max_block_size = 1 9.72 s median 9.69 s median

The max_block_size = 1 arm 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

  • Merged into: 26.8.1.1004 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
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
code, a second-model adversarial gate, and adjudication of every finding against the source. Findings
are reported below with the verdict I reached and the evidence for it. Nothing here needs action from
a reviewer; it is disclosure of what was checked and what remains.

Totals over the whole PR: 14 gate rounds, 40 gate findings (3 blocker, 31 major, 6 nit) plus 79 from
my own 15 cold reviews; 52 agreed and fixed across 13 fix rounds, 27 disagreed with evidence, 21
dropped. The final round is clean.

Final round (cdda23a)

⚠️ cancel-catch-matrix (major, 3rd raise) - DISAGREE. The claim is that a non-DB::Exception
failure coinciding with cancellation still reaches on_error, so an async flush would record a
parsing failure and carry on. I refute two necessary steps.

First, the cancellation exception is never a non-DB exception, so the code this PR adds has zero
exposure to the sibling catches. QueryStatus::throwQueryWasCancelled rethrows
cancellation_exception if set, else throws QUERY_WAS_CANCELLED. cancellation_exception is
written only by the two-argument cancelQuery, whose only two callers tree-wide are in
BackupCoordinationStageSync, both constructing a DB::Exception; and a backup QueryStatus can
never drive a format read (grep of src/Backups/ for StreamingFormatExecutor,
getInputFormat, IRowInputFormat returns nothing). So the new checkIfNotCancelled checkpoint can
only ever raise a DB::Exception, which lands in the branch this PR already guards.

Second, what remains is an unrelated non-DB throw coinciding with a cancellation. That asymmetry is
byte-identical on the merge base, is not in this diff, and its consequence is bounded to one entry: as
soon as on_error returns, the next entry re-enters execute, whose first action is the pre-chunk
cancellation check; and if it was the last entry, PipelineExecutor::execute calls checkTimeLimit
on its first line and throws. The flush cannot report success and continue. Widening both sibling
catches would reclassify genuine non-DB parse failures, which is the on_error contract this PR
deliberately preserves, so I left it as a bounded pre-existing residual rather than folding an
unrelated change in.

⚠️ deadline-phase-timing (major, 4th raise) - DISAGREE, closed by the measurement it asked for.
The concern: the test's 500 ms deadline is armed at process-list registration while the format is
built later, so on a slow build setup could consume the budget and a correct build would report the
same label as an unfixed one. Agreed on the first three raises and addressed each time; this raise
asked for repeated runs on the slowest configurations. Measured as an upper bound (a one-row payload
makes parse cost negligible, so the flush's own query_duration_ms bounds registration to first
check): worst setup share is 1 ms of 500 ms on idle debug, 3 ms at load average 77, 1 ms on an
official release build - 0.6 % of the budget at worst. Falsification test: sweeping the deadline down
to 5 ms under load average 49-77 still gives in-loop-timeout in 8 of 8 runs at every value and
between-chunks in 0, so the label does not flip even at a deadline 100 times smaller than shipped.
Label distribution on the loaded arm (50 runs plus 30 concurrent copies): 269 in-loop-timeout, 1
cancelled-elsewhere, 0 between-chunks, 0 failures, one attempt used in 269 cases.

💡 Three nits from my own cold review, all already disclosed in the description rather than fixed: the
widened rethrow's TIMEOUT_EXCEEDED arm is load-bearing only for the five streaming-engine callers
(it is redundant on the async path, where the callback already reports cancelled) and its outcome
there is strictly safer; the count-only needOnlyCount fast path is uncovered but has no caller on
any insert path; and of the 13 direct IInputFormat subclasses only Values has a per-row loop
bounded by max_block_size_rows, which is why it is the only sibling patched.

What earlier rounds changed

The three blockers were all real and fixed: the count-only bypass and the break overflow mode were
resolved by scoping (both are now stated in the description with the reasoning), and a DROP in the
test was being silently skipped by the stress runner's ignore_drop_queries_probability injection.
The long-running majors that shaped the final shape of this PR were about the test proving the right
thing: the oracle moved from client stderr to the flush's own system.query_log row (because the
initiating INSERT carries the same deadline and reports an identical message), the failpoint and
KILL QUERY were replaced by the flush's own max_execution_time, table names became unique per
invocation as well as per case and attempt (a shared name let a previous invocation's row satisfy the
oracle vacuously), and the period constant's value - not merely its existence - is now pinned by an
equality assertion in each of the two row loops independently.

Verification carried into this round: the shipped test passes 50/50 including under load average 77
and 30 concurrent copies; removing both row-loop guards makes it fail with the retry provably
exhausted per carrier; and an independently built official release binary without this fix fails it
20/20 in exactly the designed diagnostic way.

Session id: cron:clickhouse-review-slot-49:20260730-174501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. One async insert of 1,000,000 JSON rows with many distinct paths ({"p<i mod 5000>": i, "b": "xxxx..."}, 56 MB) parses for about 26 s in ONE block; KILL QUERY the AsyncInsertFlush and poll system.processes. Unpatched: the row stays with is_cancelled = 1, read_rows = 0. Reproduces every run. A payload of a fixed 2-key shape does NOT work (1M such rows parse in ~1.0 s), and above async_insert_max_data_size the push falls back to a synchronous insert, so the trigger is per-row parse cost, not row count. Round r10 REPLACES the shell test's synchronisation: 04652 now gives the flush its own max_execution_time deadline instead of parking it on a failpoint and issuing KILL QUERY, so the repro is deterministic without any server-global state. Measured deterministic arms (parse-only, ENGINE = Null): 30000 JSON rows / 8.3 MB parse for ~1.2 s and 100000 varied-expression Values rows / 2.4 MB for ~2.3 s on debug, and 845-915 ms / 1559-1582 ms on an official release build, against a 0.5 s deadline, i.e. 1.7-3.2x headroom on the fastest flavour and 5x above the 100 ms grid CancellationChecker aligns deadlines to. Per-row parse COST is the lever, not payload size: a plain integer column parses 1M rows in 77 ms (about 0.08 ms/MB), whereas a JSON column reaches 291 ms/MB and the Values expression fallback 970 ms/MB, so the old size-only approach would have needed a ~90 MB payload.
b Root cause explained? YES. StreamingFormatExecutor::execute's cancellation check (StreamingFormatExecutor.cpp:111-112) runs once per returned Chunk; one Chunk is one IRowInputFormat::read() call (IRowInputFormat.cpp:128-233). The async-insert flush's format is built with max_insert_block_size / min_insert_block_size_rows (getSourceFromASTInsertQuery.cpp:66-71), both default 1048449 and neither randomised, so one read() consumes ~1M rows with no interruption point. KILL sets is_killed, the callback would return true, but control does not return to the executor for the rest of the block. In the reported run: kill at 12:37:48, control returned 575 s later, elapsed = 623.6 s, max_execution_time = 60 ignored throughout.
c Fix matches root cause? YES. The interruption point is added to the loops that lacked one: CurrentThread::checkIfNotCancelled every 8192 rows in the row loop of IRowInputFormat::read AND in the separate one in ValuesBlockInputFormat::read, plus the executor's catch now recognises that abort as cancellation instead of routing it to on_error as a parse error. No widened bound, no no-random-* tag, no reduced dataset, no defensive guard masking an upstream bug. Rejected alternatives: lowering the flush's block size (does not fix the invariant and regresses insert block sizing), calling format->cancel() from the executor (still only between chunks), threading cancellation into SerializationJSON (huge blast radius, JSON-only).
d Test intent preserved / new tests added? YES. New 04652_async_insert_flush_cancellation_inside_block covers the in-block case with one section per row loop (TSV and Values), driven by the flush's own max_execution_time and asserted on the error code the flush RECORDED (system.query_log, query_kind = 'AsyncInsertFlush') rather than on text scraped from the client: TIMEOUT_EXCEEDED when the deadline is seen inside the row loop versus QUERY_WAS_CANCELLED when it is only seen between chunks. That distinguishes the two builds without a timing margin, cannot be satisfied by the initiating INSERT (which carries the same deadline and reports an identical message), and reports a foreign KILL from Stress's random killer as a distinct third label instead of matching nothing. Round r11 removed the earlier in-loop PAUSEABLE failpoint together with its opt-in setting: once the test stopped arming it, what remained was a user-facing setting with no consumer. 04547_async_insert_flush_cancellation, which pins the complementary between-chunks case and asserts the executor's own message, is unchanged and green (50/50). 03365_json_rollback_bug, whose payload ends in a malformed row, is unchanged and green as the positive control that genuine parse errors still reach on_error. The non-KILL direction (max_execution_time) and the executor's classification of it are covered by a unit suite instead of a third shell section: StreamingFormatExecutorCancellation.* drives StreamingFormatExecutor::execute with a fake format, so each of the three arms of its cancellation test is pinned SEPARATELY, which a shell test cannot do because a killed query satisfies several arms at once. That section was removed in round r3 in favour of the unit suite (it also removed the test's dependence on a 3-second timeout landing while the flush was parked, and cut a single run from ~8 s to 4.7 s); the two shell sections that uniquely pin the row loops are untouched. Every DROP the test's reset depends on is pinned with statement-level SETTINGS ignore_drop_queries_probability = 0, because the Stress runner injects ignore_drop_queries_probability=0.2 into every client invocation and a skipped drop still reports success; forcing the injection to 1 the test is 50/50 OK, and removing one pin under the same forced value fails with Code: 57 TABLE_ALREADY_EXISTS. The failpoint the test drives is armed per query, and the test asserts that exclusivity directly: a concurrent ordinary INSERT completes while the test's own flush is parked, and as of round r4 that probe uses the section's OWN format, so each of the two arming gates is pinned in the negative direction rather than only the TSV one. Round r4 also adds RowInputFormatCancellation.*, which pins the row-loop checkpoint itself without a server, a failpoint or any global state, and does so without a server, a failpoint or any global state, which is what let round r6 hand the period pin entirely to that suite (OneCheckPerStridePeriod) and re-size the shell payload for a different purpose. Round r5 grows that suite to 5 cases, closing the two coverage gaps r4 left. ValuesShortBlockAsksNothing mirrors the existing short-block control onto the SECOND copy of the row-zero guard (ValuesBlockInputFormat.cpp:138); only IRowInputFormat.cpp:143 was pinned, and deleting the Values copy left the whole suite green because it only moves the abort earlier, which the two abort cases still accept. OneCheckPerStridePeriod pins the period by EQUALITY on a payload of exactly one period plus one row, so a NARROWED stride is caught too, which nothing previously did: at a halved period 04652 still parks and is still killed. The payload shrank only to make the assertion stricter; no bound was widened and no assertion weakened. Round r6 re-sizes the shell payload to 81921 rows for a DIFFERENT reason, now that the period pin lives in the unit suite: the pause channel is keyed by failpoint name only, so a concurrent copy of the test can release the parked flush early, and ten checkpoints instead of one make that cost one opportunity rather than the only one. The release itself became SYSTEM NOTIFY FAILPOINT, which wakes the waiters without erasing the channel a concurrent copy is parked on. Both changes were measured, not argued: with a premature release injected the test FAILS at 8193 rows and PASSES at 81921. Round r7 completes the two-loop symmetry and hardens the shell test against the one foreign-release mode the r6 widening could NOT absorb. On the unit side, OneCheckPerStridePeriod instantiated TabSeparatedRowInputFormat only, so it pinned the period of the checkpoint in IRowInputFormat.cpp and nothing else, while ValuesBlockInputFormat.cpp:138 carries an independent copy of the same modulo; the two existing Values cases cannot see its period (one asks for at least one check over four periods, the other for none below one), so the Values loop could have violated the 8192-row bound this PR publishes with every test green. ValuesOneCheckPerStridePeriod pins it by equality over the same 8193-row payload, and the two periods are now provably independent: mutating ONLY the Values condition to 16384 reddens the new case (predicate_calls 0 vs 1) while the TSV case stays green, mutating ONLY the TSV condition gives the mirror image, mutating only the Values condition to 4096 catches the NARROWING direction (2 vs 1) that nothing caught before, and mutating the shared constant reddens both. On the shell side, r6's NOTIFY release keeps the channel alive for a concurrent copy, but a concurrent copy's own cleanup trap issues SYSTEM DISABLE FAILPOINT, which ERASES the name-keyed channel - and then ten checkpoints help no more than one, because nothing can park on a channel that is gone. run_case now retries up to three times, re-issuing SYSTEM ENABLE FAILPOINT so a fresh channel exists again, and it retries ONLY the outcome a lost channel produces (nothing cancelled AND every row inserted), so a genuine regression is still reported from the first attempt and is never retried away. That last property is measured, not asserted: with one production hunk reverted the test still FAILS on its own loop's section only, in both directions. Round r10 removes the failpoint, the KILL QUERY and the no-parallel tag from 04652 entirely, together with the three concurrent-copy remedies they required (the notify-until-deregistered loop, the three-attempt retry and the foreign-insert probe). The two sections that uniquely pin the two row loops remain, now driven by the flush's OWN max_execution_time deadline: ProcessListBase::insert registers every async-insert flush with CancellationChecker from the settings it inherited, so the deadline is per-flush and no concurrent copy can observe or perturb it. The runner's real tag parser confirms the result carries NO tags (control 04547 still reports ['no-parallel']), and 30 concurrent copies at -j 12 under host load 61 with 78 other ClickHouse processes pass 30/30. Round r11 DELETES input_format_pause_inside_block and its opt-in setting entirely, reversing r10's decision to keep them: once r10 stopped arming the failpoint, what remained was a user-facing setting published in system.settings and in the generated docs, carrying a permanent SettingsChangesHistory entry for compatibility, whose own description said no test used it, plus a field on RowInputFormatParams (constructed for every input format) and a branch in both hot row loops. Everything deleted was introduced by this PR, so a future KILL-based test can reintroduce it in the PR that needs it, where its justification is reviewable. Round r11 also replaces the shell test's oracle: it no longer greps the client's stderr but reads the error code the FLUSH recorded in system.query_log, which is what makes the assertion attributable (see row e). Round r12 closes the two ways that oracle could still report the wrong build state, and changes only the test. First, each case is now retried up to three times, and ONLY over the two labels that are transient rather than a verdict: cancelled-elsewhere (Stress's random killer reached this flush) and a between-chunks produced when the deadline was already spent by the SETUP phase, which aborts at the executor's pre-chunk check and throws from the same line with the same message as the unfixed mid-block abort, so text cannot separate the two. Retrying cannot mask the bug, because an unfixed build has no checkpoint in the row loop and therefore yields between-chunks on EVERY attempt, and exhausting the attempts prints the last observed label rather than a synthesised pass. Second, the oracle narrowed by a table name that was assigned once and shared by both cases, so when a flush left no system.query_log row of its own the newest-row restriction silently returned the OTHER case's verdict; each case and attempt now gets its own table and cleanup enumerates them from system.tables by the shared prefix. The ${CLICKHOUSE_DATABASE} component of the name is kept, so 30 concurrent copies still pass 30/30. The reference is unchanged, no assertion was weakened and no tag was added: worst-case runtime is 15.4 s measured against the runner's 180 s limit (tests/clickhouse-test:150, enforced at :3358-3362), so no long tag is owed. r13 closes the last two ways this test could have reported a verdict it did not measure. The flush is now structurally ineligible for the Stress random killer: its query text carries a SETTINGS log_comment whose value contains the literal KILL QUERY, which is one of that killer's two exclusions, verified by running the killer's own victim SELECT against a live flush (0 rows with the clause, 1 row with it removed). The killer's other exclusion, system.processes, was deliberately not used, because the runner's own hung check filters on that same text and the token would have hidden this flush from the very check the test protects. The table name also carries the shell PID now, so two invocations in one database (Stress passes a fixed --database to half its threads, and the runner re-runs a failed test in the database it already used) can no longer read each other's system.query_log rows: on the previous naming a second invocation whose insert never ran returned the first one's in-loop-timeout as a pass, and it now correctly returns nothing and fails.
e Both directions demonstrated? YES, and per hunk, each on Build-ID-verified binaries (SELECT lower(buildId()) == readelf -n before every measurement). The bug: unpatched flush survives the KILL for 25.5 s (ef52c5f8), patched 0.49 s, re-verified 0.470 s on the committed tree; server logs show 25.14 s vs 127 ms from KillQuery to the exception. The test: reverting ONLY the ValuesBlockInputFormat hunk (df35b0ba) makes the Values section fail (20000 rows inserted) while TSV still passes; reverting ONLY the IRowInputFormat hunk (a598e6f6) does the mirror image, with 04547 still green. Both hunks are therefore independently load-bearing. At suite level the async_insert failure set differs between patched and pristine by exactly one test: this new one. Round r2 adds three more one-variable mutants: deleting the per-query failpoint gate at both sites turns foreign-insert: ok into FAILED: in both sections and the runtime from 9.3 s to 68.9 s; deleting the DROP pin fails with Code: 57; and restoring the unmodified master catch condition (both new disjuncts removed) turns parsing-error-rows: 0 into 1. Round r3 replaces that both-removed pin with a PER-DISJUNCT one, which is what the shell test could not express: deleting only || e.code() == TIMEOUT_EXCEEDED fails exactly the timeout case (3 others pass); deleting only || (is_cancelled && is_cancelled()) fails exactly the callback case; deleting both fails both; the non-vacuity control and the pre-existing QUERY_WAS_CANCELLED guard pass throughout. Build ID was verified to have MOVED before each of the four measurements, and the post-restore rebuild returned to the baseline Build ID bit-identically. Round r4 adds six more one-variable mutants, each Build-ID-verified. On the new row-loop unit suite: deleting the whole checkpoint block from IRowInputFormat::read fails ONLY the TSV case, deleting it from ValuesBlockInputFormat::read fails ONLY the Values case (run separately, so each loop is shown independently pinned), and rows != 0 -> true fails ONLY the short-block control. On the shell test: deleting ONLY the Values arming gate turns foreign-insert: ok into FAILED: in the Values case alone, deleting ONLY the IRowInputFormat gate does the mirror image, and widening CANCELLATION_CHECK_PERIOD_ROWS from 8192 to 16384 fails both cases, no cancellation, where at the payload size preceding r4 the same mutation passed (r5 moved that period pin into OneCheckPerStridePeriod, which pins it by equality with no server at all, and r6 therefore stopped asking the shell payload to carry it). After the sweep both carrier objects rebuilt bit-identical to their pre-mutation state. Round r5 adds four more, each Build-ID-verified: deleting rows_in_block != 0 from ValuesBlockInputFormat.cpp:138 fails ONLY ValuesShortBlockAsksNothing (predicate_calls 1 vs 0) with the other four passing, deleting rows != 0 from IRowInputFormat.cpp:143 fails ONLY the IRowInputFormat-side cases while ValuesShortBlockAsksNothing passes (the two mutations reddening opposite cases is what shows the guards are independently pinned), and moving CANCELLATION_CHECK_PERIOD_ROWS to 16384 and to 4096 fails OneCheckPerStridePeriod reporting predicate_calls 0 and 2 respectively against the expected 1. unit_tests_dbms rebuilt bit-identically to its pre-mutation Build ID after restore. Round r6 re-runs the per-hunk pair on the widened payload: reverting ONLY IRowInputFormat.cpp fails ONLY the TSV section (81921 rows inserted, Values green), reverting ONLY ValuesBlockInputFormat.cpp does the mirror image, and after restoring both the clickhouse binary rebuilt bit-identically to its pre-mutation Build ID. It also adds the pair that justifies the widening itself: with one premature channel release injected before the KILL, the test FAILS at ROWS=8193 (both sections insert all rows) and PASSES at ROWS=81921. Round r7 adds two independent both-directions measurements, all arms Build-ID-verified with one variable each and the predicted failing set stated before running. For the unit item, a four-arm mutation matrix over the two period literals: Values-only to 16384 reddens ONLY the new Values case, TSV-only to 16384 reddens ONLY the TSV case, Values-only to 4096 reddens the new case in the narrowing direction, and the shared constant reddens both; afterwards every source is md5-identical and unit_tests_dbms rebuilt back to its exact pre-mutation Build ID. For the shell item, the decisive pair injects a foreign SYSTEM DISABLE FAILPOINT while the flush is parked: with the retry loop the test PASSES, with the loop reduced to one attempt it FAILS with both sections printing +81921, and an un-injected control passes. That pair also surfaced a real defect the retry alone could not fix: notifyFailPoint throws BAD_ARGUMENTS when the channel is already gone, and ||: discards only the exit code, so the message reached stderr and clickhouse-test FAILs on non-empty stderr no matter what stdout says - visible as an arm whose stdout was already correct while the verdict was still FAIL. The release now discards stderr too, scoped to that one statement (its callee has exactly one throw), with the neighbouring SYSTEM ENABLE FAILPOINT deliberately left unguarded. Finally, the retry was proven not to mask a regression: reverting ONLY IRowInputFormat.cpp fails the TSV section and leaves Values green, reverting ONLY ValuesBlockInputFormat.cpp gives the mirror image, and both fail on the first attempt's outcome rather than going green after three. Round r10 re-establishes both directions for the rewritten shell test, and the discriminator is now SEMANTIC rather than a timing margin: the fixed build reports Timeout exceeded (TIMEOUT_EXCEEDED) from inside the row loop after 593-1113 ms, while an unpatched build parses the whole payload and reports Format streaming was cancelled (QUERY_WAS_CANCELLED) after 941-2441 ms, so the reference diff names the bug instead of reporting a timeout. Measured on the pristine master snapshot (all four carrier files md5-identical to the merge-base) and again on a build with only the two row-loop hunks reverted (Build ID moved 8115d546 -> 7f83a0df), which FAILS for BOTH carriers; restoring the sources relinked bit-identically back to 8115d546 with both source md5s equal to the pre-mutation copies. Two further one-variable mutants pin the fixture itself: removing the max_execution_time pin FAILS with both assertion lines absent (nothing cancels the flush, so the deadline and not incidental slowness is what aborts it), and pinning timeout_overflow_mode = 'break' also FAILS with no abort, which is what makes the previous mutant sound because break routes to checkTimeLimit rather than cancelQuery.. Round r11 re-establishes every one of those arms against the rewritten oracle, and the labels now name the mechanism rather than a message. The reverted-hunks control (only the two row-loop CurrentThread::checkIfNotCancelled() calls removed, Build ID moved 2a8755d3 -> 66fe71d3) FAILS for BOTH carriers with the diff reading -in-loop-timeout / +between-chunks, and it was run TWICE, once against the first version of the oracle and again against the final test file; restoring the two sources relinked BIT-IDENTICALLY back to 2a8755d3 with both source md5s equal to the pre-mutation copies. Both fixture mutants were re-confirmed against the new oracle and now fail with a diagnosis instead of a blank line: removing the max_execution_time pin and pinning timeout_overflow_mode = 'break' each give -in-loop-timeout / +other-0 on both carriers, where other-0 is exception_code on a QueryFinish row, i.e. the label states that the flush COMPLETED. Two arms are new in r11 and neither was expressible before. A foreign KILL QUERY was hand-injected against a flush run with max_execution_time=0, so only the kill could end it: the label becomes cancelled-elsewhere (code 394, Query was cancelled), a named third state, where the old grep -oE oracle would have printed NOTHING and failed a correct build. And the same predicate WITHOUT its query_kind filter returns, newest-first, a Select row (the oracle query itself, which contains the table name) then the initiator's Insert row carrying the SAME code 159 then the flush - so the filter is shown to defend against two distinct wrong answers, not one. Round r12 re-runs the reverted-hunks control against the retried test and adds the measurement that proves the retry did not weaken it. With only the two row-loop CurrentThread::checkIfNotCancelled() calls removed (Build ID moved 2a8755d3 -> 66fe71d3) the test FAILS for BOTH carriers with the diff reading -in-loop-timeout / +between-chunks, and because every attempt now uses its own table the attempt count is directly countable in system.query_log: the mutant produced rows for _tsv_1, _tsv_2, _tsv_3, _values_1, _values_2 and _values_3, i.e. all three attempts ran for both cases and the loop was exhausted rather than short-circuited, while the fixed build produced _tsv_1 and _values_1 only. Wall time corroborates it independently, 15.37 s against 3.99 s. Restoring the two sources relinked BIT-IDENTICALLY back to 2a8755d3 with both source md5s equal to the pre-mutation copies. The recovery direction is measured too: a foreign KILL QUERY hand-injected against a flush run with max_execution_time=0 records code 394 Query was cancelled and the label cancelled-elsewhere, and through the retry the case then recovers on attempt 2 and prints in-loop-timeout, where before r12 that same disturbance failed a correct build. Finally the stale-row defect is shown closed by a discriminating pair on the SAME state: querying the Values case's table name without having run that insert selects 0 rows and prints nothing, and therefore FAILs, whereas the previously shared name returned the TSV case's in-loop-timeout as a PASS. r13 adds a third, independent both-directions arm that does not rely on a locally reverted tree: the official master release build 26.8.1.435 (buildId 879ae7f7), which does not contain this change, fails the shipped test in exactly the diagnostic way it is designed to (between-chunks for both carriers, 20 of 20 runs before the runner's failure-chain limit stopped it), while the fixed build passes 50 of 50. The reverted-hunks arm was also re-run against r13's test file, with all three attempts per carrier exhausted and the restore relinking bit-identically to 2a8755d3.
f Fix is general across code paths? YES, with the loop set enumerated rather than spot-patched. The carrier is "a class reachable from StreamingFormatExecutor whose read can iterate up to max_block_size_rows without returning"; there are exactly two such shapes on this path, and both are fixed: IRowInputFormat::read (the loop every row-based format inherits) and ValuesBlockInputFormat::read, which is final : public IInputFormat and so inherits nothing, is bounded by the same max_block_size_rows, and is the format the executor explicitly typeid_casts (StreamingFormatExecutor.cpp:57-61) for the commonest async-insert shape, INSERT ... VALUES. Column-oriented formats do not loop per row in read. Sibling carriers enumerated and dispositioned: the executor's per-chunk check (already correct); its cancellation-vs-parse-error classification (also fixed); the error-skipping path (safe by construction, isParseError contains neither cancellation code); CancelReason::PartialResult early stop (verified not broken); NpyRowInputFormat's pre-existing isCancelled() loop (out of scope, noted); the countRows / need_only_count family (unreachable from the insert path, needOnlyCount() has only three SELECT-side callers, tracked separately); the streaming engines (Kafka/Kafka2/FileLog/NATS/RabbitMQ), which never call setProcessListElement, so the predicate is a no-op there. Round r3 adds direct coverage for that last shape: those five callers build the executor with only three arguments, i.e. with NO cancellation callback, so for them the error code alone must classify a timeout, and the new unit case for exactly that shape had no test before. Round r4 closes the last gap in this row: until now both row loops were pinned only through the shell test, whose failpoint channel is global to the server, and whose foreign-insert probe was hard-coded to TSV, so a mutation deleting only the Values guard left the whole suite green. Each loop is now pinned twice and separately, by a server-free unit case (RowInputFormatCancellation.*, which constructs each format directly and drives read over a payload crossing the stride) and by a probe that travels the case's own format. Both mutation directions were measured, and the unit cases are immune to the collision the shell test can suffer: 50 repeats and 4 concurrent processes, 0 failures. Round r5 finishes the job on both axes: the row-zero guard exists twice in independent code and each copy now has its own short-block control, and the stride's VALUE, which until now rested solely on the shared-failpoint shell test, is pinned by equality in the server-free suite as well. Round r10 does not change the carrier set; it changes how the two loops are driven end to end. Both are still pinned twice and separately: by the server-free RowInputFormatCancellation.* suite, and by the two 04652 sections, which now reach the same checkpoint through the flush's own deadline rather than a shared failpoint channel. The TIMEOUT_EXCEEDED arm of StreamingFormatExecutor::execute is now exercised end to end as well as by StreamingFormatExecutorCancellation.RethrowsTimeoutWithoutCancelCallback, which it was not before.
g Fix generalizes across inputs (params/datatypes/wrappers)? YES. The checkpoint is one integer test in the loop that drives readRow, above any serialization, so it is format- and type-agnostic by construction. Boundaries exercised: empty payload (after the row-0 skip it performs no poll at all and exits normally), payload smaller than one 8192-row stride, max_block_size at 1 / 8191 / 8192 / 65409 (one below, at, and far above the stride), and ~1M rows in one block. The format (472 tests) and values (81 tests) suites were run on BOTH the patched and the pristine binary in the same sandbox and their sorted failing-test lists are IDENTICAL, so a regression cannot hide behind an equal count; the 47 and 2 pre-existing failures fail identically (missing 2-shard cluster, /var/lib/clickhouse paths, missing S3/Kafka/protobuf fixtures). Driving all 35 input+output formats directly through the async-insert path: 34/34 OK, only AvroConfluent fails because the CI Avro schema registry is not running locally. Round r2 touches FormatFactory::getInputImpl, which builds the params for every input format, so the format + values selection (546 tests) was re-run on the patched binary and its 66 distinct failures were then re-run on a pristine control built in the same tree: 66 FAIL / 0 OK, so the sets are identical and there are 0 regressions.
h Backward compatible? (maintainer-approved exception only) YES, nothing to migrate. One setting is ADDED in round r2 (input_format_pause_inside_block_failpoint, Bool, default false, documented test-only) so that the new PAUSEABLE failpoint can only pause the query that opts in rather than every query on the server that crosses a row-loop stride. It is recorded in the 26.8 block of SettingsChangesHistory.cpp, which is required rather than optional: 03999_stateless_settings_history fails any new non-obsolete setting that is neither in the frozen baseline nor in the history, and ci/jobs/check_style.py:580 enforces the same for the current version block; that test is green. No existing default is changed, so compatibility restores nothing differently. No serialization or format change; no new validation over existing data; no feature gate. The only behaviour change is an earlier abort of an already-killed or already-timed-out query, which previously ran to the end of its block. Round r11 REMOVES that setting again, so as merged this PR adds NO setting at all: the 26.8 SettingsChangesHistory.cpp row is deleted together with the declaration, and src/Core/Settings.cpp, src/Core/SettingsChangesHistory.cpp, src/Common/FailPoint.cpp and src/Formats/FormatFactory.cpp are now md5-identical to the merge-base. check-settings-style and check_cpp.sh are both clean afterwards.
i Invariants and contracts preserved? YES. The new throw is raised in the loop body and caught by read()'s existing outer catch (Exception &), which rethrows because isParseError(QUERY_WAS_CANCELLED) is false, so no verbose-diagnostic read of a self-cancelled buffer and no partial-column rollback path is entered; the columns are local to the call. Post-conditions of a successful read() are untouched. No lock is held at the checkpoint, so no lock-ordering or atomicity contract changes. The executor still runs format->resetParser() before the rethrow. The async queue's entry-finishing contract is upheld more correctly than before: a cancelled flush now finishes with the cancellation exception instead of a mislabelled parsing failure. Deliberately NOT using IProcessor::isCancelled(), because ISource::cancel sets that flag ignoring the CancelReason and PartialResult reaches it via TCPHandler, so throwing on it would turn a valid LIMIT early stop into an error; all six early-stop controls (file/url with LIMIT, max_threads=1, max_block_size=1, parallel parsing off, full pipeline INSERT) return their rows without error. The same reasoning and the same unconditional-rethrow argument hold for the Values loop, whose enclosing try also only decorates the message when isParseError(e.code()). Round r3 adds an explicit non-vacuity control to the new unit suite (a parse error with nothing reporting cancellation must STILL reach on_error), so the three rethrow cases cannot pass merely because on_error became unreachable; each case also asserts the format was actually entered (read_calls == 1), which keeps them from going vacuous if the executor's pre-chunk check ever fires first.

Session id: cron:clickhouse-impl-slot-4:20260730-164200

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c040da8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
04215_91595_uniq_theta_intersect_empty_state FAIL cidb IGNORED
Stress test (arm_release) FAIL
S3_ERROR No such key thrown (see clickhouse-server.log or no_such_key_errors.txt) FAIL cidb IGNORED
Stress test (arm_tsan) FAIL
Logical error: Bad cast from type A to B (STID: 4256-3fc1) FAIL cidb IGNORED

AI Review

Summary

This PR fixes the original async-insert failure mode by adding query-cancellation checkpoints inside the long row loops in IRowInputFormat::read and ValuesBlockInputFormat::read, while keeping StreamingFormatExecutor's bad-message handling unchanged for callback-less streaming callers. The follow-up test change also closes the missing-query_log-row flake in 04652. I did not find a remaining blocker or major issue in the current head.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
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`.
@groeneai
groeneai force-pushed the fix-async-insert-flush-cancellation-json-parse branch from cdda23a to 9ed6794 Compare July 31, 2026 01:41
/// 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)

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9ed6794

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (unit tests) harness limitation, not a test result: the job aborts as inconclusive because master moved seven submodules (contrib/StringZilla, contrib/jwt-cpp, contrib/libarchive, contrib/openssl, contrib/orc, contrib/sqlite-amalgamation, contrib/thrift) after this branch split, so the before-worktree cannot be populated at the merge-base revisions. No test ran and this PR changes no submodule a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260731-155315

#include <gtest/gtest.h>

#include <Columns/ColumnsNumber.h>
#include <Core/Block.h>

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.

@groeneai remove the gtests. There is a sql test

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c040da8

CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both green, last check completed 2026-08-08T05:31:54Z. Counted by conclusion:
155 success, 17 skipped, 3 failure.

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04215_91595_uniq_theta_intersect_empty_state stale literal_token_map entry inherited by a parser-synthesized ASTLiteral on the Array slow path: Code: 130 Array does not start with '[' character on CAST(-dummy-0, 'Array(UInt32)') at SerializationArray::deserializeText, while executing ValuesBlockInputFormat. The job's own diagnostics report All reruns passed. The failure is not reproducible, and the rate is 3 failures against 120206 OK over 30 days #110637 (mine, open)
Stress test (arm_tsan) / Logical error: Bad cast from type A to B (STID 4256-3fc1) trunk bug: reading only a dotted Nested member's subcolumn from a part written before an ALTER ... MODIFY COLUMN that added a type wrapper casts ColumnString to ColumnNullable #113925 (mine, open)
Stress test (arm_release) / S3_ERROR No such key thrown trunk bug: a merge over a stale packed temporary directory on a cached S3 disk reads a key that no longer exists. 9 rows / 9 distinct PRs / 1 master in 14 days a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

None is PR-caused, and the first row is the one that needed measuring rather than assuming: this PR
edits src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp, which is named in that stack, so it
looks like an own-code regression. It is not.

  • The whole diff in that file is +6/-0: one #include <Common/CurrentThread.h> and one
    if (rows_in_block != 0 && rows_in_block % CANCELLATION_CHECK_PERIOD_ROWS == 0) CurrentThread::checkIfNotCancelled(); checkpoint. Adding a cancellation checkpoint cannot make
    SerializationArray::deserializeText reject a value's leading character.
  • Refuted on dates as well: the identical signature (same -dummy-0 expression, same
    SerializationArray::deserializeText frame, same query 14, line 65) fired on PR 110151 on
    2026-07-14, while this branch was created 2026-07-30, 16 days later.
  • The -dummy-0 placeholder is the family's fingerprint. Keyed on that mechanism rather than on a test
    name, the family spans 11 distinct test names and 0 master hits over 90 days.

The other two rows are likewise outside this diff, which only adds cancellation checkpoints to
IRowInputFormat, ValuesBlockInputFormat and StreamingFormatExecutor plus one new test: this PR
touches no Nested subcolumn read path and no S3 disk caching.

Session id: cron:our-pr-ci-monitor:20260808-060000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 8, 2026
Merged via the queue into ClickHouse:master with commit fd2595c Aug 8, 2026
176 of 180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors 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.

4 participants