Skip to content

Check for cancellation in AggregatingInOrderTransform - #110104

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregating-in-order-cancel
Aug 13, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregating-in-order-cancel

Conversation

@groeneai

@groeneai groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107941

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

Fix optimize_aggregation_in_order ignoring query cancellation. AggregatingInOrderTransform now checks for cancellation while aggregating a chunk, so a query stopped by KILL QUERY or by max_execution_time (in the default timeout_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 (between work() calls), so 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.

As a result 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. The server-side AST fuzzer repeatedly hit this as Hung check failed, possible deadlock found (Stress test, all sanitizers), with system.processes showing is_cancelled = 1 and elapsed far past the 90s hung-check window while the worker thread sat in AggregatingInOrderTransform::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 in WindowTransform and FillingTransform.

Scope: this covers cancellation that sets is_cancelled on the pipeline, i.e. KILL QUERY and max_execution_time in the default timeout_overflow_mode = 'throw', which is what the reproduced hung check hit (system.processes showed is_cancelled = 1). The non-default break mode is a soft limit that returns a partial result and never sets is_cancelled; honoring it mid-chunk (as FillingTransform does via process_list_element->checkTimeLimit()) is a separate partial-result change, out of scope here. The regular AggregatingTransform behaves the same way.

Regression test 04512_aggregation_in_order_cancellation forces one long consume() over 40M distinct-key rows in a single chunk, KILL QUERY ... SYNC once 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

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

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. optimize_aggregation_in_order over 5M distinct-key rows with max_execution_time = 1: without the fix a single consume() runs ~40-84s (measured 84121 ms / 65409 loop iterations, is_cancelled=true) and the timeout 40 wrapper kills the client.
b Root cause explained? AggregatingInOrderTransform::consume() loops over key intervals in one chunk; cancellation is only checked between work() calls, so with many distinct keys per chunk one consume() runs to completion after KILL/timeout → connection thread blocks in PullingAsyncPipelineExecutor::cancel() -> join() → hung check.
c Fix matches root cause? Yes. Adds an isCancelled() checkpoint inside the interval loop, exactly where the uninterruptible work happens.
d Test intent preserved / new tests added? New regression test 04512_aggregation_in_order_cancellation added; asserts a cancelled in-order aggregation stops with TIMEOUT_EXCEEDED promptly.
e Both directions demonstrated? Yes. Test FAILS on pristine master (44.3s, no timeout), PASSES with the fix (5.6s, TIMEOUT_EXCEEDED); KILL-SYNC latency 82.6s → 0.16s.
f Fix is general across code paths? Both consume() paths (group_by_key executeOnBlockSmall and executeOnIntervalWithoutKey) are inside the guarded loop. WindowTransform/FillingTransform already use the same per-loop isCancelled() idiom.
g Fix generalizes across inputs? The check is key-type independent (fires before the interval work regardless of key datatype/wrappers); reproduced with String keys, applies to all.
h Backward compatible? Yes. No settings/format/behavior change for non-cancelled queries; only makes a cancelled query stop sooner.
i Invariants and contracts preserved? Yes. Early return on cancellation discards partial aggregation state, which is correct because the pipeline is being torn down; no output is produced from a cancelled consume(). Matches existing transforms.

Session id: cron:clickhouse-worker-slot-4:20260711-162500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @nickitat — could you review? AggregatingInOrderTransform::consume() loops over key intervals in one chunk with no cancellation checkpoint, so a cancelled optimize_aggregation_in_order query keeps aggregating a large chunk to completion and the connection thread blocks in PullingAsyncPipelineExecutor::cancel() -> join() (a recurring "Hung check failed, possible deadlock found" signature). Added a per-interval isCancelled() check, mirroring WindowTransform/FillingTransform.

@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Jul 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d248d2]

Summary: ✅


AI Review

Summary

This PR adds an isCancelled() checkpoint to AggregatingInOrderTransform::consume() and a regression test for the many-distinct-keys cancellation hang. That fixes the specific "lots of tiny intervals in one chunk" repro, but reachable optimize_aggregation_in_order plans still have single-interval paths that can run a whole large chunk without another cancellation poll, so I would not merge it yet.

Findings

⚠️ Majors

  • [src/Processors/Transforms/AggregatingInOrderTransform.cpp:165-190] [dismissed by author -- https://github.com/Check for cancellation in AggregatingInOrderTransform #110104#discussion_r3564809873] [dismissed by author -- https://github.com/Check for cancellation in AggregatingInOrderTransform #110104#discussion_r3610173236] The new checkpoint only fires before each [key_begin, key_end) interval. In group_by_key mode that interval is defined by the sort-prefix comparison at lines 166-173, not by the full GROUP BY key, so one interval can still cover every row in a large chunk and then run straight through executeOnBlockSmall / mergeOnBlockSmall without any deeper cancellation poll (src/Interpreters/Aggregator.cpp:868-929). The same blind spot remains in the non-merge full-key path: if one full key dominates a large chunk, executeOnIntervalWithoutKey still processes the whole interval with no inner check (src/Interpreters/Aggregator.cpp:1496-1524). The author's "intervals are capped by the default block size" rebuttal does not hold here, because this PR's own regression test forces max_block_size = 200000000 and preferred_block_size_bytes = '100G', proving that AggregatingInOrderTransform can receive a much larger single chunk. A cancelled query can therefore still sit in one of these helpers until the entire interval finishes, which violates the advertised "stop promptly instead of running the whole chunk to completion" contract for skewed-prefix or skewed-key inputs.
    Suggested fix: thread is_cancelled through executeOnBlockSmall / mergeOnBlockSmall and the executeOnIntervalWithoutKey sibling, or split oversized intervals before calling those helpers.
Tests
  • ⚠️ Add a focused regression where the forced 40M-row chunk contains one huge interval instead of 40M single-row intervals: either a single full-key run, or a group_by_key shape where the sort prefix is shorter than the full GROUP BY key (for example the (a, c) / (a, c, d) plan family referenced in optimizeReadInOrder.cpp). The current test only proves the many-small-interval case.
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 AggregatingInOrderTransform.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 2/3 (66.67%) · 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 11, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 11, 2026
{
/// 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())

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.

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.

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.

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:

  1. 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 in optimizeReadInOrder.cpp:723-725 only affects which keys form a run inside a chunk; it cannot make one executeOnBlockSmall span more than the chunk. A single small-block aggregation over <= max_block_size rows completes in the millisecond range.

  2. Per-block is the established granularity for the aggregation execute path. The regular (non-in-order) AggregatingTransform aggregates an entire block via Aggregator::executeOnBlock (AggregatingTransform.cpp:993) with no inner-row isCancelled() 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 threads is_cancelled deeper (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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 92ea716

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. None is caused by this PR (which only adds if (isCancelled()) return; to AggregatingInOrderTransform plus a regression test).

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log infra (DatabasePostgreSQL::getTablesIterator Code 614 connection timeout to 192.0.2.1:5432, upgrade-check log leak) #109350 (ours, open)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error crash (LOGICAL_ERROR Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64' at FunctionBinaryArithmetic.h:3166, query SELECT n * 0.123; chronic across 11+ unrelated PRs + master, unrelated to this PR) a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260711-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the multiply Int256*Float64 LOGICAL_ERROR (Server died on the amd_llvm_coverage, old analyzer job): #109747 (ours, open).

Root cause is a concurrent EXCHANGE TABLES swapping a column's type (Float64<->Int256) between query analysis and header computation, so ActionsDAG partial-result evaluation runs multiply on an argument type it was not resolved for and trips the FunctionBinaryArithmetic::executeImpl2 "incorrect data types" LOGICAL_ERROR. Chronic trunk issue (11+ unrelated PRs + master), not caused by this PR. #109747 turns the mismatch into a recoverable TYPE_MISMATCH instead of aborting.

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,

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.

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.

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.

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]>
@groeneai
groeneai force-pushed the groeneai/aggregating-in-order-cancel branch from 7f2c68a to fd73840 Compare July 19, 2026 16:05
@groeneai
groeneai force-pushed the groeneai/aggregating-in-order-cancel branch from fd73840 to f502f1f Compare July 19, 2026 17:08
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]>
@groeneai
groeneai force-pushed the groeneai/aggregating-in-order-cancel branch from f502f1f to 303b5c5 Compare July 19, 2026 19:27
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 303b5c5

CI fully finished on this head (Finish Workflow SUCCESS). Our test 04512_aggregation_in_order_cancellation is OK on every normal job (amd_debug/tsan/asan parallel, arm_binary, arm_asan azure) and correctly SKIPPED on all flaky-check jobs (no-flaky-check) — the flaky-check latency-race mode is eliminated. Neither remaining red is PR-caused; each has a fixing-PR owner:

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Cannot start clickhouse-server (load table test_7.t_plt_rb_contains -> Code 722/695/27, txn metadata parse) flaky (part_loading_tree_rollback tests fabricate a raw txn_version.txt; 13 unrelated PRs / 0 master in 14d) #110999 (ours, open)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error crash (SIGABRT multiply Int256*Float64 partial-result type mismatch via concurrent EXCHANGE TABLES; 26 master + ~18 PRs in 14d) #109747 (ours, open) + #110048 (external, open)

Session id: cron:our-pr-ci-monitor:20260720-030000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 4/5 (80.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ceb9f64

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas: the per-table max_concurrent_queries throttle is keyed on query id, so one statement becomes several same-table reads that compete against themselves #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-053000

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3d248d210 with master 068ec6d2a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.30 MiB 689.29 MiB -3.01 MiB (-0.43%)

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 units

7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

groeneai and others added 3 commits August 12, 2026 21:55
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3d248d2

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - no failed checks on this head

177 leaf jobs: 159 OK, 18 skipped, 0 failed, 0 dropped. Praktika reports this head top-level OK
with zero DROPPED jobs, and every skip carries an explicit reason (not labeled with 'pr-performance' x6, reused from cache x3, no integration tests updates x3, Not affected by the changed files and not required x2, not labeled with 'ci-toolchain' x2, and two more), so the
matrix ran rather than being dropped. GitHub check conclusions agree: 160 success, 17 skipped, 0
failure. The CI database has no FAIL or ERROR row for this commit.

Session id: cron:our-pr-ci-monitor:20260813-123000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit 688c921 Aug 13, 2026
181 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 16, 2026
…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.
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.

6 participants