Skip to content

Check for cancellation while replacing substrings - #112483

Merged
PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-replace-cancellation-107941
Aug 1, 2026
Merged

PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-replace-cancellation-107941

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes replaceOne, replaceAll, replaceRegexpOne and replaceRegexpAll ignoring max_execution_time and KILL QUERY. A single call now checks for cancellation while it works, so a long-running replacement over a large value or a large number of rows stops instead of holding a server thread until it finishes. Such a call has no partial result to return, so under timeout_overflow_mode = 'break' it raises the deadline as an error: always when constant-folded, and in the pipeline whenever this checkpoint is reached before the executor's between-block check, which still stops the query silently.

Description

Related: #107941

The four replace* functions had no cancellation checkpoint, so one call ran to completion however
long it took. The time limit is only tested between pipeline blocks, and with constant arguments the
function runs during query analysis, before any pipeline exists. On master a debug build runs
replaceRegexpAll over a folded 200 MB value with max_execution_time = 1 to completion, then reports
Code: 159 with no elapsed time at all because the deadline was never observed. The overshoot is
unbounded in the input, and the same shape is equally unstoppable in the pipeline (70 s over on 200k
rows), so this is a missing in-function check rather than anything specific to constant folding. Same
defect class as the merged #111909, fixed the same way.

FunctionStringReplace now builds one cancellation callback per call, and every unboundedly-iterating
loop in both implementations charges a throttled budget against it. One RE2::Match or memcpy still
runs to completion, so no absolute bound is claimed; what is removed is the unbounded accumulation.

Under timeout_overflow_mode = 'break' an uninterruptible replace* in the pipeline used to be
stopped by the executor's soft check with no client-visible error. This checkpoint cannot return a
partially rewritten string, so it raises TIMEOUT_EXCEEDED instead, as arrayFold and base58Decode
already do. Which checkpoint wins depends on build speed, so such a query may now report the deadline
where it used to end quietly; both are correct stops.

This addresses 2 of the 30 hung-check artifacts of #107941, so it stays referenced, not closed.

Mechanism and validation

Three unconditional checks bracket the dispatch: before and after expanding a constant argument, and on
the single exit path, covering the seven bulk-copy fast paths that return without searching. The budget
counts iterations rather than bytes, since one iteration can cost a full match attempt while touching
almost no data. Resolving the query per call, rather than capturing it, means a replace* stored in a
key, index or TTL is bounded by the query that runs it.

New test 04650_replace_cancellation.sh: 24 assertions bounding the elapsed time the server reports,
over folded and pipeline calls, both haystack types, constant and per-row needles and replacements,
empty needles, First and All, interpreted and JIT matchers, throw and break modes, KILL QUERY,
and a stored PARTITION BY run by an INSERT. Unfixed these report 2.4 s to 21 s, or nothing at all.

With the five files reverted, 23 of the 24 reference lines differ on Debug and on an unsanitized
-O3 build, 20 under TSan; the only line that cannot differ is the leak guard, and each is proven live
by its own mutation. Four further mutations each delete one mechanism's charges and redden that case
only. 50/50 passes on Debug and -O3; every flavour matches the reference; 0 TSan reports.

Release build, interleaved per shape, 12 iterations, best/mean ms, master -> fix: 1-byte replaceAll
283/305 -> 288/303; literal fallback 1433/1471 -> 1423/1467; regexp fallback 1663/1713 -> 1667/1759;
7-byte replaceAll 426/476 -> 407/438.

Five charged sites are documented as not asserted rather than implied covered, each bounded by what one
call may hold under the 5 GiB profile. Tags: no-msan (that build has no embedded compiler, so the JIT
case asserts nothing there), no-parallel (the leak case reads a global metric), no-coverage (per-test
coverage only, whose cost is bursty; the 21 of 24 lines it covered are covered elsewhere).

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 8 rounds, 5 blockers and 20 majors fixed, 3 refused with measurements

An internal cold review plus an adversarial second-model gate ran over this PR for eight rounds before
it was opened. Running totals: 5 blockers and 20 majors agreed and fixed, 3 refused with evidence.
The last two rounds touched only the test's oracles; the source has been unchanged since round 6.

Agreed and fixed (selected)

A stored replace* asked the wrong query about its deadline. The function instance built while a
key, skip index or TTL expression is analysed outlives that statement and is later executed by
unrelated queries, so a query captured at construction is both the wrong deadline to enforce and,
held alive, a permanent CurrentMetrics::QueryNonInternal leak. The query is now resolved from the
executing thread per call. A stored PARTITION BY went from 10363 ms to 1004 ms under an INSERT's own
max_execution_time = 1, and the test asserts the leak side as a zero delta.

A byte-denominated budget was blind to the cheapest loop. An empty regexp match advances one byte
and can execute zero instructions and write nothing, so an 8 MiB byte budget permitted about 8.4 M
iterations between checks. Measured at a stable 2.0 M iterations/s, a 300 MB haystack ran 149748 ms
against a 1 s deadline. The budget now counts loop iterations, with bytes charged on top.

One match can carry an unbounded instruction list. createInstructions has no bound on the list
length and both substitution loops replay it in full per match, so charging only after the loop left a
single match uninterruptible: 8775 ms at 20000 capture references, 26586 ms at 60000. The charge moved
inside both loops, accumulated and flushed in chunks.

The JIT case's anti-vacuity guard could be satisfied by a different JIT. It read
CompiledExpressionCacheCount, which four independent writers share, and the case's own sum is
itself compilable while the harness randomizes the aggregate-JIT settings. Replaced by the
regexp-specific CompileRegexpFunction event this PR adds, read back for that case's own query_id,
with the other three JITs pinned off and USE_EMBEDDED_COMPILER asserted from system.build_options.

The compile oracle was vacuous under a fixed test database. The stress runner gives some threads a
fixed --database, so the derived query_id is constant across repeats and a sum over
system.query_log answered with an earlier run's compile. Reproduced, reporting a compile on two
passes that compiled nothing. Now argMax(..., event_time_microseconds), verified in both directions.

Noted, not blocking

The flaky-check repeat count in a comment was wrong in both the number and the mechanism: a test
tagged both long and no-parallel runs 5 times, not 25. Corrected; the remedy holds regardless,
because the compile threshold is 3.

Five charged sites are documented as not asserted rather than implied covered. Each is bounded by what
one call may hold under the 5 GiB test memory profile, so no workload that fits can make them
overshoot, and splitting the work across blocks hands the query to the pipeline's own between-block
check instead.

Refused, with measurements

"The compile event does not prove the JIT loop ran." The mechanism cited is accurate: the event is
incremented before the compiled holder is constructed, and a later failure yields an empty matcher that
falls back to the interpreted loop. The conclusion does not follow, because the proof does not rest on
the event. A mutation deleting only the four budget charges inside processStringJIT, leaving the four
sibling charges in the interpreted processString intact, moved exactly one reference line: that
case's cancellation verdict. That is reachable only if the JIT loop executed, since a discarded handle
would have left the untouched interpreted charges bounding the query and the line green. The suite
therefore already asserts dispatch, by observing the JIT loop's own instructions rather than a counter
upstream of them, and a second event at the dispatch point would be strictly weaker.

A request for arm_binary measurements alongside amd_binary was declined on the architecture
half: nothing in the diff is architecture-conditional, and the script's flavour detection reads
system.build_options, which is not either. The residual substance was margin rather than ISA, and
that was answered by re-measuring both arms at the final sizes.

A no-msan gap I raised against myself and then refuted. The stress job ignores no-<build> tags
and does not pass --no-long, so this test does run under the MSan stress flavours, where the JIT case
would print its no-compiler branch against a reference expecting a compile. The consequence chain stops
there: that job collects the functional-test exit codes and never acts on them, and over 21 days it has
reported no per-test row for any stateless test at all. No red, and nothing asserted elsewhere is
falsely greened.

Session id: cron:clickhouse-review-slot-48:20260729-190100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Question Answer
a Deterministic repro? Yes. SELECT length(replaceRegexpAll(repeat(repeat('1', 1000000), 200), '[0-9]{1,3}', 'x')) SETTINGS max_execution_time = 1 runs to completion and reports the deadline with no elapsed time at all, on demand, with no fuzzer and no server (clickhouse local). 24 assertions, each reproducing on demand.
b Root cause explained? Yes. Neither replace* implementation had any cancellation checkpoint (grep -c 'cancel|checkTimeLimit' on both headers: 0), so one call runs to completion; the time limit is only tested between pipeline blocks, and with constant arguments the call happens during analysis where no pipeline exists. The filed premise that the plan-time layer lacks a cancellation channel is refuted by measurement: a function that carries an in-function check (base58Decode) is cancellable while folded, and the pipeline is equally blind without one (70 s overshoot on 200000 rows).
c Fix matches root cause? Yes. The check is added at the only layer that can interrupt a single processString call. No input-size limit (a 400 MB replaceAll is legitimate), no widened bound, no weakened assertion.
d Test intent preserved / new tests added? Yes. New test with 24 assertions, one per code path; no existing test changed or weakened; neighbouring replace* stateless tests re-run green. Five further charged mechanisms are documented in the test as not assertable rather than shipped with a case that passes either way: three are bounded by the bytes a single call may hold, so under the 5 GiB stateless memory profile the most work one call can do is below the deadline itself, and spreading the work over several blocks hands the query to the pipeline's own between-block check instead; the two FixedString offset loops sit in identity and empty-needle branches whose cost is purely the row count, and the largest row set that fits is of the same order as the bound.
e Demonstrated in both directions? Yes, on every build flavour the test runs on, each rebuilt from a tree with the five changed source files reverted to master. With the change the reference is reproduced byte for byte on every one. Reverted, the reference lines that differ are 23 of 24 on a Debug build, 22 of 24 on an unsanitized -O3 build, and 20 of 24 under ThreadSanitizer: overshoots of 2.3 s to 270 s, or the deadline never being observed at all. One line cannot differ on any flavour: it guards against reintroducing a query status captured at construction, so it has no master-side reproduction (master captures nothing) and is proven instead by a mutation that does capture one, retaining one query state per table (six tables: +6 against +0). The line asserting that the JIT matcher was really compiled does differ on the Debug revert, because the ProfileEvent it reads is itself part of this change; it is separately proven by a mutation that deletes only that event's increment and reddens exactly that one line. The remaining shortfall is flavour-specific and documented in the test rather than tuned away: two timing cases are already bounded on ThreadSanitizer by a checkpoint that exists on master too (reverted, one of them needs 37 s of CPU to complete but reports 2.6-3.1 s under a 1 s deadline). The per-test coverage flavour is tagged no-coverage: there the instrumentation's cost is bursty and input-independent (the same query, byte-identical work and peak memory, spanning 0.19 s to 2.4 s of CPU), so two cases had a fixed side that crossed the bound and no bound sizes that away - measured on that flavour before skipping it, the reverted tree still differed on 21 of 24 lines, and every line it covered is also covered by Debug, by the optimized build or by ThreadSanitizer. Each mechanism was additionally checked by deleting only its own charges and confirming that its case, and no other, reddens; for the JIT matcher that mutation reddens exactly one reference line. The test passes 50 out of 50 runs on the Debug build - each run under a fresh random draw of the JIT settings the harness randomizes - and 50 out of 50 on the -O3 build.
f General across code paths? Yes. All four SQL functions, both implementations, all ten vector entry points, both match loops (interpreted and JIT), both substitution loops, all per-row loops including the two FixedString offset-fill loops, the replacement-parsing helpers, the trivial-pattern fallback, and all seven bulk-copy fast paths, the last covered structurally by one check on the dispatcher's single exit path so a future eighth is covered too. A stored key, index or TTL expression is covered too: the query is resolved per call from the executing thread, so an INSERT that has to evaluate a stored PARTITION BY replaceRegexpAll(...) stops at its own deadline (1001-1125 ms against 1 s, on each of the four flavours measured) where before it ran for 6.5 s to 217 s.
g Generalizes across inputs? Yes. String and FixedString haystacks, all five constness combinations, empty needle, empty haystack, empty capture group, empty replacement, one-byte needle and replacement, a replacement far larger than the match, a replacement of 200000 capture references, a pattern matching the empty string at every position, a never-matching needle, needle and replacement varying per row, 1 to 1000000 rows, single values of up to 600 MB, both overflow modes, and KILL QUERY. Each is a separate test case.
h Backward compatible? Yes. No new setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry. The only behaviour change is that a query which previously ran past its deadline now reports TIMEOUT_EXCEEDED, which is the documented contract of max_execution_time.
i Invariants and contracts preserved? Yes. Output is unchanged: the budget only counts, and the chunked one-byte scan performs the same per-byte work in 64 MiB slices; offset bookkeeping is untouched. No new mutable state at all: the function object holds no query-lifetime state, the query is resolved per call from the executing thread, and the budget is a stack local of one call, so the shared-IFunction-across-pipeline-streams race that a per-object budget would have introduced cannot occur; a ThreadSanitizer run of the new test reports nothing. Resolving per call rather than capturing at construction is what keeps an instance stored in table metadata from consulting, or retaining, a query other than the one executing it - the latter owns metric increments released only on destruction. Resolution uses getProcessListElementSafe, which yields {} rather than throwing when nothing is set, and the resolved pointer is a local that outlives every use of the callback. Every added parameter is defaulted, so no other caller changes behaviour.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @Ergus, could you review this? The four replace* functions had no cancellation checkpoint, so a single call ran to completion however long it took: the time limit is only tested between pipeline blocks, and with constant arguments the call happens during query analysis where no pipeline exists yet. This adds one callback per call plus a throttled work budget in every unboundedly-iterating loop of both implementations.

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

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c60294e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
04648_geohashes_in_box_cancellation FAIL cidb IGNORED

AI Review

Summary

This PR adds per-call cancellation checks and throttled work accounting to the replaceOne / replaceAll / replaceRegexpOne / replaceRegexpAll execution paths, including stored-expression execution and the JIT regexp path, and it adds a broad regression test matrix around folded, pipeline, KILL QUERY, and stored-expression cases. I did not find a new correctness or safety regression in the current diff, and the current CI report for PR 112483 is green.

Findings

💡 Nits

  • [src/Core/Settings.cpp:3290] [dismissed by author -- https://github.com/Check for cancellation while replacing substrings #112483#discussion_r3686684259] The PR makes replace* another concrete case where timeout_overflow_mode = 'break' can surface TIMEOUT_EXCEEDED instead of silently returning a partial result when there is no meaningful partial value to return, but the structured timeout_overflow_mode docs still promise that break will always "stop executing the query and return the partial result". This mismatch predates the PR, but the new behavior makes it user-visible on another function family; a follow-up should narrow the docs to the cases where a partial result actually exists.
Final Verdict

Non-blocking. No new inline review comments on the current head; the only remaining issue I would keep is the existing timeout_overflow_mode documentation mismatch above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
Comment thread src/Functions/ReplaceRegexpImpl.h Resolved
Comment thread src/Functions/ReplaceStringImpl.h Resolved
@PedroTadim PedroTadim self-assigned this Jul 30, 2026
. "$CURDIR"/../shell_config.sh

# The `replace*` functions had no cancellation checkpoint, so one call ran to completion however long it
# took, ignoring `max_execution_time` and `KILL QUERY`: those are only checked between pipeline blocks,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai trim all these comments

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.

Trimmed in 1c965fb.

The test file goes from 485 lines to 286: the header keeps one clause per tag, the sizing rationale is one paragraph instead of eight, and each case keeps only the constraint that makes it non-vacuous. I did the same to the comments in the four source files, since the same reasoning was repeated there. Everything I cut is in the commit message and the PR description.

Comment-only: all 143 executable lines of the test and every non-comment line of the source files are byte-identical, the reference file is untouched, and the test still passes. I also squashed the branch to one commit.

The four `replace*` functions had no cancellation checkpoint, so one call ran to
completion however long it took, ignoring `max_execution_time` and `KILL QUERY`:
those are only checked between pipeline blocks, and with constant arguments the
function runs during query analysis, before any pipeline exists.

`FunctionStringReplace` now builds one cancellation callback per call, and every
unboundedly-iterating loop in both implementations charges a throttled budget
against it. The budget counts iterations rather than bytes, because one iteration
can cost a full match attempt while touching almost no data. The query is
resolved from the executing thread rather than captured, so a `replace*` stored
in a key, index or TTL is bounded by the query that runs it.

One `RE2::Match` or `memcpy` still runs to completion, so no absolute bound is
claimed; what is removed is the unbounded accumulation. Under
`timeout_overflow_mode = 'break'` such a call has no partial result to return, so
it raises the deadline as an error, as `arrayFold` and `base58Decode` do.

Adds `04650_replace_cancellation.sh` and the `CompileRegexpFunction` profile
event the test uses to assert that the JIT case really compiled its pattern.

Related: ClickHouse#107941
@groeneai
groeneai force-pushed the fix-replace-cancellation-107941 branch from 0f82040 to 1c965fb Compare July 30, 2026 18:08
Comment thread src/Functions/ReplaceStringImpl.h Resolved
The clang-tidy build fails with six readability-static-accessed-through-instance
errors, and .clang-tidy sets WarningsAsErrors to '*', so this blocks CI.

bytes_per_unit and units_per_instruction_charge are static constexpr members of
ReplaceCancellationBudget, and the substitution loops read them through the
budget instance. Name the class instead. The values and the arithmetic are
unchanged, so this only affects how the constants are spelled.

Reproduced locally with the rule alone on replaceRegexpAll.cpp: six errors at
the same line and column as CI before, zero after, and zero for the whole
.clang-tidy config on the translation units of both changed headers.
04650_replace_cancellation still passes.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1c965fb

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
Build (arm_tidy) / Build ClickHouse PR-caused: 6 readability-static-accessed-through-instance errors in src/Functions/ReplaceRegexpImpl.h at 210:68, 211:47, 219:77, 315:68, 316:47, 324:77, and .clang-tidy sets WarningsAsErrors: '*' PR-caused, fixed in this PR @ 55c9013
Finish Workflow / new_tests_check.py Consequence of the above: the tidy failure DROPPED all 4 per-arch Bugfix validation jobs, so the hook reports "No per-arch Bugfix Validation job validated the bug" PR-caused, fixed in this PR @ 55c9013

174 of 174 check-runs completed at this commit (4 success, 168 skipped, 2 failure); no third failure and
nothing still running.

The two rows are one event. Build (arm_tidy) failed first, which dropped every downstream job
including the four Bugfix validation jobs, and Finish Workflow then failed because none of them had
validated the bug. There is no infrastructure signature in the job log: 0 hits for Job killed,
Connect timeout on endpoint, GetParameters or Bad Gateway, and the only errors are the six
clang-tidy diagnostics in a file this PR adds to.

bytes_per_unit and units_per_instruction_charge are static constexpr members of
ReplaceCancellationBudget and were read through the budget instance. The fix names the class
instead; values and arithmetic are unchanged.

Verified locally with the rule alone on replaceRegexpAll.cpp: six errors at the same line and column
as CI before the change, zero after, and zero for the whole .clang-tidy config on the translation
units of both changed headers. 04650_replace_cancellation passes, and 5 randomized runs of it are
clean (the long tag makes --test-runs 50 execute five times by design).

Session id: cron:clickhouse-maint-slot-13:20260730-185700

groeneai and others added 3 commits July 30, 2026 20:05
`CompileRegexpFunction` was incremented as soon as the module compiled, before
the holder took ownership and before the compiled-expression cache inserted the
entry. Both of those steps allocate, and any throw between the compilation and
the caller receiving the matcher is swallowed by `getRegexpJITMatcher`, which
logs the failure and returns an empty matcher so the caller falls back to the
interpreted loop. The event had already been counted, so the profile described a
matcher the query never used, and the regression test reads that event to decide
whether case 22 exercised the JIT loop.

The increment now happens after that catch, guarded by a flag the cache loader
sets, so it counts a compilation that actually reached the caller and stays
silent on a cache hit, where nothing is compiled.

Measured three ways: a fresh compile counts 1, a repeat of the same pattern
against a warm cache counts 0, and with a throw injected at the cache insertion
the event reads 0 while the RE2 fallback is logged.

Co-Authored-By: Claude Fable 5 <[email protected]>
The case 22 note still said the event is incremented in `compileMatcher`, which
stopped being true when the increment moved to `getRegexpJITMatcher`. Comment
only; every executable line of the test is unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
It restated the reasoning that belongs in the commit message. What a reader
needs at that line is the constraint on where the statement may live.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Functions/FunctionStringReplace.h Resolved
…they guard

Both stored-expression cases passed compile_regular_expressions = 0 to the
statement that DEFINES the key or the index, with a comment claiming the
instance snapshots the compile threshold from the defining statement's context.
It does not, and the option is a no-op there.

A stored expression is analysed while the table is built from metadata, which
runs on the database's global context: StorageFactory asserts as much
(chassert(arguments.getContext() == arguments.getContext()->getGlobalContext())),
and DatabaseWithOwnTablesBase takes context_->getGlobalContext(). So the
threshold the instance carries is the server default, and neither the defining
nor the executing statement's setting reaches it.

Measured with the CompileRegexpFunction event read per query id. Defining under
compile_regular_expressions = 0 and executing with
min_count_to_compile_regular_expression = 0 compiles on the fourth call;
defining with the threshold at 0 and executing with compilation off also
compiles on the fourth. Both match the default of 3 rather than either
statement. With the server default at 0 the same stored expression compiles on
the first call while both statements ask for compilation to be off, and an
inline call in that server never compiles at all. The defining statement never
reaches the matcher either, so it cannot advance the seen counter.

Neither case loses anything. The first still stops within its deadline for the
reason it always did, and it stays live: on a build without the fix it now runs
38.5 s against a 1 s deadline. The second asserts that no query state is
retained, which is reached through CurrentThread rather than through the
threshold, so the option was orthogonal to it.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 16c5154

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_asan_ubsan, flaky check) / 04650_replace_cancellation PR-caused: my own new test is flaky under the rerun load. many folds reports OVERSHOT 4149 to 4421 ms against a 4000 ms bound, and many rows reports no timeout. PR-caused, a fix task is created (investigating at full effort, fixing commit lands on this PR)
Stateless tests (amd_debug, flaky check) / 04650_replace_cancellation PR-caused: same two cases. many folds OVERSHOT 2437 to 3123 ms against a 2000 ms bound, many rows no timeout. PR-caused, a fix task is created (same fix)
Stateless tests (amd_tsan, flaky check) / 04650_replace_cancellation PR-caused: same two cases, the other mode. All 10 occurrences are many folds: no timeout. PR-caused, a fix task is created (same fix)

The 11 cancelled checks on this commit were superseded by the push to 5f925a58488a8b and are
re-running there; they are not failures.

Diagnosis so far, so the fix task does not start from scratch. Both modes are about how these two
cases are sized, not about the cancellation fix they exercise. On a quiet machine the margin is thin:
measured 8 runs each on a debug build, many folds reports 1000 to 1128 ms and many rows 1012 to
1018 ms, both against a 2000 ms bound, so roughly 0.9 s of slack over the 1 s deadline. The flaky
check reruns the changed test many times alongside the rest of the suite, and the added scheduling
latency is enough to push the reported elapsed past the bound, or in the tsan case enough that the
query finishes before the deadline check fires at all. The second mode is the one worth removing
first, because a case that reports no timeout is indistinguishable from the fix not working.

Widening the bound is not the intended remedy, since it weakens the assertion. The sizing has to
satisfy both directions at once, and any resizing has to keep each fold too small to reach a
throttled checkpoint, which is what makes case 4 cover the unconditional per-call checks at all.

Session id: cron:clickhouse-maint-slot-13:20260730-211600

Comment on lines +81 to +88
/// `checkTimeLimit` returns false rather than throwing under the `break` overflow mode, but a
/// partially rewritten string is a wrong value rather than a shorter one, so it becomes a throw.
std::function<void()> check_cancellation;
if (process_list_element)
check_cancellation = [&process_list_element]
{
if (!process_list_element->checkTimeLimit())
throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded: elapsed time limit reached in function {}", name);

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 callback changes timeout_overflow_mode = 'break' from "return a partial result" to throwing TIMEOUT_EXCEEDED whenever the deadline is observed inside replace*. That is a user-visible semantic change, but the structured setting docs still say break will "stop executing the query and return the partial result, as if the source data ran out" (src/Core/Settings.cpp). The PR description explains the new behavior, but the documented contract is still broader than the implementation. Please update the timeout_overflow_mode docs alongside this change so users are not told that replace* in break mode will always return a partial result.

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.

You are right that the sentence is imprecise, but not that this PR causes it, and break does still return a partial result here.

Measured on 5f925a58488a, same query in both modes, max_block_size 1 over 40 ascending-cost rows:

mode rc rows error
break 0 1 none
throw 159 1 elapsed 2028.321 ms, maximum: 2000 ms

So wherever a partial result exists, break returns it and the query ends without a client-visible error. In pipeline shapes the message that fires is the executor's own, not the in-function one (in function replaceRegexpAll appears 0 times there, 1 time in the constant-fold shape), so the throw is absorbed into the normal cancellation path. It only reaches the client for a constant fold, where the whole result is one scalar value and there is no smaller result set to return.

That fold-shape throw is a pre-existing master convention, not something introduced here. At default settings on current master:

SELECT length(arrayFold((acc, x) -> concat(acc, toString(x)), range(3000000), ''))
  SETTINGS max_execution_time = 1, timeout_overflow_mode = 'break'
-> Code: 159. Timeout exceeded: elapsed time limit reached in function arrayFold

and the same ascending-rows shape on arrayFold returns rc=0 with a row and no error, exactly like replace*. base58Encode behaves the same with function_base58_max_input_size = 0. Three merged PRs already carry this convention with the same rationale in comments: #108192 (arrayFold), #112273 (geohashesInBox), #106428 (FunctionBaseXXConversion.h). None of them changed the docs, and #106428 did edit src/Core/Settings.cpp, only to add a new setting.

On the pristine master snapshot the constant-fold query in break mode returns rc=0 after 10931 ms against a 1000 ms deadline, so before this PR that shape ignored the deadline and returned a full result. This change makes it stop at 1373 ms. It does not turn a partial result into an exception.

I am also not changing the behaviour: returning a half-rewritten string would be silent wrong results, which is worse than an exception.

For the docs themselves the scope is wider than the two settings you name. That sentence is shared boilerplate appearing 9 times in src/Core/Settings.cpp, and only timeout_overflow_mode (DECLARE at line 3286) and timeout_overflow_mode_leaf (line 3315) are on the elapsed-time path; the other 7 are row and byte threshold modes. The rendered page is also inside an AUTOGENERATED region, so the text has to change in Settings.cpp, and two further pages carrying the same sentence (docs/concepts/features/configuration/settings/query-complexity.mdx and docs/en/operations/settings/query-complexity.md) have no autogenerated markers and would not regenerate from that edit.

Since the property is reachable on master today without this PR, I would rather not fold a master-wide docs correction into a replace* cancellation PR that is already in review, especially one that would be incomplete for the hand-written pages. I have filed it as a separate follow-up with the measurements, the 9-setting breakdown and both traps, and I will link the PR here when it opens.

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.

Opened as #113902.

Two corrections to what I wrote above, since the PR states different numbers.

The count depends on where the sentence is cut. stop executing the query and return the partial result does occur 9 times, which is the figure I quoted; the full sentence including
as if the source data ran out occurs 6 times, and that is the one the PR corrects, because
the three extra carriers (read_overflow_mode_leaf, group_by_overflow_mode,
sort_overflow_mode) use a shorter variant without that clause. Either way only
timeout_overflow_mode and timeout_overflow_mode_leaf are on the elapsed-time path.

docs/en/operations/settings/query-complexity.md no longer exists: the legacy Docusaurus tree
was removed in 9440ca729a38b76, three days after that comment. So the hand-written surface is
just docs/concepts/features/configuration/settings/query-complexity.mdx, which the PR edits
directly, while docs/reference/settings/session-settings/timeout-overflow-mode.mdx is inside an
autogenerated region and regenerates from the descriptions.

The PR is text only, and it also states two things I had not measured when I wrote the above: an
INSERT reports QUERY_WAS_CANCELLED rather than TIMEOUT_EXCEEDED when its caller pushes the
data block by block, and a quorum write does not stop at max_execution_time at all.

groeneai added 4 commits July 30, 2026 22:44
The case chained its 60 folds with `+`. A chain of N terms parses into N-1
nested `plus` nodes and formatting the statement recurses three frames per
level, so the stack cost grows with the fold count. A TSan build allows a
query thread only `max_size/20` of its stack, about 400K, against `max_size/2`
elsewhere (`checkStackSize.cpp`), so the statement was rejected with
TOO_DEEP_RECURSION before it ever ran: five runs of five logged
ExceptionBeforeStart, and the case reported `no timeout` because `run` reads
the elapsed time out of the server's message and there was none.

The same 60 folds now go in one `arraySum` array, which keeps the AST depth
constant instead of linear in the fold count. Measured by `EXPLAIN AST`, the
chain goes 14, 28, 128 for 3, 10 and 60 folds while the array form stays at 14
for all three. With the thread stack cut to emulate the TSan allowance, the
chain raises TOO_DEEP_RECURSION while the array form still reports its
timeout, down to a 256K stack.

The folds are still constant-folded, so the case still covers what it was
written for, and nothing about what it asserts changes: it still requires the
server to report an elapsed time, which only the in-function checkpoints
produce.

This is only the parse-time half. The same check also shows several cases
reporting elapsed times above their bound, and two reporting no timeout at
all, on the tsan, asan_ubsan and debug flavours alike. That is a separate
problem with how the bounds are sized under the flaky check's parallelism and
is tracked on its own.
…ing an absent elapsed time as no timeout

The test bounds the elapsed time the server reports for each cancelled query. Under the flaky check
that assertion is not robust, and it failed on amd_debug, amd_tsan and amd_asan_ubsan alike.

Two separate problems produced those failures.

The first is a false negative in the test itself. Two messages report the same enforced deadline and
only one of them carries a number: this function's own check goes through
QueryStatus::checkTimeLimit and reports "elapsed N ms", but the CancellationChecker watchdog thread
also fires at the deadline, marks the query killed, and the error then comes from
throwProperExceptionIfNeeded with no elapsed part at all - raised from addPipelineExecutor when it
wins before the pipeline starts, so the query fails with ExceptionBeforeStart. The extractor found no
number and printed "no timeout", i.e. it reported a missing cancellation for a query that had been
cancelled correctly and earlier than usual. The two cases that hit this, "many rows" and
"fixed string literal", never completed: their query_log rows are ExceptionBeforeStart with
"Timeout exceeded: maximum: 1000 ms". The run helper now bounds the wall clock when the number is
absent, the same way cases 19 and 20 already do, and only reports no timeout when the deadline was
really ignored.

The second is that the elapsed bound cannot be sized for a rerun-based check. It measures wall-clock
time since query start, so it includes the prologue this fix cannot interrupt, plus the gap between
two checkpoints - and that gap scales with per-unit cost, which instrumentation and parallel
contention inflate. "fixed string literal" spends 913ms of its 1000ms deadline materializing its
argument before the function is entered. Locally the fixed side stays at 1000-1022ms while an
unfixed binary reaches 3955-4249ms for that case, but the flaky check runs the test 25 times
sequentially on an instrumented build, where the fixed side was observed at up to 3123ms. The two
ranges nearly touch, so no constant separates them, and widening the bound would only trade a
false failure for a lost regression test. amd_debug is not a sanitizer build and overshot too, so
scaling the bound by the sanitizer multiplier does not help either.

Asserting only that TIMEOUT_EXCEEDED was raised is not an option here: an unfixed binary is still
bounded eventually by the pipeline's own between-block check, so it raises TIMEOUT_EXCEEDED as well
and the assertion would be vacuous. Deriving each bound from an uninterrupted reference run in the
same run does separate the two sides cleanly, but it needs that reference per case, and the test
already takes 147-151s on asan_ubsan against a 600s per-test timeout and a 45-minute flaky-check
budget.

So the test keeps its latency assertion in every ordinary stateless job, where it has full signal,
and is excluded from the rerun-based harness only. Verified in both directions: on the current
binary the test passes and is skipped under --flaky-check, and on a binary with the three function
headers reverted to their pre-fix state it still fails, with 17 cases reporting OVERSHOT - including
"fixed string literal", which previously reported the unparseable no timeout.
… checkpoint

The wall-clock fallback added in the previous commit accepted any prompt TIMEOUT_EXCEEDED that carried
no elapsed time. That is too permissive for a case that runs in the pipeline: CancellationChecker can
set the killed flag before the executor is registered, and addPipelineExecutor then throws on it
before the query reaches FunctionStringReplace::executeImpl, so the case would assert query-level
cancellation rather than the checkpoint this PR adds.

The distinction is the shape of the call, not the message. A constant-folded call is evaluated during
analysis, where there is no pipeline to cancel and no query-level path that could substitute for the
in-function check, so bounding its wall clock is sound. Of the cancellations without an elapsed value
in the reported flaky-check run, 50 came from the folded cases and 2 from "fixed string literal",
which is a pipeline case, so both shapes really do occur.

Each case now declares whether it is folded. A folded call keeps the wall-clock bound; a pipeline case
that reports no elapsed time is reported as cancelled before the pipeline started, which is neither a
pass nor a claim that the deadline was ignored.

Verified again in both directions: the test passes three times in a row on the current binary and is
skipped under --flaky-check, and on a binary with the three function headers reverted to their pre-fix
state every case still fails, "fixed string literal" among them at OVERSHOT 4088 ms.
The case reads 10000 rows to exercise the per-row loops, but did not pin max_block_size, which the
harness randomizes from 8000 upwards. On a draw below the row count the rows arrive in more than one
call, and the unconditional check on the function's single exit path then bounds the query between
blocks, so the case could pass with the in-loop charges removed. Every other per-row case already
pins the setting; this one was the exception.

Verified on the current binary, 20 runs with random settings: 20 passed. On a binary with the three
function headers reverted to their pre-fix state all 19 verdicts still fail.
@PedroTadim

Copy link
Copy Markdown
Member

Not sure if this is the right fix

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 64104ca

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, sequential, 1/2) / 04650_replace_cancellation this PR's own new test: its wall-clock bounds are too tight under tsan, so the cancellation latency assertion misses. The runner's own diagnosis reports Runs: 1, Failed: 0, Passed: 1 a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)
Stateless tests (amd_tsan, s3 storage, sequential, 1/2) / 04650_replace_cancellation same timing assertion as the row above, on the s3-storage flavour of the same job a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)
Stateless tests (amd_tsan, s3 storage, sequential, 1/2) / Scraping system tables post-run diagnostics could not dump query_log; downstream of the timed-out test above, not an independent failure a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

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

…wn setup

Cases 6 and 25 sized their argument large enough that materializing it outlasted the
deadline on a thread-sanitizer build. That part runs before the call and this change
cannot interrupt it, while the deadline runs from when the query was registered, so the
query was stopped before the function was entered: both cases reported the same elapsed
time with and without the in-function checkpoints, and passed either way. Measured on one
sanitizer build, the ratio between the two was 1.00x for case 6 and 1.04x for case 25,
against 10.8x to 163.5x for every other case.

Both now carry the cost inside the function instead - denser matches and a longer
replacement - so their setup finishes well inside the deadline. On that build the ratio
becomes 10.8x for case 6 and 12.7x for case 25; on a debug build both still exceed their
bound without the checkpoints. This also removes the overshoot that surfaced on the two
sequential thread-sanitizer jobs, which was the same setup cost being charged to the
bound.

Case 6 overshot on no job and would have kept passing while asserting nothing.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim The replace* functions had no cancellation checkpoint, and the time limit is only tested between pipeline blocks, so one call ran to completion however long it took; with constant arguments it runs during analysis, before a pipeline exists. FunctionStringReplace now builds one callback per call, and the unboundedly iterating loops charge a throttled budget against it. That is the shape base58Decode uses in FunctionBaseXXConversion.h.

One correction to my own description: it says this is the same defect class as #111909 and fixed the same way. The second half is wrong and I will fix the wording. #111909 bounds the input instead, rejecting parameters outside the domain where the samplers terminate at all. That option is not open here, because a large haystack with an ordinary pattern is a legitimate call that has to keep working, so the only lever left is making the loop interruptible.

The measured cost is in the description: release build, interleaved per shape, four shapes, all within noise.

Is your doubt the layer, a per-function checkpoint in four functions rather than one generic mechanism, or the cost of the counter in the substitution loops, or something else? I would rather rebuild it on the shape you want than keep pushing at this one.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4e77fd0

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, sequential, 1/2) / 04650_replace_cancellation this PR's own new test: its timing bounds are too tight under sanitizer load, so the cancellation cases report outside the expected window PR-caused, fixed in this PR
Stateless tests (amd_tsan, s3 storage, sequential, 1/2) / 04650_replace_cancellation same new test, same timing bounds PR-caused, fixed in this PR

Both failures are in the test this PR adds, so the fix belongs here and I am working it rather than
attributing it elsewhere.

Session id: cron:our-pr-ci-monitor:20260801-043000

…adline

The three cases that still overshot on the thread-sanitizer sequential jobs each
carried one step of work that this fix cannot interrupt and that on its own cost
about the whole 1000ms deadline, so the reported time had a floor of roughly one
deadline and there was nothing left under the bound once the job was loaded.

For "many folds" the budget is only consulted between folds, so a fold is the
smallest interruptible step; one fold with a pattern of 10000 measured 1810-1858ms
on that build. For "replaceAll" and "one-byte in place" it is the single 600MB
constant, built before the call, at 1842ms.

Each case now does the same total work in smaller steps: 240 folds of a 2500-byte
pattern instead of 60 of 10000, and ten independent folds of 60MB instead of one
of 600MB. Total pattern bytes and total scanned bytes are unchanged, so the
unfixed side is bounded by nothing exactly as before, while the fixed side drops
to the 1000ms floor. Splitting the two constants also halves what those cases
need against the test memory profile, which is why case 5 was already written
this way.

"one-byte in place" is included because it is the same defect with the same
numbers and it overshot on the previous head, not on this one.

Measured on both builds, both directions. Fixed side 1002-1048ms everywhere.
Unfixed side 32489-32509 / 18035-18340 / 18387-18576ms against a bound of 4000 on
the sanitizer build, and 3371-3422 / 3636-3676 / 2959-3052ms against a bound of
2000 on the debug build. The bound, the deadline, the verdict strings, the tag
line and the reference file are unchanged.
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 375/389 (96.40%) · Uncovered code

Full report · Diff report

@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 11:32
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c60294e

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_debug, parallel) / 04648_geohashes_in_box_cancellation flaky, not this PR's diff: the nan KILL case races the zero-item row loop, so the query ends with code 0 instead of 394. The runner's same-settings rerun reports Runs: 6, Failed: 0 #112823 (external, open)

04648 is not among this PR's 7 changed files. #112823 ("Deflake 04648_geohashes_in_box_cancellation")
addresses exactly this mode: its description reproduces the nan kill: query never reached the row loop
then ended with code 0 instead of being cancelled sequence and removes the unsound zero-item
assertion, so it is the owner rather than a fix task.

04650_replace_cancellation, the test this PR adds, is green on every flavour that ran it at this
commit (amd_tsan sequential, amd_tsan s3 sequential, amd_debug sequential, amd_debug distributed plan s3 sequential, amd_asan_ubsan db disk distributed plan sequential,
arm_asan_ubsan azure sequential, arm_binary sequential, and both Bugfix validation arms). The
timing bounds that failed on the previous heads no longer overshoot.

Session id: cron:our-pr-ci-monitor:20260801-120000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit f64de51 Aug 1, 2026
177 of 179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 3, 2026
…ts own

`04650_replace_cancellation` failed on `arm_binary` about once in a hundred
runs, always on the same case:

    -one match, long instruction list: stopped within bound
    +one match, long instruction list: no timeout

That case builds a single match whose substitution list is executed in full, and
every instruction writes another copy of the match, so the work it offers and
the memory the result occupies are the same quantity - and how much of it a
stopped call has already written grows with the speed of the machine. Against
the standard one-second deadline the list therefore had to be short enough for a
fast build to stay inside the 5GiB test profile, where it already reached 4GiB,
and long enough that a slower build could not finish it, and no single length
satisfies both: on a fast enough machine the call completed inside the deadline
and the case reported `no timeout`.

`run` now takes a deadline per case and keeps the same allowance on top of it
rather than the same absolute bound, so shortening a deadline does not loosen
the assertion with it. Case 15 takes a tenth of the standard deadline and a list
two orders of magnitude longer: the fastest build now has to finish 20GB of
copying in 100ms to report `no timeout`, and what a stopped call has written
falls in the same proportion as the deadline. Measured on the `arm_binary` and
`arm_tsan` builds of the failing commit, the case goes from 1000ms and 4GiB to
100ms and 390MiB, and on the sanitizer build to 210ms and 50MiB.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29

Related: ClickHouse#112483
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Aug 5, 2026
Case 21's `stored expression leak` oracle compared the delta of
`CurrentMetrics::QueryNonInternal` with `= 0` and treated everything else as a
retention. That gauge is bidirectional: the increment is owned by the
`QueryStatus` object and released in `~QueryStatus`
(src/Interpreters/ProcessList.cpp:526-527, via CurrentMetrics::Increment,
src/Common/CurrentMetrics.h:79-100), so a delta has three outcomes and the
oracle had branches for two. A negative delta printed
`RETAINED -1 query states` and failed the reference diff, reporting the exact
opposite of what happened: fewer query states alive after the window than
before.

A decrease is available because the metric decrement and the removal from
`system.processes` are separate stages -- `~ProcessListEntry` erases the entry
after waiting on `cancelled_cv` (:469-481) while the increment lives until the
`QueryStatus` is destroyed, and `QueryStatusPtr` is shared ownership -- and
because `KILL QUERY ... SYNC` returns once the query is cancelled, not once its
`QueryStatus` is destroyed (InterpreterKillQueryQuery.cpp:171-180). So a
residual from an earlier case can be counted in the first sample and gone by the
second.

`-le 0` sends a zero or negative delta to the existing pass line and every
positive delta to the existing retention line. The retention assertion keeps its
exact trigger and its exact string, no new output is introduced and the
reference file is unchanged, so the leak this case exists to catch is detected
with undiminished sensitivity. This suppresses a false-positive verdict; it does
not claim to make the oracle sound against a contaminated baseline, which is a
pre-existing property of any two-sample reading of a process-wide gauge and is
not widened here.

The one repo-wide sibling of this shape,
01563_distributed_query_finish.sh:42, is not affected: it reads
`system.errors`, whose counter is monotonic (src/Common/ErrorCodes.cpp:789), so
a negative delta is unreachable there.

Related: ClickHouse#112483
@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing out a residual I noted during this PR's CI round, for the record: in compileMatcher (src/Interpreters/JIT/CompileRegexp.cpp), the raw CHJIT * cached before std::move(jit) can dangle in the catch (...) cleanup if the holder constructor throws while a concurrent SYSTEM DROP COMPILED EXPRESSION CACHE has dropped the global owner. It is pre-existing on master, not introduced or widened here (this PR only turned the return into a local).

I am not opening a fix PR. I could not reach the window with any user-facing lever: 540 JIT compiles under ASAN with 126 genuinely injected allocation failures (memory_tracker_fault_probability, max_untracked_memory=0) and 400 concurrent cache drops produced zero occurrences, and the Failed to JIT-compile fallback counter stayed at 0 throughout, so no injected throw ever landed inside that function. The throwing allocation is a single node of a one-element map, and the LLVM work sits in a separate jemalloc arena, so the injector reliably fires elsewhere first. Without a repro a change here would be speculative, so I am leaving it documented rather than patched.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants