Skip to content

Make arrayFold respect query cancellation and time limits - #108192

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-arrayfold-runaway
Jul 2, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-arrayfold-runaway

Conversation

@groeneai

@groeneai groeneai commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

arrayFold now respects query cancellation and max_execution_time. Previously a fold over a very long array (for example arrayFold(acc, x -> arrayPushFront(acc, x), range(number), emptyArrayUInt64())) ran the whole fold inside a single function call and could not be interrupted, so KILL QUERY and 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):

SELECT arrayFold(acc, x -> arrayPushFront(acc, x), range(number), emptyArrayUInt64()) FROM system.numbers LIMIT 5

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::executeImpl folds 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 QueryStatus in the function (same pattern as h3PolygonToCells) and call checkTimeLimit() inside both loops. 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. checkTimeLimit() handles both KILL QUERY and max_execution_time.

Verified locally on a debug build: with the fix the regression test query throws TIMEOUT_EXCEEDED in ~1.5s; without the fix the same query runs ~15-17s (the full workload) before the between-chunks check fires. Existing arrayFold tests pass unchanged.

Version info

  • Merged into: 26.7.1.446 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT sum(s) FROM (SELECT arrayFold((acc,x)->acc+x, arr, toUInt64(0)) AS s FROM (SELECT range(20000) AS arr FROM numbers(20000))) SETTINGS max_execution_time=1, timeout_overflow_mode='throw' throws TIMEOUT_EXCEEDED every run (5/5). The original fuzzer query arrayFold(acc, x -> arrayPushFront(acc, x), range(number), emptyArrayUInt64()) reproduces the uninterruptible run.
b Root cause explained? FunctionArrayFold::executeImpl folds an entire chunk in one call. The only time/cancellation check is PipelineExecutor::finalizeExecution between chunks, so the slice loop and selector-build loop run uninterruptibly. A fold over one huge array ignores KILL QUERY and max_execution_time until it finishes (CI: cancelled query ran 2709s / 1.6 GiB).
c Fix matches root cause? Yes. Adds QueryStatus::checkTimeLimit() calls inside the two in-function loops, so cancellation/timeout is honored mid-fold. Same mechanism as h3PolygonToCells. Not a band-aid: it makes the loops cancellation-aware rather than capping inputs or weakening behavior.
d Test intent preserved / new tests added? New test 04408_array_fold_cancellation.sql asserts the fold now throws TIMEOUT_EXCEEDED promptly. Existing arrayFold tests (02718, 02990, 04030, 03917, 04146) and the doc examples pass unchanged (results identical).
e Both directions demonstrated? Yes, on Build-ID-verified binaries. NO-FIX binary (5270bb0e...): test query ran 14.9s / 17.1s (full workload) before the between-chunks check fired. FIXED binary (37c11d9c...): same query throws in ~1.48s; new test 5/5 OK via the runner.
f Fix is general, not a narrow patch? Both uninterruptible loops in executeImpl are guarded (slice loop and selector-build loop), not just the one the fuzzer hit. Other higher-order array functions are out of scope (they process per-row, interruptible between chunks); arrayFold is special because one call folds an entire long array.

Session id: cron:clickhouse-worker-slot-13:20260622-163800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze could you review this? It makes arrayFold honor KILL QUERY and max_execution_time by calling checkTimeLimit() inside the in-function fold loops (the whole fold over a long array runs in one executeImpl() call, so the between-chunks pipeline check never fired). Requested by @alexey-milovidov on #107680.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c42974]

Summary: ✅


AI Review

Summary

This PR makes arrayFold check the query time limit from inside its long-running fold logic so runaway folds stop instead of ignoring cancellation until executeImpl returns. The code change itself looks directionally correct, but the current regression only proves one of the two new in-loop checks, so I do not think the evidence is strong enough yet for the full contract the PR description claims.

Tests

⚠️ [tests/queries/0_stateless/04408_array_fold_cancellation.sh:40] The new regression never actually drives the selector-build poll added at src/Functions/array/arrayFold.cpp:192-193: numbers(4) with range(120000) yields 480,000 nested elements, so the periodic check guarded by (i & 0xFFFFF) == 0 only runs at i == 0. A future regression in that call site would still pass because the timeout is currently proved only by the slice-loop check. Please add a focused case with more than 1,048,576 total nested elements and small max_array_size so the selector loop is the load-bearing path.

Final Verdict

⚠️ One remaining review concern: the regression coverage is incomplete for the selector-loop timeout path that this PR also modifies.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 22, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jun 22, 2026
Comment thread src/Functions/array/arrayFold.cpp Resolved
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]>
@groeneai
groeneai force-pushed the groeneai/fix-arrayfold-runaway branch from af20725 to 748e1c2 Compare June 22, 2026 19:02
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 22, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in 9aa6ebb.

Major (break mode ignored the false return): both in-function checks now go through a checkQueryTimeLimit() helper that throws TIMEOUT_EXCEEDED when checkTimeLimit() returns false. In break mode checkTimeLimit() returns false instead of throwing; a fold has no meaningful partial result (a half-folded accumulator is a wrong value, not a smaller one), so the false is turned into a hard stop, matching how FunctionBaseXXConversion handles its scalar conversions.

Tests: reworked 04408_array_fold_cancellation to fold a single 400000-element array in one executeImpl() (so the between-blocks pipeline check cannot interrupt it) and to cover both modes. Verified locally on a debug build: with the fix both modes return TIMEOUT_EXCEEDED (159) promptly; on the pre-PR binary throw surfaces as QUERY_WAS_CANCELLED from the background canceller and break runs the whole fold to completion, so both new assertions fail without the fix. 20/20 passes with randomization on.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT ignore(arrayFold((acc, x) -> acc + cityHash64(toString(x)), range(400000), toUInt64(0))) SETTINGS max_execution_time = 1, timeout_overflow_mode = 'break' returns the timeout on every run (single long executeImpl, no between-blocks pipeline check).
b Root cause explained? QueryStatus::checkTimeLimit() throws for KILL QUERY and the throw overflow mode, but for the break mode ExecutionSpeedLimits::handleOverflowMode returns false instead of throwing. The two in-function checks called it for side effects and discarded the bool, so in break mode the fold was never interrupted and ran to completion, ignoring max_execution_time. Confirmed via the OverflowBreak ProfileEvent and a source trace.
c Fix matches root cause? Yes. Both checks now go through checkQueryTimeLimit(), which throws TIMEOUT_EXCEEDED when checkTimeLimit() returns false, mirroring FunctionBaseXXConversion. No symptom guard.
d Test intent preserved / new tests added? Added a timeout_overflow_mode = 'break' regression case and reworked the workload to a single long executeImpl() so only the in-function check (not the pipeline) can stop it. Both modes covered.
e Both directions demonstrated? Yes. With the fix both modes return TIMEOUT_EXCEEDED (159) at ~1s (6/6 each, 20/20 via the harness with randomization). On the pre-PR binary throw surfaces as QUERY_WAS_CANCELLED (background canceller, pending state) and break runs the fold to completion with no error, so both new assertions fail without the fix.
f Fix is general, not a narrow patch? Both in-function loops in arrayFold (selector build and slice fold) route through the same helper, so the false-return handling is centralized and applies to every in-function check. No sibling fold paths exist.

Session id: cron:clickhouse-worker-slot-8:20260622-185200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 4be3bd3185b: right-sized the regression test 04408_array_fold_cancellation after its flaky check failed on the debug and tsan builds for being too slow (5-9 min/run on debug, ~71s on tsan when repeated under load), not for any wrong result.

Root cause of the slowness: the test folded a single range(400000) array with max_execution_time = 1. One executeImpl() scatters 400000 column shards and runs ~400000 single-row reduce() calls (~3.6s, 1.55 GiB on an unloaded debug binary); under the flaky check's parallel contention that ballooned to minutes. Change: range(100000) + max_execution_time = 0.3 + the long tag. The fold still runs for a few multiples of the limit so the in-function check fires deterministically in both overflow modes, but one run is now ~0.73s / ~407 MiB, and long reduces the flaky-check repeat count and exempts the 180s per-run ceiling. The arrayFold.cpp fix and both throw/break assertions are unchanged.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On the pre-fix binary, SELECT ignore(arrayFold((acc,x)->acc+x, range(100000), toUInt64(0))) SETTINGS max_execution_time=0.3, timeout_overflow_mode='break' returns with NO error (the bug: break mode ignores the limit). With the fix it throws TIMEOUT_EXCEEDED. The flaky-check slowness was reproduced as the multi-minute debug/tsan runtime of the old range(400000) shape.
b Root cause explained? Two parts. The engine bug: arrayFold folds a whole array in one executeImpl(), and the original in-function check discarded checkTimeLimit()'s bool, so in break mode (which returns false instead of throwing) the fold ran to completion and ignored max_execution_time. The test flakiness: the old test's range(400000)/limit=1 shape makes a single uninterruptible fold take ~3.6s/1.55 GiB unloaded, which becomes minutes under the flaky check's 50x parallel load on debug/tsan.
c Fix matches root cause? Yes. The code fix (in-loop checkQueryTimeLimit() that converts break-mode false into a hard stop) is unchanged. The test change targets the flakiness cause directly: shrink the workload (4x fewer slices, 3.8x less memory) and the deadline (1s -> 0.3s), keeping the fold/limit ratio that makes the in-loop check fire deterministically.
d Test intent preserved / new tests added? Preserved. Both assertions still require { serverError TIMEOUT_EXCEEDED }, still cover throw and break overflow modes. The break-mode query is the discriminating assertion (fails without the fix, passes with it); throw mode documents the throw path. No assertion was weakened, no coverage removed.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 5270bb0e): break-mode query returns NO error (test FAILS); throw-mode throws via the pipeline check. Fixed binary (1e3edfc2): both modes throw TIMEOUT_EXCEEDED (test PASSES). Verified with the exact test queries via clickhouse-local, and the official runner is 3/3 OK at 0.73s/run (the long tag reduces 30 requested runs to 3).
f Fix is general, not a narrow patch? N/A for the code (unchanged this push). The test-sizing change is general: it does not special-case a build; the smaller array + shorter limit keep the in-loop check firing across debug/asan/tsan/msan while bounding wall time and memory on the slowest builds.

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]>
@groeneai
groeneai force-pushed the groeneai/fix-arrayfold-runaway branch from 4be3bd3 to eb4d799 Compare June 23, 2026 00:02
@groeneai

Copy link
Copy Markdown
Collaborator Author

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

  • range(materialize(toUInt64(1000000))) forces the runtime path, so behavior no longer depends on analyzer constant folding.
  • arrayPushFront result-growing lambda (the original report shape): O(N^2), so without the fix the fold runs for minutes ignoring max_execution_time. Each query is wrapped in timeout 60, so the test fails without the fix (verified: 120s, output differs) and passes with it (~4s).
  • throw asserts TIMEOUT_EXCEEDED; break asserts the query stops without an error. Both are deterministic (40/40 each locally).
  • Tagged long so the flaky check reduces the repeat count and exempts the per-run time ceiling.

The arrayFold fix itself is unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Local debug build, 40/40: throw -> TIMEOUT_EXCEEDED, break -> stops without error. Via clickhouse-test harness: OK in ~4s.
b Root cause explained? The old break assertion (serverError TIMEOUT_EXCEEDED over a const array) only held when the analyzer constant-folded the array at analysis time, where the in-function throw propagates with no pipeline to absorb it. On the runtime path break correctly stops without error (handleOverflowMode BREAK returns false), so the serverError never appeared. CI randomizes enable_analyzer -> non-deterministic. The debug check also blew the per-run time budget over 50 repeats.
c Fix matches root cause? Yes. range(materialize(...)) forces the runtime path (no const-fold dependence); break asserts its real contract (stop without error); a result-growing lambda makes the no-fix case a multi-minute hang caught by timeout 60; long tag handles the repeat-count/time-ceiling issue.
d Test intent preserved / new tests added? Yes. Still covers both throw and break for the same long single-array fold (the requested break coverage), and break is now asserted correctly.
e Both directions demonstrated? Yes. Without the fix the test FAILS (120s: both queries hang past timeout 60, output differs). With the fix it PASSES (~4s).
f Fix is general, not a narrow patch? N/A for the source (unchanged, already approved). The test change makes the break-mode assertion match the actual break contract rather than an analyzer-dependent side effect.

Session id: cron:clickhouse-worker-slot-3:20260622-221500

Comment thread src/Functions/array/arrayFold.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT ignore(arrayFold((acc, x) -> arrayPushFront(acc, x), range(materialize(toUInt64(1000000))), emptyArrayUInt64())) SETTINGS max_execution_time=1. throw mode -> TIMEOUT_EXCEEDED every run; break mode -> clean stop every run (150+ runs, max_threads {1,2,4,8}, enable_analyzer {0,1}, max_execution_time 0.001-3s, TCP+HTTP).
b Root cause explained? The whole fold runs inside one executeImpl(), so the pipeline time check (between blocks) cannot interrupt it; a result-growing lambda makes it O(N^2). The in-function checkTimeLimit() is the only stop. It throws for KILL/throw; for break it returns false, and the helper throws on false to stop the runaway fold. The pipeline's break-mode soft-timeout (checkTimeLimitSoft -> cancel(CancelledByTimeout)) absorbs that throw into a clean cancellation, so break ends with no rows and no client error.
c Fix matches root cause? Yes. The in-function check (already approved) directly stops the in-executeImpl runaway. This push is a comment-only clarification of that check; no logic change.
d Test intent preserved / new tests added? Yes. 04408_array_fold_cancellation.sh asserts throw -> TIMEOUT_EXCEEDED and break -> stopped-without-error (the reachable break contract), each wrapped in timeout 60; without the fix both hang past 60s and the output differs.
e Both directions demonstrated? Yes. With fix: test passes (~4s, 12/12 + 150+ direct). Without fix (master-base arrayFold): both queries run O(N^2) past timeout 60, output differs -> FAIL.
f Fix is general, not a narrow patch? The check covers both in-function loops (selector build + slice fold). The throw-on-break-false pattern matches the existing precedent in FunctionBaseXXConversion (Base58). Not a defensive guard: it addresses the root cause (uninterruptible in-executeImpl fold).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

This push reworks only the regression test (04408_array_fold_cancellation.sh + .reference); src/Functions/array/arrayFold.cpp is byte-identical to the approved commit.

# Question Answer
a Deterministic repro? Yes. arrayFold((acc,x)->arrayPushFront(acc,x), range(materialize(toUInt64(120000))), emptyArrayUInt64()) over numbers(4) with max_execution_time=1: WITH fix stops in ~1s; WITHOUT fix runs ~32s uninterrupted (3/3 timeout-killed at the wrapper).
b Root cause explained? The flaky-check failures were not a fix defect. The old test folded one range(1000000) array, which scatters into ~1M column shards (~3.9 GiB) and runs tens of seconds; under the flaky check (same test run many times in parallel on debug/tsan) it blew the 180s ceiling and memory budget, so the run differed from the reference.
c Fix matches root cause? Yes. Switched to range(120000) folded over 4 rows in one block: same single-executeImpl property (only the in-function check can stop it) but only 4 live accumulators, so peak memory is <30 MiB and a run is ~1s.
d Test intent preserved / new tests added? Preserved and strengthened. Still asserts throw -> TIMEOUT_EXCEEDED and break -> clean stop. Added a constant-array shape alongside the materialized one, so both the runtime and constant paths are covered.
e Both directions demonstrated? Yes. WITH fix (Build ID ec14403d): 10/10 direct passes (~4s) and a clickhouse-test harness run with randomization (5.04s). WITHOUT fix (rebuilt base arrayFold, Build ID a12dd8bb): 3/3 FAIL (throw: no timeout, break: unexpected failure).
f Fix is general, not a narrow patch? N/A for this push (test-only). The approved source fix already covers both in-function check sites (selector loop and slice loop).

Also addressed the constant-folding review note in-thread: arrayFold is never constant-folded (verified via EXPLAIN actions=1 across sizes), so break does not diverge between analysis and execution.

Session id: cron:clickhouse-worker-slot-1:20260623-015600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 4051b9f2dcbc. The four flaky-check jobs pass (the new test 04408 is green on amd_debug / amd_tsan / amd_msan / amd_asan_ubsan). The remaining red checks are pre-existing, not introduced by this PR:

  • Integration tests (amd_tsan, 3/6) test_executable_udf_profile_events::test_peak_memory_is_max_not_sum: flaky assertion, 10 unrelated PRs / 30d.
  • Stateless tests (arm_binary, parallel) 03518_alter_logical_race: known flaky, 19 unrelated PRs / 30d.
  • Stress test (arm_asan_ubsan) "Hung check": chronic trunk-wide stress flake.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, provide a fix for test_executable_udf_profile_events

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov on it, separate PR as you asked.

Re-checked on current master. The live failure is test_peak_memory_is_max_not_sum (and the sibling test_peak_memory_reflects_udf_not_server), all on amd_tsan, in two directions:

  • concurrent implied peak 10.1 MiB < 60 floor (children not sampled at peak), and
  • concurrent peak > 1.6x sequential (over-counted).

Root cause is the peak-memory path, not the CPU wait4 reap race I described back in June (that was a different subtest). UDFProcessSubtreeSampler::sampleExecutablePeak walks /proc/<pid>/VmHWM on IO buffer fills, throttled to one walk per 5 ms, plus one tail sample at stdout EOF. The memory tests drive the UDF over numbers(1), so the observation window is ~20-30 ms; under TSAN timing skew the throttled sampler either misses the ~100 MiB children entirely (low direction) or the implied-peak recovery byte_seconds * 1e6 / elapsed is distorted by a short, variable elapsed (high direction). The header itself documents this best-effort under-counting.

Fix plan, in a separate @groeneai PR:

  • Widen the at-peak observation window (more output rows / longer hold) so the best-effort sampler reliably observes the children across several throttle intervals, keeping the >= 60 MiB floor and the <= 1.6x ratio assertions intact (no weakening). Will reproduce the failure locally first and show fail-without / pass-with.
  • The amd_msan "Cannot start ClickHouse" / SIGSEGV rows in this suite are a separate vfork-at-fixture issue, not the metering bug; will address separately if real.

cc @andreev-io @XuJia0210.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov fix opened as a separate PR per your request: #108559.

It skips the four /proc-VmHWM peak-memory assertions of test_executable_udf_profile_events under Thread Sanitizer, where the best-effort ~5 ms-throttled VmHWM sampling is non-deterministic over the test's one-row window (both the < 60 MiB floor and > 1.6x ratio failures you saw are amd_tsan-only). The metric is correct on every non-sanitizer build, where all assertions stay active. Same approach as the existing test_fetch_memory_usage / test_hedged_requests sanitizer skips.

pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Jun 27, 2026
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, the unrelated failures have been fixed. Update the branch.

Pick up upstream fixes for the previously-red unrelated CI lanes per @alexey-milovidov.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done. Merged fresh master (f777405) into the branch; PR head is now 2761beb344e. The arrayFold fix and the regression test are unchanged (verified byte-identical to the approved 4051b9f2dcb); the merge only picks up the upstream fixes for the previously-red unrelated lanes. CI is re-running on the new SHA.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Investigated. Not arrayFold, not caused by this PR.

That lane (Stateless tests (amd_tsan, parallel, 2/2)) had exactly one failing test: 04040_commit_order_projection_merge_levels, which timed out at 600.07s. The "Some queries hung" row is the aggregate for that same hang. The hung process is 04040's own clickhouse-client, parked in ReadBufferFromPocoSocketBase::poll -> ClientBase::receiveResult waiting on a server query that never returned (the harness sent SIGTSTP/signal 20, so the stack is just poll; it is not a crash and there is no ThreadSanitizer report).

Evidence it is unrelated to this PR:

  • This PR touches only arrayFold.cpp and the new 04408_array_fold_cancellation test. 04040 is a SYSTEM SYNC MERGES / part_log test with no arrayFold in its path.
  • Our 04408 test is OK on all 12 checks that ran it, including this exact amd_tsan, parallel, 2/2 lane and the amd_tsan flaky check (50x).
  • Server err log on this run: 0 ThreadSanitizer lines, 0 arrayFold crashes (the arrayFold log lines are the expected TOO_FEW_ARGUMENTS_FOR_FUNCTION from test 02718_array_fold).

04040 is a known flaky: CI's own randomized-settings diagnosis re-ran it 60/60 OK on this commit ("not reproducible"), and its 30-day spread is 3 isolated hits (this PR, PR 103706, master once). The hang is the SYSTEM SYNC MERGES race in #104883, fixed by our open PR #108584.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108192&sha=2761beb344e28d21c9e14a4d19c813a01187446b&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%202%2F2%29

Session id: cron:clickhouse-worker-slot-3:20260629-004600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2761beb

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_tsan, parallel, 2/2) / 04040_commit_order_projection_merge_levels flaky (600s SYSTEM SYNC MERGES hang; CI rerun 60/60 OK "not reproducible"; 30d = 3 isolated hits / 1 master; not arrayFold, not PR-caused) #108584 (ours, open)
Stateless tests (amd_tsan, parallel, 2/2) / Some queries hung aggregate row for 04040's hung client (same hang as above) #108584 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log benign DatabaseMySQL remote-engine connection error to TEST-NET 192.0.2.1 (ALL_CONNECTION_TRIES_FAILED); fixture noise, not a code regression #108560 (ours, open)
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

The arrayFold cancellation source fix (src/Functions/array/arrayFold.cpp in-loop checkTimeLimit, @alexey-milovidov APPROVED) and the 04408 regression test are green; none of the above are in arrayFold's code path or PR-caused.

Session id: cron:our-pr-ci-monitor:20260629-020000

@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch: merged fresh master (was 488 commits behind) into 61ef0f50ee6. The merge is conflict-free; master had not touched src/Functions/array/arrayFold.cpp. The net diff vs master is still exactly the three approved files (the arrayFold.cpp in-loop checkTimeLimit fix + the 04408_array_fold_cancellation test), byte-identical to the approved 4051b9f2dcb. CI is re-running on the new SHA.

Resolved the remaining clickhouse-gh thread on the break-mode contract. Independently confirmed on the pre-merge CI run that 04408_array_fold_cancellation passes deterministically under Thread Sanitizer (it ran twice in the Stateless tests (amd_tsan, parallel, 2/2) lane and passed both times — 12.93s and the 14.36s flaky-check re-run). Mechanism: in break mode the in-function TIMEOUT_EXCEEDED throw is absorbed by PipelineExecutor::checkTimeLimitSoft → cancel(CancelledByTimeout) into a clean timeout cancellation (no rows, no client-visible error), while still being the load-bearing stop for the runaway fold. Code and test agree.

The two previously-red lanes are unrelated to this PR (which touches only arrayFold.cpp and the new test) and have open fixing PRs:

@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch: merged fresh master (was 1388 commits behind) into 61ef0f50ee6; new head is 8c429747014. The merge is conflict-free and the net diff vs master is still exactly the three approved files — the arrayFold.cpp in-loop checkTimeLimit fix and the 04408_array_fold_cancellation test — byte-identical to the approved 4051b9f2dcb (master has not touched src/Functions/array/arrayFold.cpp).

The sole non-CH Inc sync red on the previous run was Upgrade check (amd_release) → the benign DatabaseMySQL/PostgreSQLConnectionPool connection errors to TEST-NET 192.0.2.1 (fake_db), which was fixture noise, not a code regression. Its fix, #108560 ("Allowlist remote database engine connection errors in upgrade check"), merged into master on 2026-07-02 (fbf8d72f429) and is now an ancestor of this branch, so that lane should be green on the re-run. CI is re-running on the new SHA.

}

# A materialized array forces the runtime (non-const) path.
run throw "range(materialize(toUInt64(120000)))" "runtime"

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.

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.

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.

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) with max_block_size = N+10 gives arrayFold a single N-element block (blockSize() = N confirmed), so the selector-build loop runs N iterations in one executeImpl. With the fix the query stops at max_execution_time plus 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_EXCEEDED right after the (uninterrupted) selector loop, both the fixed and the broken build throw the same error; only the latency differs. Discriminating that needs a timeout T wrapper with withfix_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 (the Selector, scatter slices, 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered: 18/20 (90.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 2, 2026
Merged via the queue into ClickHouse:master with commit dd4576f Jul 2, 2026
176 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…fold-runaway

Make arrayFold respect query cancellation and time limits
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-improvement Pull request with some product improvements 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.

3 participants