Repository navigation
Make arrayFold respect query cancellation and time limits - #108192
Conversation
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-13:20260622-163800 |
|
cc @rschu1ze could you review this? It makes |
|
Workflow [PR], commit [8c42974] Summary: ✅
AI ReviewSummaryThis PR makes Tests
Final Verdict |
The whole fold over a chunk runs inside a single FunctionArrayFold::executeImpl() call. The pipeline-level time/cancellation check only runs between chunks, so a fold over a very long array (e.g. range(number) with a result-growing lambda such as arrayPushFront) could not be interrupted: it ignored KILL QUERY and max_execution_time and kept running. This was observed in CI as a multi-thousand second uncancellable hang at gigabytes of memory. Capture the query's QueryStatus in the function and call checkTimeLimit() inside the two uninterruptible loops (the slice loop and the selector-build loop), so a cancelled or timed-out query terminates promptly. The slice loop performs a full lambda->reduce() per iteration, so the per-iteration check is negligible; the selector-build loop is a tight per-element loop and is checked periodically. Co-Authored-By: Claude Opus 4.8 <[email protected]>
af20725 to
748e1c2
Compare
…check checkTimeLimit() throws for KILL QUERY and for the throw overflow mode, but for the break overflow mode it returns false instead of throwing. The two in-function time checks called it only for side effects and discarded the bool, so a fold over a long array in break mode kept folding to completion and ignored max_execution_time. A fold has no meaningful partial result (a half-folded accumulator is a wrong value, not a smaller one), so turn the false return into a hard TIMEOUT_EXCEEDED stop, the same way FunctionBaseXXConversion handles its scalar conversions. Rework the regression test to fold a single long array in one executeImpl() (so the pipeline-level between-blocks check cannot interrupt it) and cover both throw and break modes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed in 9aa6ebb. Major (break mode ignored the false return): both in-function checks now go through a Tests: reworked |
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-8:20260622-185200 |
|
Pushed Root cause of the slowness: the test folded a single Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-5:20260622-221500 |
The previous regression test asserted serverError TIMEOUT_EXCEEDED for both
throw and break overflow modes over a constant range(N) array. That break
assertion was flaky: break mode's contract is to stop without an error
(ExecutionSpeedLimits::handleOverflowMode for BREAK returns false instead of
throwing), so the runtime pipeline absorbs the in-function stop and the query
ends cleanly. The assertion only passed when the analyzer constant-folded the
const array at analysis time, where the in-function throw propagates because
there is no pipeline to absorb it. CI randomizes enable_analyzer, so on the
runtime path the serverError never appeared and the flaky check failed on the
tsan build ("Expected server error code 159 but got no server error"). The
debug flaky check also failed because the test ran past the per-run time
budget when repeated 50 times.
Rewrite as a .sh test:
- Force the runtime (non-constant) path with range(materialize(toUInt64(N)))
so behavior no longer depends on analyzer constant folding.
- Use a result-growing lambda (arrayPushFront) over a 1000000-element array.
This is the original report's shape and is O(N^2): without the fix the fold
runs for minutes ignoring max_execution_time, so each query is wrapped in
`timeout 60` and the test fails (output differs) without the fix.
- throw mode asserts TIMEOUT_EXCEEDED; break mode asserts the query stops
without an error. Both stop in about a second with the fix.
- Tag long so the flaky check reduces the repeat count and exempts the per-run
time ceiling.
The arrayFold fix itself is unchanged.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
4be3bd3 to
eb4d799
Compare
|
Reworked the regression test (04408_array_fold_cancellation), which was itself flaky on the tsan and debug flaky checks. Root cause of the flakiness: the old test asserted serverError TIMEOUT_EXCEEDED for break mode over a constant range(N). But break mode is supposed to stop without an error (ExecutionSpeedLimits::handleOverflowMode returns false for BREAK), so the runtime pipeline absorbs the in-function stop and the query ends cleanly. The assertion only passed when the analyzer constant-folded the const array at analysis time (no pipeline to absorb the throw). CI randomizes enable_analyzer, so on the runtime path no error appeared -> "Expected server error code 159 but got no server error". New test (now a .sh):
The arrayFold fix itself is unchanged. |
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-3:20260622-221500 |
The previous comment said a break-mode timeout is 'turned into a hard stop here', which reads as a client-visible error and appears to contradict the regression test (which asserts break stops without an error). Clarify that we throw on the false (break) return to stop the runaway fold, and that in break mode the pipeline absorbs this timeout into a clean cancellation, so the query ends without a client-visible error and yields no rows. Behavior is unchanged; this is a comment-only edit. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-1:20260623-002200 |
The previous test folded a single range(1000000) array, which scatters into a million column shards and peaks at ~3.9 GiB while running for tens of seconds. Under the flaky check (the same test run many times in parallel) that blew the 180s per-run ceiling and the memory budget, so the check failed on amd_debug and amd_tsan even though the fix itself is correct. Fold range(120000) over four rows instead: the whole fold still happens in one block (so only the new in-function check, not the pipeline-level check, can stop it), but only four growing accumulators are live at a time, so the run stays under 30 MiB and about a second. Cover both the materialized (runtime) and constant array shapes to show break mode is a clean stop on both (arrayFold is not subject to constant folding, so the two shapes do not diverge).
Pre-PR validation gateThis push reworks only the regression test (
Also addressed the constant-folding review note in-thread: Session id: cron:clickhouse-worker-slot-1:20260623-015600 |
|
CI finished on
|
|
@groeneai, provide a fix for |
|
@alexey-milovidov on it, separate PR as you asked. Re-checked on current master. The live failure is
Root cause is the peak-memory path, not the CPU Fix plan, in a separate @groeneai PR:
|
|
@alexey-milovidov fix opened as a separate PR per your request: #108559. It skips the four |
…e_events under TSAN The four peak-memory tests (test_peak_memory_is_max_not_sum, test_peak_memory_reflects_udf_not_server, test_peak_memory_byte_seconds, test_reaped_child_memory_rolls_up) are flaky exclusively on Thread Sanitizer. PeakMemoryByteSeconds is sampled from /proc/<pid>/VmHWM across the UDF subtree on a best-effort ~5 ms throttle (UDFProcessSubtreeSampler). Under TSAN the scheduling skew and sanitizer memory bloat make that sampling non-deterministic over the test's one-row window, producing both directions of failure: an implied peak below the floor (children never sampled) and an inflated reading above the max-not-sum ratio. The metric is correct on every non-sanitizer build, where the assertions remain fully active and still catch a UDF that reports only the parent's memory. Skip only these assertions under Thread Sanitizer, matching the existing pattern in other memory/timing integration tests (test_fetch_memory_usage, test_hedged_requests). MSAN is already skipped. Requested by alexey-milovidov in PR ClickHouse#108192. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@groeneai, the unrelated failures have been fixed. Update the branch. |
Pick up upstream fixes for the previously-red unrelated CI lanes per @alexey-milovidov.
|
@alexey-milovidov done. Merged fresh master (f777405) into the branch; PR head is now |
|
@alexey-milovidov Investigated. Not arrayFold, not caused by this PR. That lane ( Evidence it is unrelated to this PR:
Session id: cron:clickhouse-worker-slot-3:20260629-004600 |
CI finish ledger — 2761bebEvery 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
The arrayFold cancellation source fix ( Session id: cron:our-pr-ci-monitor:20260629-020000 |
|
Updated the branch: merged fresh Resolved the remaining The two previously-red lanes are unrelated to this PR (which touches only
|
|
Updated the branch: merged fresh The sole non- |
| } | ||
|
|
||
| # A materialized array forces the runtime (non-const) path. | ||
| run throw "range(materialize(toUInt64(120000)))" "runtime" |
There was a problem hiding this comment.
This regression still never exercises the selector-build timeout poll added in arrayFold.cpp: numbers(4) × range(120000) produces only 480,000 nested elements, so (i & 0xFFFFF) == 0 fires only at i == 0. In practice the timeout is proved only by the slice-loop check, and a regression in the selector-loop call site would still merge green.
Please add one focused case where num_elements_in_array_col > 1,048,576 but max_array_size stays small (for example many one-element arrays). That keeps the slice loop cheap and makes the selector loop the load-bearing timeout path this PR also claims to fix.
There was a problem hiding this comment.
Good catch. I checked this with a probe binary that has the selector-loop checkQueryTimeLimit() removed (everything else identical to the fix):
- The check is reachable and works.
numbers(N)withmax_block_size = N+10givesarrayFolda single N-element block (blockSize()= N confirmed), so the selector-build loop runs N iterations in oneexecuteImpl. With the fix the query stops atmax_execution_timeplus at most one 2^20-element poll interval (N=80M debug: D=1.0 -> ~1.00s, D=2.0 -> ~2.3s). With the check removed the fold cannot stop during the selector build and only bails at the slice-loop backstop after the whole build finishes. - But it resists a robust, flaky-safe stateless assertion. Because the slice-loop backstop still throws
TIMEOUT_EXCEEDEDright after the (uninterrupted) selector loop, both the fixed and the broken build throw the same error; only the latency differs. Discriminating that needs atimeout Twrapper withwithfix_wall < T < regress_wall, and that window is not robust: the fix's stop time carries a one-poll-interval overshoot that grows under load (this box runs 32 build/test slots), so a fixed run occasionally overshoots into the broken run's range. Making the gap safe means making the broken build overshoot the wrapper by seconds, i.e. ~100M+ elements = >5GB/run (theSelector,scatterslices, and permutation arrays are all O(num_elements)). That brings back the multi-GB / >180s flaky-check failures this test was resized twice to avoid (current shape ~450MB). Smaller sizes make the selector loop too short to cross a deadline above startup and load noise.
Both loops call the same QueryStatus::checkTimeLimit(), already covered end to end by the slice-loop case, so I would rather not add a timing-fragile or memory-heavy case and risk the flaky check. If you prefer, I can add a coverage-only case that drives the selector loop past 2^20 and asserts the query is cancellable (guarding a future selector-phase hang, where the slice backstop is never reached) without a hard latency assertion. Let me know which you prefer.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/20 (90.00%) · Uncovered code |
…e_events under TSAN The four peak-memory tests (test_peak_memory_is_max_not_sum, test_peak_memory_reflects_udf_not_server, test_peak_memory_byte_seconds, test_reaped_child_memory_rolls_up) are flaky exclusively on Thread Sanitizer. PeakMemoryByteSeconds is sampled from /proc/<pid>/VmHWM across the UDF subtree on a best-effort ~5 ms throttle (UDFProcessSubtreeSampler). Under TSAN the scheduling skew and sanitizer memory bloat make that sampling non-deterministic over the test's one-row window, producing both directions of failure: an implied peak below the floor (children never sampled) and an inflated reading above the max-not-sum ratio. The metric is correct on every non-sanitizer build, where the assertions remain fully active and still catch a UDF that reports only the parent's memory. Skip only these assertions under Thread Sanitizer, matching the existing pattern in other memory/timing integration tests (test_fetch_memory_usage, test_hedged_requests). MSAN is already skipped. Requested by alexey-milovidov in PR ClickHouse#108192. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…fold-runaway Make arrayFold respect query cancellation and time limits
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
arrayFoldnow respects query cancellation andmax_execution_time. Previously a fold over a very long array (for examplearrayFold(acc, x -> arrayPushFront(acc, x), range(number), emptyArrayUInt64())) ran the whole fold inside a single function call and could not be interrupted, soKILL QUERYand time limits were ignored until the fold finished.Description
Found by the server-side fuzzer on PR #107680 (
Stress test (amd_asan_ubsan)Hung check), where the query below was already cancelled but kept running (elapsed 2709s, 1.6 GiB):Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107680&sha=3f23dfc85cace53649bd8ac14135dc2429aa2cd1&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29
Root cause:
FunctionArrayFold::executeImplfolds an entire chunk in one call. The only time/cancellation check is at the pipeline level between chunks (PipelineExecutor::finalizeExecution), so neither the slice loop nor the selector-build loop could be interrupted mid-fold.Fix: capture the query
QueryStatusin the function (same pattern ash3PolygonToCells) and callcheckTimeLimit()inside both loops. The slice loop performs a fulllambda->reduce()per iteration, so the per-iteration check is negligible; the selector-build loop is a tight per-element loop and is checked periodically.checkTimeLimit()handles bothKILL QUERYandmax_execution_time.Verified locally on a debug build: with the fix the regression test query throws
TIMEOUT_EXCEEDEDin ~1.5s; without the fix the same query runs ~15-17s (the full workload) before the between-chunks check fires. ExistingarrayFoldtests pass unchanged.Version info
26.7.1.446(included in26.7and later)