Repository navigation
Fix quadratic complexity in countSubstringsCaseInsensitiveUTF8 - #112003
PedroTadim merged 3 commits into
Conversation
CountSubstringsImpl::vectorConstant scans the haystack column once with a
Volnitsky searcher, but for every match it recomputed the character offset from
the start of the current row via Impl::countChars. That helper is O(row bytes)
for the UTF-8 policies, so M matches over N bytes cost O(N * M).
Keep a forward-only cursor inside the current row instead and count only the
bytes newly traversed since the previous match, so every byte is counted at most
once. countChars is additive over a partition of a byte range and pos only moves
forward within a row, so the resulting offset is unchanged.
Only countSubstringsCaseInsensitiveUTF8 was affected: countChars is a member of
the search policy and the ASCII policies return end - begin, so the other two
CountSubstringsImpl instantiations were already O(1) there.
On a debug build with haystack repeat('\0\0\0\0\0\0\0\0\0\0a', N) materialized,
N = 16k/32k/64k/128k took 0.51/1.70/6.45/25.65 s before and 0.12/0.13/0.13/0.10 s
after; the 11 MB case (N = 1000000) goes from roughly 1550 s to 0.12 s.
Found through a hung check on unrelated CI runs, where such a query sat in the
processlist for 1612 s with is_cancelled = 1. The query text recorded for that
row was countMatches(...), which is misleading: the row was an AST fuzzer
statement whose displayed text is the original query while a later mutation ran
under the same query id. The stack of the running thread named
CountSubstringsImpl<NameCountSubstringsCaseInsensitiveUTF8,
PositionCaseInsensitiveUTF8>. countMatches itself takes 0.12 s on that haystack.
is_cancelled = 1 is a consequence of the loop having no interruption point, not
the cause. A cancellation checkpoint alone would leave a legitimate query over a
1.4 MB string running for about 27 minutes, so the complexity is fixed instead.
Adding cancellation checks to the string search family may be worth doing
separately.
Results are unchanged, so there is no compatibility surface: no setting, no
serialization or format change. Verified byte-identical output across multibyte
and ASCII haystacks, multibyte, single-byte, empty and zero-byte needles,
needles straddling row boundaries, start_pos at 0/1/mid/past-end, empty rows,
and the constant-haystack and needle-vector code paths.
Co-Authored-By: Claude Fable 5 <[email protected]>
Follow-up to the previous commit on this branch, addressing review feedback. The comment above the incremental cursor in `CountSubstringsImpl::vectorConstant` justified the row-identity check with "rows never share a start offset". That is not true of `ColumnString`: its strings carry no terminator, `sizeAt` permits `offsets[i] == offsets[i - 1]`, and a zero-length insert pushes the unchanged offset, so adjacent empty rows do share a start offset. The check is still exact for a narrower reason, which the comment now states: only a row that contains a match ever sets the cursor, and such a row is non-empty because the index scan leaves `haystack_offsets[i - 1] <= pos < haystack_offsets[i]`. The change to the header is comment-only - the preprocessed token stream is unchanged. `04648_count_substrings_utf8_complexity` pinned the complexity but not the cursor arithmetic. Its multi-row query uses a 10-character, 11-byte chunk with `start_pos` thresholds of 1 to 4, i.e. below both the character and the byte distance between matches, so a per-match delta cursor and a byte-offset cursor produce the same numbers as the correct one. Two small cases are added where multibyte characters precede the matches and `start_pos` exceeds the distance between matches. Each is verified against three wrong implementations: a per-match delta cursor returns 0 and 0, a byte-offset cursor returns 2 and 2, and a cursor that never restarts on a row change returns 3 for the second case, against a reference of 1 and 1. Reverting the whole cursor hunk still makes the file time out, so the complexity assertions are unaffected by the addition. The reference was regenerated with `clickhouse-test --record`. Existing suites `01590_countSubstrings`, `02346_position_countsubstrings_zero_byte`, `01163_search_case_insensetive_utf8`, `03278_enum_string_functions`, `03666_count_matches_complexity` and `00233_position_function_family` pass with unchanged references, and 50 runs of `04648` pass at 0.23 to 0.28 s each. CI reports for the hung check that led to this branch: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111881&sha=ff60399af8498b3ce3db0df35c2317474779b732&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 ClickHouse#111881 https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=852e60ed1f6b4b834b49e4421043f1edf1adb501&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 ClickHouse#108977
Internal second-model review (click to expand)Before opening this PR I ran two independent review rounds against it (an
The re-review of the follow-up commit returned no findings. Also checked and found sound: the offset is unchanged because |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260726-230001 |
|
cc @george-larionov @Ergus - could you review this? |
|
Workflow [PR], commit [46ea70e] Summary: ❌
AI ReviewSummaryThis PR replaces the per-match Final Verdict
|
CI finish ledger — 7126d02Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of these are caused by this PR's diff, which touches only Session id: cron:our-pr-ci-monitor:20260727-130000 |
|
Fixing PR for the The server logs for that job are 403 (the run was SIGTERM-killed at the 9000 s watchdog before the upload hook compressed them), so the earlier ledger line could only describe the symptom. The same failure also produces CIDB rows with No sanitizer report, no second logical error, The wedge that destroyed the diagnostics is a separate defect in the shared runner invocation ( The |
…s-utf8-quadratic-complexity
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
CI finish ledger — 46ea70eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-053000 |
6b80e3d
|
Fixing PR for the Root cause of that row: |
Related: #107941
Related: #111881
Related: #108977
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed quadratic complexity in
countSubstringsCaseInsensitiveUTF8, which made the function take minutes on a haystack of a few megabytes with many matches. The character offset of each match is now maintained incrementally instead of being recounted from the start of the row.Description
CountSubstringsImpl::vectorConstantscans the haystack column once with a Volnitsky searcher, but for every match it recomputed the character offset from the start of the current row:countCharsis O(row bytes) for the UTF-8 policies, so with M matches over N bytes the total work is O(N * M). This patch keeps a forward-only cursor inside the current row and counts only the bytes newly traversed since the previous match, so every byte is counted at most once.countCharsis additive over a partition of a byte range andposonly moves forward within a row, so the computed offset is unchanged.Only
countSubstringsCaseInsensitiveUTF8was affected.countCharsis a member of the search policy, and the ASCII policies returnend - begin, so the other twoCountSubstringsImplinstantiations (countSubstrings,countSubstringsCaseInsensitive) were already O(1) there.Measured on a debug build, haystack
repeat('\0\0\0\0\0\0\0\0\0\0a', N)wrapped inmaterialize:Roughly 3.3x to 4.0x per doubling before the change, flat after it.
I found this through a hung check on unrelated CI runs of my own PRs, where a single such query sat in the processlist for 1612 s with
is_cancelled = 1:Stress test (arm_asan_ubsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111881&sha=ff60399af8498b3ce3db0df35c2317474779b732&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29Stress test (arm_tsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=852e60ed1f6b4b834b49e4421043f1edf1adb501&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29The query text shown for that processlist row is
countMatches(...), which is misleading: the row hasASTFuzzerQueries: 4and one of its threads is inexecuteASTFuzzerQueries, so the recorded text is the original statement while the fuzzer was running a later mutation under the same query id. The stack of the thread that was actually running namesPositionImpl.hinsideCountSubstringsImpl<NameCountSubstringsCaseInsensitiveUTF8, PositionCaseInsensitiveUTF8>.countMatchesitself completes in 0.12 s on the same haystack and is not changed here.is_cancelled = 1is a consequence of the loop having no interruption point, not the cause. A cancellation checkpoint alone would leave a legitimate query over a 1.4 MB string running for about 27 minutes, so this patch fixes the complexity instead. Adding cancellation checks to the string search family may be worth doing separately.There is no open issue for this specific defect; the hung checks above are tracked under the general umbrella issue #107941, which covers many unrelated sub-causes, so this PR does not close it. Prior art for the same bug class in a neighbouring function: #88401
Results are unchanged, so there is no compatibility surface: no setting added or defaulted differently, no serialization or format change. Verified byte-identical output before and after across multibyte and ASCII haystacks, multibyte and single-byte and empty and zero-byte needles, needles straddling row boundaries,
start_posat 0 / 1 / mid-haystack / past the end, empty rows, and the constant-haystack and needle-vector code paths.01590_countSubstrings,02346_position_countsubstrings_zero_byte,01163_search_case_insensetive_utf8,03278_enum_string_functions,03666_count_matches_complexityand00233_position_function_familyall pass with unchanged references.The new test
04648_count_substrings_utf8_complexitytimes out without the fix and takes 0.23 s with it.materializein the test is load-bearing: the constant-haystack form takes a different, already fast path. The test also pins the cursor arithmetic itself, since a complexity assertion alone cannot tell a correct incremental offset from a wrong one: two small cases place multibyte characters before the matches and a start position above the distance between matches, and each was checked against three plausible wrong cursors (a per-match delta, byte offsets, and one that never restarts on a row change), all of which fail it.Version info
26.8.1.338(included in26.8and later)