Repository navigation
Check for cancellation in AggregatingInOrderTransform - #110104
alexey-milovidov merged 10 commits into
Conversation
AggregatingInOrderTransform::consume() splits one input chunk into runs of equal keys in a loop; query time and cancellation limits are only checked between pipeline steps (between work() calls). A chunk with many distinct keys makes a single consume() call run for a long time (O(distinct_keys) iterations, each an upper_bound over the remaining rows) with no cancellation checkpoint. So a cancelled query (KILL QUERY, max_execution_time) using optimize_aggregation_in_order kept aggregating until the whole chunk was done; the connection thread then blocked in PullingAsyncPipelineExecutor::cancel() -> ThreadFromGlobalPool::join() waiting for that loop, which the server-side AST fuzzer repeatedly hit as "Hung check failed, possible deadlock found" (is_cancelled=1, elapsed far past the 90s hung-check window, worker thread in AggregatingInOrderTransform::consume -> Aggregator::executeImpl). The loop now checks isCancelled() once per key interval and returns early; the partial state is discarded because the pipeline is torn down. This mirrors the existing per-loop cancellation checks in WindowTransform and FillingTransform. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260711-162500 |
|
cc @KochetovNicolai @nickitat — could you review? |
|
Workflow [PR], commit [3d248d2] Summary: ✅
AI ReviewSummaryThis PR adds an Findings
Tests
Final Verdict❌ Changes requested. The new checkpoint fixes the reproduced tiny-interval loop, but the same cancellation gap is still reachable for single large intervals in LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 2/3 (66.67%) · Uncovered code |
| { | ||
| /// Cancellation is only checked between work() calls, but one consume() over a chunk with many | ||
| /// keys can run for a long time; check per key interval so a cancelled query stops promptly. | ||
| if (isCancelled()) |
There was a problem hiding this comment.
isCancelled here only runs between intervals, but optimize_aggregation_in_order also has reachable plans where one interval itself is huge. optimizeReadInOrder.cpp:723-725 documents the (a, c) / (a, c, d) shape, and 02233_optimize_aggregation_in_order_prefix.sql exercises it: one sort_description_for_merging prefix can cover many rows that are then aggregated in a single executeOnBlockSmall call. That call (Aggregator.cpp:845-868) and the no-key path (Aggregator.cpp:1471-1500) still have no cancellation checkpoint, so a cancelled query can still stay stuck until the whole interval finishes. To actually satisfy the bug-fix contract here, the cancellation check needs to be threaded into those aggregation routines (or the interval work needs to be chunked), not just added between intervals.
There was a problem hiding this comment.
The finding is accurate that executeOnBlockSmall / executeOnIntervalWithoutKey have no inner-row cancellation check, but it does not change the deadlock contract here, for two reasons:
-
One interval is chunk-bounded, not query-bounded. An interval is a maximal equal-key run within a single input chunk, so its length is capped by the chunk size (
<= max_block_size, default 65409 rows). Even the(a, c)/(a, c, d)prefix shape inoptimizeReadInOrder.cpp:723-725only affects which keys form a run inside a chunk; it cannot make oneexecuteOnBlockSmallspan more than the chunk. A single small-block aggregation over<= max_block_sizerows completes in the millisecond range. -
Per-block is the established granularity for the aggregation execute path. The regular (non-in-order)
AggregatingTransformaggregates an entire block viaAggregator::executeOnBlock(AggregatingTransform.cpp:993) with no inner-rowisCancelled()check either, and that path has never been a hung-check source. Cancellation in the execute path is a per-block/per-interval checkpoint by design; only the merge path threadsis_cancelleddeeper (mergeWithoutKeyStreamsImpl) because merges are unbounded across many source variants.
The reproduced 90s+ hang was caused by the while (key_end != rows) loop iterating O(distinct_keys) times (65409 tiny intervals) with the cancellation flag ignored the whole time, not by any single interval running long. The per-interval isCancelled() check sits exactly on that loop and reduced KILL SYNC latency from 82.65s to 0.16s in the local repro.
Threading a checkpoint into executeImplBatch (the hottest row loop in the server) would add a branch to every aggregation for a scenario bounded to a single block, i.e. no reproducible benefit and a measurable hot-path cost. I have no repro where one interval alone exceeds the hung-check window, so per the bug-fix contract I am keeping the fix at the per-interval granularity that mirrors WindowTransform/FillingTransform.
CI finish ledger — 92ea716Every 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. None is caused by this PR (which only adds
Session id: cron:our-pr-ci-monitor:20260711-223000 |
|
Fixing PR for the multiply Int256*Float64 Root cause is a concurrent |
…g-in-order-cancel
| SELECT number, toString(number % 1000), number, toString(number % 777), number | ||
| FROM numbers(5000000) SETTINGS max_insert_threads = 1, max_block_size = 1000000" | ||
|
|
||
| # GROUP BY on the full sort key prefix triggers optimize_aggregation_in_order; every row is a distinct group, |
There was a problem hiding this comment.
AggregatingInOrderTransform also runs with params.only_merge (for example in aggregating projections and distributed/parallel partial-merge plans), and that sibling path is still uninterruptible for a single large prefix interval. The only_merge && group_by_key branch here calls Aggregator::mergeOnBlockSmall, but that helper still passes a local std::atomic<bool>{false} into mergeStreamsImpl (src/Interpreters/Aggregator.cpp:885-915), so the inner merge never sees cancellation. This test only proves the non-merge repro, while the changelog and PR description now read as if optimize_aggregation_in_order is fixed in general. Please thread the processor's cancellation flag through mergeOnBlockSmall as well, or scope the fix/test/PR text down to the non-merge path.
There was a problem hiding this comment.
Verified on the rebased head (0bac4ef):
The cancellation check is at the top of the while (key_end != rows) loop (AggregatingInOrderTransform.cpp:159), before the branch that selects the aggregator call (lines 175-190), so it guards all four branches equally, including only_merge && group_by_key -> mergeOnBlockSmall (line 178). The reproduced deadlock (the O(distinct_keys) loop of tiny intervals ignoring is_cancelled) is therefore fixed for the merge path too; the only_merge sibling is not still uninterruptible at the loop level.
The residual point is sub-interval: yes, mergeOnBlockSmall (Aggregator.cpp:910) passes a local atomic<bool>{false} into mergeStreamsImpl. That is the same shape as the execute-path concern already discussed at r3564834313, applied to the merge sibling, and the same bound holds: one interval is a maximal equal-key run within a single input chunk (key_end = upper_bound over [key_begin, rows), rows = current chunk rows), so it is capped by max_block_size (default 65409) for merge and execute alike. A single small merge/execute over <= max_block_size rows is millisecond-range, and there is no repro where one interval alone exceeds the 90s hung-check window. Threading the flag into mergeStreamsImpl / executeImplBatch adds a branch to the hottest aggregation loops for a block-bounded case, so per the no-speculative-change rule I keep the fix at per-interval granularity absent such a repro. Only mergeOnIntervalWithoutKey (line 180) threads the flag deeper, because mergeWithoutKeyStreamsImpl also runs on unbounded cross-source ranges elsewhere.
On the text: the changelog says the transform "checks for cancellation while aggregating a chunk", which is exactly what the loop-level check does for every path. It does not claim sub-interval interruptibility, so no scoping change is needed.
The test used max_execution_time=1 and expected TIMEOUT_EXCEEDED, but that is a wall-clock race: the whole query occasionally completes just before the timeout is observed (printing "no timeout"), and max_execution_time cancels the downstream window/sort transforms regardless of the aggregation fix, so it does not test the fix directionally. Rewrite it around KILL QUERY. Force one long AggregatingInOrderTransform::consume() call (all rows in a single input chunk; max_block_size and aggregation_in_order_max_block_bytes large so consume() does not return early), wait until every row is read so the query is inside that single consume() loop, then KILL QUERY ... SYNC. With the fix the KILL returns in a fraction of a second; without it it blocks for the seconds the loop needs to finish. A timeout(1) around the KILL sits between the two, so a missing fix shows up deterministically as "not cancelled in time". Co-Authored-By: Claude Opus 4.8 <[email protected]>
7f2c68a to
fd73840
Compare
fd73840 to
f502f1f
Compare
The regression asserts cancellation LATENCY: a cancelled query must stop before a short wall-clock timeout. Pin max_rows_to_read = 0 on the setup INSERT and the long SELECT (the default stateless profile sets max_rows_to_read = 20000000, which numbers() enforces up front, so the 40M-row INSERT and SELECT would otherwise throw TOO_MANY_ROWS before the cancellation path is reached). Tag it no-flaky-check. The flaky check reruns a changed test ~50x concurrently under sanitizers; for a wall-clock latency assertion that only produces timing races (the flaky check always runs the fixed binary, so it adds no fails-without-fix signal). The fails-without-fix / passes-with-fix coverage is kept on every normal debug/asan/tsan/msan/release job. Same reasoning as the sibling KILL cancellation tests 03984_kill_query_with_fill and 04028_kill_query_expression_cancelled. Co-Authored-By: Claude Opus 4.8 <[email protected]>
f502f1f to
303b5c5
Compare
CI finish ledger — 303b5c5CI fully finished on this head (Finish Workflow SUCCESS). Our test
Session id: cron:our-pr-ci-monitor:20260720-030000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 4/5 (80.00%) · Uncovered code |
CI finish ledger — ceb9f64Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-053000 |
|
Dear @yakov-olkhovskiy, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
04512_aggregation_in_order_cancellation asserted that a cancelled query stops promptly by wrapping the KILL QUERY ... SYNC client invocation in `timeout 3`. That bounds the wall clock of a whole clickhouse-client run: process startup, connect, the KILL itself and teardown. Only the KILL is what the fix affects; the rest grows with load on the runner, so the assertion raced and the test failed as "not cancelled in time" on Stateless tests (amd_tsan, parallel). Give the KILL its own query_id and assert on its query_duration_ms from query_log instead. That measures only the server-side wait, so the bound no longer competes with client startup. Measured in a debug build with the same fixture (40M distinct keys, one part, one consume() call): with the fix 102, 102, 102, 102, 102, 102 ms without it 11315, 11217, 11319 ms Across 8 copies of the test running concurrently the server-side figure stayed at 102-104 ms while the test's own wall clock moved from 3.09s to 8.55s, which is the term the old bound was measuring. The new bound of 3s leaves 29x margin over the fixed 100ms poll granularity of the SYNC loop in InterpreterKillQueryQuery, and a regression still costs seconds. The query_id includes the pid and the verdict reads the newest matching row, because CLICKHOUSE_DATABASE is reused across runs when clickhouse-test is given a fixed --database, and a row count assertion broke on the second such run. An absent row yields an empty verdict, which still fails. Directionality re-verified with the final test: 3/3 FAIL with the cancellation checkpoint removed, 3/3 and 8/8 PASS with it (fixed-database repeats, randomized settings, and 8-way concurrent). The no-flaky-check tag stays: the flaky check only ever runs the fixed binary, so repeating this test there adds no fails-without-fix signal, while every normal job keeps running it directionally. AggregatingInOrderTransform.cpp is unchanged by this commit.
The Style check requires every test that reads system.query_log or system.query_thread_log to constrain it by the current database (ci/jobs/scripts/check_style/various_checks.sh). The KILL latency lookup added in the previous commit filtered only by query_id, so the check failed on this test. The KILL runs through $CLICKHOUSE_CLIENT, which passes --database=$CLICKHOUSE_DATABASE, so its query_log row already records the test's own database: the predicate is a no-op for matching the row here. Verified it is nonetheless live rather than decorative -- the same lookup run from another database returns no row, and an absent row leaves the verdict empty so the assertion still fails. Both directions re-checked on the same binaries as before (with the cancellation checkpoint: 3/3 fresh databases, 3/3 on one reused database, 6/6 concurrent copies, 3/3 randomized via clickhouse-test, all "cancelled" with the server-side KILL at 102-103 ms; without it: 3/3 "not cancelled in time" at 11.2-11.4 s). Co-Authored-By: Claude Fable 5 <[email protected]>
The KILL latency assertion used a fixed 3000ms budget on the KILL's server-side duration. On amd_tsan the KILL measured 3359ms and the test failed, while two reruns of the same binary measured 1168ms and 2063ms: the bound was competing with runner load, not with a cancellation regression. Every wall-clock form has this problem, including the one it replaced, because a debug or sanitizer runner under parallel load stretches whichever duration the assertion names. Assert instead on the CPU time the cancelled query burned, which is what the checkpoint changes: returning at the next key interval leaves the rest of the loop unaggregated, while ignoring cancellation charges the whole loop. That counts work done rather than time passed, so no scheduling delay or competing load can inflate it. To keep the cutoff meaningful across build types, price the read first by scanning the same rows without aggregating and compare against a multiple of it, since sanitizer instrumentation and architecture scale both together. Measured: the cancelled query costs 1.6-2.4 times the plain read with the fix and about 40 times it without, and each population holds under parallel load. Three relative wall-clock forms were tried first and each was defeated against the unfixed binary: ratios to the victim's total duration and to its read time both let a pre-KILL stall inflate the denominator and print cancelled, and a separately measured reference KILL did not inflate under load at all (103ms with 12 competing scans), so it could not track the delay that caused the failure. The regression the test exists to catch is still caught: with the 5-line checkpoint removed it fails 3/3 sequentially, 6/6 concurrently, and under clickhouse-test. Also report the measured values when the assertion fails. Both halves of the conjunction printed the same message, so a failure could not say whether the KILL never reported finished, the loop kept running, or a measurement was missing. The counters are read through mapContains and log_profile_events is pinned, so an unlogged counter reads as missing rather than as a zero that would pass. Test-only change. Diagnostics go to stdout, since any stderr output is itself a test failure in clickhouse-test.
CI finish ledger - 3d248d2CI is fully finished on this head and there are no failures to own.
177 leaf jobs: 159 OK, 18 skipped, 0 failed, 0 dropped. Praktika reports this head top-level Session id: cron:our-pr-ci-monitor:20260813-123000 |
…point integration test 04512_aggregation_in_order_cancellation.sh guards the per-key-interval cancellation check added in ClickHouse#110104, but it asserts on a measured quantity: aggregation CPU as a multiple of scan CPU, after a shell-issued KILL. It has now been rewritten eight times and prints "not cancelled in time" on master again (5 failures in 24 h on 2026-08-13, 2 of them on master, all on amd_asan_ubsan / distributed plan / parallel). The oracle prices the window between "the rows are read" and "the KILL flips is_cancelled", and two fresh clickhouse-client process startups sit on that critical path. 04410_primes_source_cancellation.sh:44-49 records the in-tree figure: a single client invocation alone can take ~8 s on a loaded sanitizer build. The checkpoint was firing on every failing run, stopping at 52-75 % of the loop rather than 100 %; only the window grew. The race cannot be closed from the shell either, because read progress is published after the source's work() returns (ExecutionThreadContext.cpp:57-75), so nothing shell-visible indicates that the aggregation loop is running. Adopt the deterministic mechanism LimitByTransform already uses (e20a673, then d811a21 and 0fa0ea3): a PAUSEABLE_ONCE failpoint on the sixth key interval, placed after the cancellation check and inside the loop, plus a LOG_TEST marker in the existing cancellation branch. The new integration test pauses there, kills the query, resumes, and asserts the marker appears. That assertion is structural and load-invariant, with no timing, threshold or free constant. The mid-loop placement is deliberate. A pre-loop pause would resume straight into the first isCancelled(), so the test would stay green even if that check were hoisted out of the loop, which is precisely the bug ClickHouse#110104 fixed. Both mutation arms were verified to redden: deleting the checkpoint, and hoisting it out of the loop. Deleting the 40 M-row fixture also removes its max_estimated_execution_time exposure on slow storage, which was a second, independent failure mode of the same test. The failpoint costs nothing when disabled: pauseFailPoint expands to if (fiu_fail(name)) [[unlikely]] and sits behind an integer compare, so it is reached at most once per consume(). Measured over 40 M key intervals, base vs patched interleaved: 11.515 s vs 11.503 s user CPU. The marker assertion counts lines rather than testing for presence. The marker is emitted inside the cancellation branch and isCancelled() reads an atomic that stays true once set, so deleting only the return re-enters the branch on every remaining iteration: the marker would print once per key interval while the loop still aggregates to completion. Requiring exactly one line rejects that mutation (94 lines on the 100-interval fixture) and keeps rejecting a deleted or hoisted check (0 lines), with no timing term.
Related: #107941
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
optimize_aggregation_in_orderignoring query cancellation.AggregatingInOrderTransformnow checks for cancellation while aggregating a chunk, so a query stopped byKILL QUERYor bymax_execution_time(in the defaulttimeout_overflow_mode = 'throw') stops promptly instead of running the whole chunk to completion.Description
AggregatingInOrderTransform::consume()splits one input chunk into runs of equal keys in a loop. Query time and cancellation limits are only checked between pipeline steps (betweenwork()calls), so a chunk with many distinct keys makes a singleconsume()call run for a long time (O(distinct_keys)iterations, each anupper_boundover the remaining rows) with no cancellation checkpoint.As a result a cancelled query (
KILL QUERY,max_execution_time) usingoptimize_aggregation_in_orderkept aggregating until the whole chunk was done; the connection thread then blocked inPullingAsyncPipelineExecutor::cancel() -> ThreadFromGlobalPool::join()waiting for that loop. The server-side AST fuzzer repeatedly hit this asHung check failed, possible deadlock found(Stress test, all sanitizers), withsystem.processesshowingis_cancelled = 1andelapsedfar past the 90s hung-check window while the worker thread sat inAggregatingInOrderTransform::consume -> Aggregator::executeImpl.The loop now checks
isCancelled()once per key interval (cheap) and returns early; the partial aggregation state is discarded because the pipeline is being torn down. This mirrors the existing per-loop cancellation checks inWindowTransformandFillingTransform.Scope: this covers cancellation that sets
is_cancelledon the pipeline, i.e.KILL QUERYandmax_execution_timein the defaulttimeout_overflow_mode = 'throw', which is what the reproduced hung check hit (system.processesshowedis_cancelled = 1). The non-defaultbreakmode is a soft limit that returns a partial result and never setsis_cancelled; honoring it mid-chunk (asFillingTransformdoes viaprocess_list_element->checkTimeLimit()) is a separate partial-result change, out of scope here. The regularAggregatingTransformbehaves the same way.Regression test
04512_aggregation_in_order_cancellationforces one longconsume()over 40M distinct-key rows in a single chunk,KILL QUERY ... SYNConce every row is read: with the fix the KILL returns in a fraction of a second, without it it blocks for the several seconds the loop needs to finish.Version info
26.8.1.1344(included in26.8and later)