Skip to content

Make countSubstrings observe cancellation and max_execution_time - #113369

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-count-substrings-cancellation
Aug 7, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-count-substrings-cancellation

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 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):

Fixed countSubstrings, countSubstringsCaseInsensitive and countSubstringsCaseInsensitiveUTF8 ignoring KILL QUERY and max_execution_time: a call over many rows or many matches could run for minutes after the query was cancelled.

Description

Related: #112203

A Stress test (amd_tsan) hung check reported a query running 767 s with is_cancelled = 1 set and
max_execution_time = 10:

SELECT count() FROM (SELECT * FROM (SELECT * FROM system.numbers_mt
    QUALIFY countSubstringsCaseInsensitiveUTF8(repeat('\0\0\0\0\0\0\0\0\0\0a', 1000000),
                                               materialize('a'))
    LIMIT 1025) LIMIT 55)

CI report

Root cause. CountSubstringsImpl has no cancellation checkpoint, and cancellation and the
elapsed-time limit are otherwise only observed between pipeline blocks, so one call runs to completion.
The materialized needle defeats the all-constant fold, giving about a million uninterruptible
iterations per row.

The change. Each CountSubstringsImpl method builds one checkTimeLimit callback per call,
resolving the running query from the executing thread, and charges a throttled, iteration-counted
budget from every unbounded loop. The budget struct and the callback factory move into a shared
header, and replace* now uses both.

FunctionsStringSearch.h is unchanged, so the budget stays out of the four other implementations
behind that dispatcher, which cover 19 of the 22 functions it instantiates: position.cpp.o,
like.cpp.o, match.cpp.o, hasToken.cpp.o and visitParamHas.cpp.o are byte-identical to master.

Known limitation. The checkpoint runs between searches, so one search must finish first. When one
call gets a very large range and the needle is absent, that search dominates: a 400 MB value takes
about 54 s to stop and a synchronous KILL QUERY is held about 53 s. Ordinary rows stay near 1 MB per
call and stop promptly. Bounding the window needs overlap handling at each boundary, so it is left to a
follow-up. HasTokenImpl::vectorConstant is also still unchecked.

Validation. New test 04722_count_substrings_cancellation.sh covers all three dispatch branches
and all three public functions, no-match rows, timeout_overflow_mode = 'break', KILL QUERY and a
correctness control. Each case asserts the termination cause, not only the duration, and leaves master
at least 3.5x over its bound. 50 runs pass.

Measured server-reported elapsed against a 1000 ms limit, 3 runs per arm
case master (optimized) master (debug) this PR
constantVector (the report's shape) 13468-13837 ms 13525 ms 1000-1001 ms
vectorVector, no match within the row 13413-13459 ms 13407 ms 1084-1091 ms
vectorVector, many matches in one row 12915-12986 ms 12899 ms 1128-1132 ms
vectorConstant 12990-13294 ms 12874 ms 1037-1046 ms
rows with no match 12981-13080 ms 13099 ms 1000-1001 ms
countSubstrings 12795-12852 ms 12892 ms 1000 ms
countSubstringsCaseInsensitive 12501-12610 ms 12762 ms 1000 ms
timeout_overflow_mode = 'break' 13539-13582 ms 13686 ms 1001 ms
KILL QUERY ... SYNC blocked for 33452-33759 ms 33554 ms 103 ms

Version info

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

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds, click to expand)

This change was reviewed independently before publication: a cold code review plus a
second-model gate on every revision, adjudicated against measured evidence. Six review
rounds, 20 findings. The final round returned no findings.

❌ Blockers found and fixed

# Finding Resolution
1 The timed cases were sized against one debug build. SCALE only widens the bound for slower builds, so on a faster machine the unfixed side shrinks toward the bound and a missing checkpoint reads as a prompt stop. The merged sibling 04650_replace_cancellation failed in CI in exactly this way and needed a follow-up to re-deadline its cases. Every case re-measured on an official optimized binary and on a pristine debug one, and re-sized to keep at least 3.5x the bound on both (the kill case 4.2x its own). Cases 3 and 4 changed shape rather than only size, which also dropped the largest fixture from 512 MB to 128 MB.
2 budget.charge was levied only inside the inner match loop, so a row containing no match was never charged at all. A per-row charge added to both row-wise methods, with a dedicated no-match test case (case 5) that is bounded by nothing else.

⚠️ Majors found and fixed

# Finding Resolution
3 The oracle scored a duration only, so any fast failure (memory limit, unknown setting, parse error) read as a pass. Each case now asserts the termination cause: throw mode requires TIMEOUT_EXCEEDED plus exception_code = 159 plus the elapsed N ms figure that only the deadline produces, and its absence is reported as inconclusive rather than as a pass; break mode requires ProfileEvents['OverflowBreak'] and a non-zero row count; the kill case has a three-way verdict. Every guard was shown to fire on the state it names, with the previous form shown passing on that same state.
4 Only one of the three public functions had a timed case, though each is a distinct instantiation over a distinct searcher. A timed case per function (cases 6 and 7 added).
5 The checkpoint machinery was reached through a header included by ~20 other functions, adding a ProcessList include to all of them. Made opt-in through a compile-time trait with the callback built out of line. Five opted-out object files are byte-identical to master after --strip-debug, and the header closure grew by exactly the size of the one new header.
6 The 50-run stability evidence predated substantial changes to the fixture and oracle. Re-run on the final revision: 50 of 50 pass, verified by the run's own captured output being byte-identical to the committed .reference, including a case label that exists only at the final commit.
7 A single very large no-match row is still bounded only by one whole search. Not a code change: the accepted replace* prior art carries the identical residual. The claim was narrowed instead, so the changelog entry and body promise per-row and per-match granularity rather than unqualified single-value cancellation, and the residual is stated in the body.

💡 Noted, not blocking

  • The three dispatch call sites are duplicated into if constexpr arms. Declined: the same requires-guarded duplication already exists on master for regexp_jit_min_count, so collapsing it would add a dispatch abstraction to a high-fan-out header that master does not have.
  • A profile-event marker would make the KILL QUERY oracle strictly stronger. The existing one already discriminates the two arms by ~300x, so this is a nice-to-have.
  • log_profile_events is pinned for the break case, since its verdict reads a counter that the query log only populates when that setting is on.

Disagreed, with evidence

  • Charging the no-match path inside vectorVector / constantVector is unbounded because Volnitsky scans without a callback. Refuted: both named methods use SearcherInSmallHaystack, never Volnitsky, and the per-row charge trips a check about every 1 MiB of row bytes. The related concern that does hold for a single huge row is item 7 above, which was accepted.
  • The Enum fast path needs charges too. Refuted: both loops there are O(rows) at a few nanoseconds per row and are capped by a pre-existing gate, and on that path the haystack is the short distinct-names dictionary, so it is the least likely place for a long call.

Session id: cron:clickhouse-review-slot-11:20260804-171931

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (SELECT * FROM (SELECT * FROM system.numbers_mt QUALIFY countSubstringsCaseInsensitiveUTF8(repeat('\0'x10 || 'a', 1000000), materialize('a')) LIMIT 1025) LIMIT 55) SETTINGS max_execution_time = 10 runs past 240 s on a debug master binary and dies with TIMEOUT_EXCEEDED at 11.2 s with this change. Every case of the new test is a fixed-size deterministic workload, not a probabilistic one.
b Root cause explained? Yes. CountSubstringsImpl has zero cancellation checkpoints, and cancellation plus the elapsed-time limit are otherwise only observed between pipeline blocks, so a single call runs to completion however long it takes. The 11 MB constant haystack with a materialized needle defeats the all-constant fold, so constantVector runs about a million search iterations per row with no interrupt point.
c Fix matches root cause? Yes. It adds the missing interrupt point: a checkTimeLimit callback built by the dispatcher, consulted from a throttled iteration-counted budget inside each unbounded loop. It does not widen a bound, cap an input size, or make the searcher faster. The report's own is_cancelled = 1 shows speed was never the defect.
d Test intent preserved / new tests added? New test 04722_count_substrings_cancellation.sh plus .reference. Nothing existing was weakened; 04648_count_substrings_utf8_complexity and 04650_replace_cancellation still pass unchanged. Case 10 of the new test is a correctness control, so a change that simply always threw, or throttling that dropped occurrences, would fail rather than pass.
e Both directions demonstrated? Yes, on Build-ID-verified binaries, both arms served by real servers under CI's 5G memory profile. Against a pristine master server the new test reports OVERSHOT on all eight timed cases (12.5 s to 13.9 s against a 1 s deadline) and kill query BLOCKED 34052ms, on an official optimized build and on a debug build alike; against this change every line matches the reference and 50 of 50 randomized runs of the final revision pass. The sizing was measured on the optimized build specifically, since a fast machine shrinks the unfixed side toward the bound and would otherwise let a missing checkpoint read as a prompt stop. Two further mutation arms: deleting the in-loop charges while keeping the whole plumbing also reports OVERSHOT everywhere, so the charges and not the plumbing carry the fix; and injecting an unknown setting into two cases makes exactly those two report NOT STOPPED BY THE DEADLINE: Code: 115 rather than a pass, so the oracle cannot be satisfied by an unrelated fast failure. Each verdict guard was also shown to fire on the state it names, with the previous form shown passing on that same state: run with log_queries = 0, the break case reports NO QUERY LOG ROW, whereas scoring the aggregate alone reads the empty result's 0 as being within the bound; and under a memory limit small enough to abort that case, it reports DEADLINE NEVER OBSERVED where a duration-only ladder reported a pass on a 30 ms Code: 241 failure. That verdict reads a profile counter out of the target's own log row, so log_profile_events is now pinned for it: with the setting off the counter reads 0 and the verdict would fire on a good state, which was measured both ways.
f Fix is general across code paths? All five unbounded loops in the file are charged, covering all three dispatch branches (vectorConstant, vectorVector, constantVector), and each charge site has its own test case. The charges are shown load-bearing as a set by an arm that deletes all five while keeping the plumbing, and the vectorVector per-match site is additionally isolated by a one-line mutation of that site alone, which reddens exactly and only its own case. All three public functions, which are distinct instantiations over distinct searchers, carry a timed case of their own. Every other implementation reachable through this dispatcher was read loop by loop: PositionImpl, MatchImpl and ExtractParamImpl perform one match attempt per row and cannot spin inside a row. HasTokenImpl::vectorConstant does share the defect; the PR description says so and it is a follow-up, not silently omitted.
g Fix generalizes across inputs (params/datatypes/wrappers)? Counts verified byte-identical to master across all three functions, all four dispatch branches, with and without start_pos, multibyte needles, empty needle, empty haystack, NUL bytes, an Enum haystack, and the Nullable / LowCardinality / LC(Nullable) / NULL wrapper matrix. The wrappers are peeled by the default implementations before this code runs, so there is no wrapper-specific path here.
h Backward compatible? (maintainer-approved exception only) No compatibility surface: no new or changed setting, so no SettingsChangesHistory.cpp entry, no serialization format change, no experimental gate. The behavior change is that a query which previously ignored its deadline now honors it, which is the documented contract of max_execution_time.
i Invariants and contracts preserved? The counts are unchanged (asserted in g), so the function's postcondition holds. The budget object lives on the stack of one vector call and is never shared between threads. The callback is resolved from the executing thread rather than captured at construction, because an instance can be stored in table metadata and run later by an unrelated query, and it is held by value so it outlives the block that built it. The only new exit path is an exception, which leaves the partially filled result column to the caller exactly as any other throw from a function does.

Session id: cron:clickhouse-impl-slot-45:20260804-064700

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @nihalzp, could you review this? countSubstrings had no cancellation checkpoint, so one call kept searching after KILL QUERY and past max_execution_time (a hung check caught it at 767 s); this adds a throttled, iteration-counted budget to each unbounded loop, opt-in through a compile-time trait so every other function reached through the same dispatcher compiles it out.

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e136e22]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-2e0c) FAIL cidb IGNORED

AI Review

Summary

This PR factors the existing replace* cancellation budget into CancellationBudget, wires the three countSubstrings* implementations through it, and adds a focused timeout / KILL QUERY regression test matrix. The many-row and many-match cases look well covered and CI is green, but one material single-call path still stays outside the new checkpointing.

Findings
  • ⚠️ Majors
    • [src/Functions/CountSubstringsImpl.h:83-132] vectorConstant still does not observe cancellation while one searcher.search call is chewing through a large no-match or near-miss range. The new budget only charges after searcher.search returns a match or finally returns end, so one large value can still hold KILL QUERY ... SYNC and max_execution_time for tens of seconds before the callback runs. Suggested fix: split the scan into bounded windows with needle_size - 1 overlap, or add another searcher-side checkpoint so the no-match path can re-enter the budget before the whole range is consumed.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make CountSubstringsImpl::vectorConstant re-enter the cancellation budget before one whole no-match search finishes, or narrow the advertised scope further and carry that residual as an explicit follow-up instead of presenting this as the general countSubstrings cancellation fix.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 124/130 (95.38%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
/// We will search for the next occurrence in all strings at once.
while (pos < end && end != (pos = searcher.search(pos, end - pos)))
{
budget.charge(pos - charged_up_to);

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 still leaves a full-block no-match path uninterruptible. budget.charge(pos - charged_up_to) only runs after searcher.search returns a match, so if the constant needle is absent from the remaining haystack_data, searcher.search(pos, end - pos) scans the whole remainder, returns end, and the loop body is skipped entirely. executeImpl only calls check_cancellation() after vectorConstant returns, so countSubstrings*(materialize(big_haystack), 'missing') can still ignore KILL QUERY / max_execution_time for the whole block. The new vector_constant case keeps one match per row, so it does not cover this shape.

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.

Confirmed, and it is worse than the residual paragraph in the description admits. Measured on the branch binary (Build ID 4de39020ddecb5d496c28ef6aa4f2790cc7cb66e, server buildId() asserted equal first), one row, no settings overrides at all:

fixture (countSubstringsCaseInsensitiveUTF8, needle absent) max_execution_time = 1
100 MB row 13503 ms
200 MB row 27123 ms
400 MB row 54346 / 55656 / 54711 / 55716 ms
SELECT countSubstringsCaseInsensitiveUTF8(materialize(repeat(repeat('Ж', 200), 1000000)),
                                          repeat('Ж', 16) || 'Щ') FORMAT Null

And the channel the changelog names, with no time limit set: the target ran 53632 ms and KILL QUERY ... SYNC blocked 53100 ms. So a synchronous kill is still held for the better part of a minute, which is the defect class this PR is about.

Two corrections to your version of it, so the shape is on record accurately:

Your literal example does not reproduce. countSubstrings(materialize(<400 MB>), 'zzz') finishes in 58-120 ms, because that instantiation searches with Volnitsky, which skips ahead. Reaching the residual needs either a needle that repeatedly almost matches, or one of the two case-insensitive instantiations. On one identical 400 MB near-miss fixture: countSubstrings 114 ms, countSubstringsCaseInsensitive 2949 ms, countSubstringsCaseInsensitiveUTF8 54346 ms.

It is not confined to a whole block either, and that cuts the other way from your reading: with ordinary 200 KB rows in a MergeTree column the fix does work (1412 ms, kill returned in 1004 ms), because preferred_block_size_bytes keeps each call's range near 1 MB. What breaks it is one call receiving a very large range, which a single large value does at default settings.

I had dismissed this shape in my own pre-publication review on the grounds that the merged replace* code has the identical structure, and that reason does not survive measurement. The structure is shared (ReplaceStringImpl.h:145 charges after the search too), but replace* is only ever instantiated over Volnitsky and CaseSensitiveStringSearcher, and there is no case-insensitive replaceAll, so no instantiation of it pays the per-byte cost that makes this visible: replaceAll on the same 400 MB near-miss fixture returns in 142 ms. Same shape, different consequence, so the precedent cannot carry the disclosure.

Worth noting that ReplaceStringImpl.h:106 already chunks its one whole-column loop at 64 MiB precisely "so the time limit is observed", with a note that chunking perturbs codegen and the chunk is therefore kept large. That is upstream precedent for bounding the range rather than against it.

I am not patching this into the current push. Bounding the search window needs needle_size - 1 of overlap at every boundary, and getting that wrong silently returns wrong counts, which is a worse outcome than the residual. It also invalidates the sizing of every timed case in the new test. So I am correcting the description, which currently understates the residual and cites a precedent I have just refuted, and the window fix goes through a normal review round with its own boundary tests rather than as a follow-up commit here.

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.

Correcting myself on one detail above, because it is a prescription someone would follow.

I wrote that bounding the search window "needs needle_size - 1 of overlap at every boundary". That is right for countSubstrings and countSubstringsCaseInsensitive, and wrong for countSubstringsCaseInsensitiveUTF8, which is the only instantiation that actually hangs here.

compareTrivialUTF8 (src/Common/StringSearcher.cpp:137-161) advances the two sides independently, each by its own sequence length:

haystack_pos += UTF8::seqLength(*haystack_pos);
needle_pos   += UTF8::seqLength(*needle_pos);

and returns on needle_pos == needle_end (:161) without regard to how many haystack bytes were consumed. So a match region is longer than the needle whenever a haystack code point folds to a shorter one. U+212A KELVIN SIGN is 3 bytes and folds to ASCII k:

needle haystack needle bytes match span count
a + 1xk a + 1xU+212A 2 4 1
a + 2xk a + 2xU+212A 3 7 1
a + 4xk a + 4xU+212A 5 13 1
a + 16xk a + 16xU+212A 17 49 1

The excess is 2 x (folding code points), so it is not bounded by needle_size - 1 at any size: at 16 code points the needle is 17 bytes and the span is 49. Truncating the haystack confirms the span is real rather than an artifact of where the match starts: needle ak, haystack a + U+212A cut to 2 and 3 bytes gives 0, and only the full 4 bytes gives 1.

The bound is 3, and only just: sweeping all 1114112 code points with the function itself as the oracle, exactly one multibyte code point matches a single-byte ASCII needle character, U+212A against K and k. Over folding-equivalent pairs of differing length the maximum haystack bytes per needle code point is 3. A needle has at most needle_size code points, so match_span <= 3 * needle_size, and the measured ratio approaches 3 from below (2.0, 2.333, 2.6, 2.882, 2.969 at 1, 2, 4, 16, 64 code points).

So a sound overlap there is 3 * needle_size - 1. Scoped by instantiation, on one identical fixture (a + 8xU+212A against a + 8xk): countSubstringsCaseInsensitiveUTF8 counts 1, countSubstringsCaseInsensitive 0, countSubstrings 0. The constant has to be searcher-aware rather than one value for all three.

This is consistent with the reason UTF8CaseInsensitiveStringSearcher avoids StringZilla in the first place, which its own comment gives as full folding returning "matches whose byte length differs from the needle, which diverges from the one-code-point contract and breaks length-based callers". An overlap expressed in needle_size is exactly such a caller.

Measured on a master debug build, Build ID 3460f97598eaa277e264ee687597b3af6437009d. Nothing here changes this pull request; it only fixes the follow-up's starting point, which my earlier comment got wrong. The window fix still waits for this to merge, since it has to charge against the budget this adds.

Comment thread src/Functions/FunctionsStringSearch.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit e136e22 - the build was skipped, reused from cache, or predates profile upload.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0e96a4a

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
Stress test (amd_tsan) / Received signal 6 (internal), STID 2009-2ba7 pre-existing trunk bug: the QueryFuzzer AST cycle detector aborts on a recycled node address #113114 (external, merged 2026-08-04) - this build predates the fix

Session id: cron:our-pr-ci-monitor:20260805-033000

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
extern const int TIMEOUT_EXCEEDED;
}

std::function<void()> makeCancellationCheck(const char * function_name)

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 you added a cancellation check for the regex functions; can't you reuse some of the code from there?

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.

Yes for the part that was still duplicated. Fixed in 9d2c7c8 (+2/-18).

The throttling struct was already reused: CancellationBudget is not new here, it is the regex change's ReplaceCancellationBudget moved out of ReplaceStringImpl.h and renamed, body unchanged. What I had left duplicated was the factory that resolves QueryStatusPtr from the executing thread and wraps checkTimeLimit in a throwing lambda: replace* still had its own copy inline in FunctionStringReplace.h. That commit deletes it and calls makeCancellationCheck(name), so both families share one budget and one factory.

Two side effects. The old lambda captured process_list_element by reference; the shared factory copies the shared_ptr into the closure, so it no longer depends on a local outliving it. And FunctionStringReplace.h drops ProcessList.h, CurrentThread.h and the TIMEOUT_EXCEEDED declaration, so the four replace* translation units stop pulling ProcessList in through that header.

Verified rather than asserted: with a mutant makeCancellationCheck that always returns an empty callback, 04650_replace_cancellation goes 29s to 329s and 04722_count_substrings_cancellation 13s to 145s, both failing; both pass again on the restored tree, whose build id is identical to the one measured before the mutation. That is what shows both paths really route through the single factory.

Not shared is the charge granularity: this change charges per row in both row-wise methods, because a row with no match never reaches the inner charge, while the replace* loops charge per rewritten string. Same primitive, different call sites.

Comment thread src/Functions/FunctionsStringSearch.h Outdated
null_map.get(),
input_rows_count);
{
if constexpr (ImplNeedsCancellationCheckpoint<Impl>::value)

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 why this constexpr is needed? Just check for cancellation at all cases

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.

Two parts to that, and the second one I measured rather than argued.

The trait was a second opt-in mechanism where this file already had one: the JIT compile-count threshold twenty lines below is detected from the call signature with requires. Dropped Impl::needs_cancellation_checkpoint for a concept that just asks whether the impl takes the callback, so an impl opts in by accepting the argument and nothing else. One mechanism instead of two, in 832bf93.

Checking in all cases I did try, and kept the condition, because the callback is built once per executeImpl and that is a TLS read, a weak_ptr lock and a std::function allocation. Measured on 200000 single-row calls of position, which needs no checkpoint:

arm median per call
conditional 560 ms -
unconditional 596 ms +180 ns

It also grows each non-participating object file by about 1.7 KB, since std::function gets instantiated where it previously did not: position.cpp.o +1680, like.cpp.o +1792, hasToken.cpp.o +1864, visitParamHas.cpp.o +1744. On a normal block size that 180 ns is noise (0.1% of a 20M-row position query), so I would not argue hard for it on its own; it is just that keeping it costs one if constexpr over the concept I was adding anyway.

So the mechanism count went from two to one, which I think was the real point, and the condition stayed. The other 19 functions through this dispatcher move by at most 112 bytes against the previous commit.

Verified on Build ID af6c751c551d6de954b5c1e486151d1a775e67ed: 04722 and 04650 both pass. Forcing the concept unsatisfiable, so the callback is never plumbed, fails 04722 at 147.87 s against 16.57 s while 04650 stays green, which is the expected split since replace* does not go through this dispatcher.

# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh

# Each timed case below puts more than a second of work inside ONE function call, then bounds the elapsed

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 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.

Done in 832bf93: 117 comment lines down to 55, longest block 22 lines down to 5, with the executable code byte-identical (verified by stripping comments and blank lines from both versions and comparing hashes).

The sizing rationale and the unfixed-side timings that were spelled out beside each case are in the commit that added them, so they are still recoverable without sitting in the file. What I kept at each case is the dispatch branch it covers and which charge can stop it, since that is the part that is not evident from the query itself.

Comment thread src/Functions/CountSubstringsImpl.h Resolved
Comment thread src/Functions/FunctionsStringSearch.h Outdated
null_map.get(),
input_rows_count);
{
if constexpr (ImplTakesCancellationCheck<Impl>)

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 do you need such extra branch? Why dont keep it as it is with the extra check_cancellation check?

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, and the branch no longer needs to exist. FunctionsStringSearch.h is back to being byte-identical to master in e136e22.

CountSubstringsImpl already has name in scope, so each of its three methods can call makeCancellationCheck itself. Nothing has to be threaded through the dispatcher, so there is no signature detection and no if constexpr at any call site.

It is also better on the thing the branch was there to protect. I had kept the condition because an always-present callback argument put std::function into the four other implementations behind that dispatcher, which cover 19 of the 22 functions it instantiates. Sourcing the check inside the impl instead means those instantiations are not touched at all. Three separately built binaries, each server's lower(buildId()) asserted against its readelf value before every verdict:

arm build id position/like/match/hasToken/visitParamHas objects
master ec331f97e86b3985 baseline
previous af6c751c551d6de9 all five differ
now 264a0c68ff27c197 all five byte-identical to master

So the 180 ns I measured for the unconditional form was the cost of paying for the callback in position, like, match and hasToken as well. That is now zero, because they are unchanged.

One thing the dispatcher was doing had to move rather than disappear. It held a checkpoint after dispatch, which covered exits that charge nothing: vectorConstant searches a whole block at once and charges inside its loop body, so a block where the needle is never found used to leave without charging. Each method now checks once on entry, and vectorConstant charges the remaining bytes on the way out.

Verified on 264a0c68ff27c197: 04722 passes in 15.32 s and 04650_replace_cancellation in 33.37 s. Both are still load-bearing: with makeCancellationCheck forced to return an empty callback, 04722 fails at 146.98 s and 04650 at 339.20 s.

Squashed to one commit, since it had reached 12.

@groeneai
groeneai force-pushed the groeneai/fix-count-substrings-cancellation branch from 63f2fd6 to 3fef8ab Compare August 5, 2026 14:43
`countSubstrings`, `countSubstringsCaseInsensitive` and `countSubstringsCaseInsensitiveUTF8`
never checked for cancellation inside their per-row loops, so a single large call ignored
both `KILL QUERY` and `max_execution_time` until it finished. On a Stress test that showed up
as a hung check: one cancelled `countSubstringsCaseInsensitiveUTF8` over an 11M-character
haystack kept running for 767 s.

The three row-wise methods now drive a throttled checkpoint. `CancellationBudget` is not new
code: it is the regex change's `ReplaceCancellationBudget` moved out of `ReplaceStringImpl.h`
and renamed, so `replace*` and the substring counters share one budget and one factory. That
factory, `makeCancellationCheck`, resolves the query from the executing thread rather than
from the context that built the caller, because a function instance can be stored in table
metadata and run by a later query.

The budget is counted in loop iterations rather than bytes, since one iteration can cost a
full search attempt while advancing almost no data; bytes are charged on top, scaled down,
because an iteration can also touch megabytes. Charging is per row in both row-wise methods:
a row with no match never reaches the inner charge, yet still scans its bytes. `vectorConstant`
searches a whole block at once, so it also charges what remains on the way out, covering a
block in which the needle is never found.

`FunctionsStringSearch.h` is unchanged. Each method sources its own check, which keeps the
budget out of the four other implementations behind that dispatcher, `PositionImpl`,
`MatchImpl`, `HasTokenImpl` and `ExtractParamImpl`, covering 19 of the 22 functions it
instantiates. Their `position.cpp.o`, `like.cpp.o`, `match.cpp.o`, `hasToken.cpp.o` and
`visitParamHas.cpp.o` are byte-identical to master.

Known limitation: `HasTokenImpl::vectorConstant` and the FixedString paths are untouched.

Related: ClickHouse#112203
@groeneai
groeneai force-pushed the groeneai/fix-count-substrings-cancellation branch from 3fef8ab to e136e22 Compare August 5, 2026 14:45
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e136e22

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
Stress test (arm_asan_ubsan, s3) / Logical error: '(isConst() || isSparse() || ...) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)', STID 2508-2e0c chronic trunk bug in the hash-join additional-filter path, not this PR. Stack: IColumn::assertTypeEquality (IColumn.h:941), inlined from IColumn::insertFrom (:255), reached from buildAdditionalFilter (HashJoinMethodsImpl.h:807). CIDB, 30 d: 39 rows over 38 distinct PRs plus 1 master row #107957 (ours, open) - "Fix LOGICAL_ERROR in HashJoin::buildAdditionalFilter with join_use_nulls and a non-equi JOIN condition". STID 2508-2e0c and 2508-30f6 are the same line, differing only in the caller's JoinStrictness template argument (RightAny vs All), and buildAdditionalFilter is templated on <AddedColumns, Selector> with no strictness parameter, so that fix covers both by construction
Build (arm_release) / Post Hooks infra: the build-profile telemetry hook aborts before its retry loop, No connection to LogCluster / LogCluster not ready from the is_ready probe. Non-gating, so the enclosing check-run still reports success a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR). Not #113409: its retries sit inside do_query's response loop, strictly after the is_ready early return, so this mode is untouched

Neither failure is PR-caused. This PR's diff is the cancellation budget shared by the string search and replace families (CancellationBudget.{h,cpp}, CountSubstringsImpl.h, FunctionStringReplace.h, ReplaceRegexpImpl.h, ReplaceStringImpl.h) plus its own new test; it does not touch the hash-join column path, and the build hook is CI telemetry.

This supersedes the earlier ledger on 0e96a4a9762b, which covered a superseded head.

Session id: cron:our-pr-ci-monitor:20260805-210000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 8bb9b45 Aug 7, 2026
178 of 180 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 Aug 7, 2026
bacek pushed a commit to bacek/ClickHouse that referenced this pull request Aug 9, 2026
`countMatches` and `countMatchesCaseInsensitive` loop over the repeated
matches of one value inside a single `executeImpl()` call and never consult
the query's status, so nothing observes `max_execution_time` or `KILL QUERY`
for the duration of that call. With a constant argument the call runs during
analysis, before a pipeline exists at all. Measured against a 2 s deadline on
a debug build: a fold over a 110 MB haystack ran 16.8 s, a per-row shape 60.2 s,
and a synchronous `KILL QUERY` waited 66.4 s, while `replaceRegexpAll` (which
gained this checkpoint in 1c965fb) stopped at 2.0 s throughout.

The match loop now charges the shared `CancellationBudget` that ClickHouse#113369 added,
with the check itself resolved per call by `makeCancellationCheck`. All three
column entry points (constant, `ColumnString`, `ColumnFixedString`) reach the
one private helper that owns the loop, and both registered functions are the
same template, so one charge covers every path. The budget lives for the whole
call rather than per row, so a block of cheap rows accumulates towards a check.

The amount charged is the distance the matcher scanned, which is not the
distance `pos` advances: an empty match moves `pos` a single byte however far
ahead the match was found, and a failing match scans the rest of the value
before the loop is left. Counting iterations alone is not enough here - one
match per megabyte is about two iterations per row, which never reaches an
iteration threshold, and that shape overran by 6.8 s before this change.

`checkTimeLimit` returns false rather than throwing under the `break` overflow
mode, but a half-counted result is a wrong value rather than a smaller one, so
it becomes a throw, as the same four merged precedents do. The charge is a
decrement and a compare against a counter advanced once per regexp match, and
an `RE2::Match` costs orders of magnitude more, so the cost is unmeasurable.

Cancellation for `extractAll`, `extractAllGroups*` and the array functions over
one large array follows in separate pull requests, one concern each.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 9, 2026
`countSubstringsCaseInsensitiveUTF8` ignored `max_execution_time` and `KILL QUERY` for the
duration of one substring search: a one-second deadline was observed after 13.4 s, and
`KILL QUERY SYNC` blocked 53 s on a 400 MB value. The checkpoint added in ClickHouse#113369 is charged
between searches, and `vectorConstant` searches a whole block in one call, so many ordinary
rows in which the needle does not occur reproduce it as readily as one large value.

Nothing under `src/Common` checked cancellation, and one searcher is slow enough to matter: on
that shape the case-sensitive scan takes 0.19 s and the ASCII case-insensitive one 0.77 s,
while `UTF8CaseInsensitiveStringSearcher` takes 13.6 s, folding a code point at a time through
`Poco::Unicode::toLower`.

The scanning loops now take an optional charger callback, modelled on the one `encodeBase58`
already takes, and `CountSubstringsImpl` binds one to the `CancellationBudget` it builds per
call. Three properties are load-bearing: comparison work is charged rather than distance
covered, since a candidate can walk the whole needle before failing; the accumulator lives in
the caller, because `vectorVector` builds a searcher per row; and both build paths carry it,
since `Volnitsky.h` gates `use_fallback_searcher` on `__AVX2__`. A caller passing no charger
gets its own instantiation of the loop and pays nothing. Realigning after a skipped window is
itself a loop over a continuation run that can span the haystack, so it is bounded per
iteration; stopping mid-run is safe because a continuation byte begins no match.

No returned value changes: the range passed to `search` is untouched, so no chunk edge exists.

The test asserts results rather than latency. Charging runs on the matching path, so it can
drop, duplicate or misplace an occurrence, and that is observable without a clock: all three
functions over both dispatch branches, start positions, empty haystack and needle, folding
between code points whose lowercase differs in byte length, and five cases in which a run of
continuation bytes long enough to skip a whole window is followed by a match that must still
be found. Each of those five is paired with the case-sensitive count as an oracle that does
not go through this searcher, and advancing one byte past the realignment changes all five and
none of the others.

An earlier revision bounded elapsed time instead. It failed 22 CI runs out of 22: on the
thread sanitizer the machine is about ten times slower, three arms overran, and the control
meant to finish well under a one-second deadline took 12027 ms, leaking its TIMEOUT_EXCEEDED
into the server log. No bound survives the build matrix, since one high enough for the
sanitizer sits above the unfixed side on release. ClickHouse#114061 removes seven earlier tests of that
shape for the same reason. Cancellation promptness is therefore left unpinned.

`position*` and `multiSearch*` share the defect and each needs its own call site.
`compareTrivialUTF8` folds a whole needle with no checkpoint, so a needle differing only at its
last code point still overruns by a bounded 0.85-1.02 s; that fix belongs inside that function,
shared with `startsWith`/`endsWith` and `VolnitskyBase::compare`.

Related: ClickHouse#112203
Related: ClickHouse#113369
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
alexey-milovidov added a commit that referenced this pull request Sep 23, 2026
Resolve the conflicts in `h3PolygonToCells.cpp` and `h3PolygonToCellsWithContainment.cpp` by taking the
thin wrappers over `appendH3Cells` from the source PR, without the `MultiPoint` rejection branch: 26.7 has
no `ColumnToMultiPointsConverter`.

Also add `CancellationBudget.h` and `CancellationBudget.cpp` from master (introduced by #113369, which is not
in 26.7): `h3GeometryToCells` and both functions depend on `CancellationBudget` and `makeCancellationCheck`.
The helper is self-contained; it does not change `countSubstrings` or anything else on 26.7.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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