Repository navigation
Check for cancellation while replacing substrings - #112483
Conversation
Internal second-model review: 8 rounds, 5 blockers and 20 majors fixed, 3 refused with measurementsAn internal cold review plus an adversarial second-model gate ran over this PR for eight rounds before Agreed and fixed (selected)A stored A byte-denominated budget was blind to the cheapest loop. An empty regexp match advances one byte One match can carry an unbounded instruction list. The JIT case's anti-vacuity guard could be satisfied by a different JIT. It read The compile oracle was vacuous under a fixed test database. The stress runner gives some threads a Noted, not blockingThe flaky-check repeat count in a comment was wrong in both the number and the mechanism: a test Five charged sites are documented as not asserted rather than implied covered. Each is bounded by what Refused, with measurements"The compile event does not prove the JIT loop ran." The mechanism cited is accurate: the event is A request for A Session id: cron:clickhouse-review-slot-48:20260729-190100 |
Pre-PR validation gate
|
|
cc @george-larionov @Ergus, could you review this? The four |
|
Workflow [PR], commit [c60294e] Summary: ❌
AI ReviewSummaryThis PR adds per-call cancellation checks and throttled work accounting to the Findings💡 Nits
Final VerdictNon-blocking. No new inline review comments on the current head; the only remaining issue I would keep is the existing |
| . "$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, |
There was a problem hiding this comment.
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
0f82040 to
1c965fb
Compare
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.
CI finish ledger - 1c965fbEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
174 of 174 check-runs completed at this commit (4 success, 168 skipped, 2 failure); no third failure and The two rows are one event.
Verified locally with the rule alone on Session id: cron:clickhouse-maint-slot-13:20260730-185700 |
`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]>
…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]>
CI finish ledger - 16c5154Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The 11 cancelled checks on this commit were superseded by the push to Diagnosis so far, so the fix task does not start from scratch. Both modes are about how these two Widening the bound is not the intended remedy, since it weakens the assertion. The sizing has to Session id: cron:clickhouse-maint-slot-13:20260730-211600 |
| /// `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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
|
Not sure if this is the right fix |
CI finish ledger - 64104caEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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.
|
@PedroTadim The 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. |
CI finish ledger - 4e77fd0Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Both failures are in the test this PR adds, so the fix belongs here and I am working it rather than 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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 375/389 (96.40%) · Uncovered code |
CI finish ledger - c60294eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260801-120000 |
f64de51
…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
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
|
Closing out a residual I noted during this PR's CI round, for the record: in 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 ( |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
replaceOne,replaceAll,replaceRegexpOneandreplaceRegexpAllignoringmax_execution_timeandKILL 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 undertimeout_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 howeverlong 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
replaceRegexpAllover a folded 200 MB value withmax_execution_time = 1to completion, then reportsCode: 159with no elapsed time at all because the deadline was never observed. The overshoot isunbounded 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.
FunctionStringReplacenow builds one cancellation callback per call, and every unboundedly-iteratingloop in both implementations charges a throttled budget against it. One
RE2::Matchormemcpystillruns to completion, so no absolute bound is claimed; what is removed is the unbounded accumulation.
Under
timeout_overflow_mode = 'break'an uninterruptiblereplace*in the pipeline used to bestopped by the executor's soft check with no client-visible error. This checkpoint cannot return a
partially rewritten string, so it raises
TIMEOUT_EXCEEDEDinstead, asarrayFoldandbase58Decodealready 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 akey, 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,
FirstandAll, interpreted and JIT matchers,throwandbreakmodes,KILL QUERY,and a stored
PARTITION BYrun 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
-O3build, 20 under TSan; the only line that cannot differ is the leak guard, and each is proven liveby 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
replaceAll283/305 -> 288/303; literal fallback 1433/1471 -> 1423/1467; regexp fallback 1663/1713 -> 1667/1759;
7-byte
replaceAll426/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 JITcase asserts nothing there),
no-parallel(the leak case reads a global metric),no-coverage(per-testcoverage only, whose cost is bursty; the 21 of 24 lines it covered are covered elsewhere).
Version info
26.8.1.581(included in26.8and later)