Skip to content

Cache regexp results for repeated haystacks in replaceRegexpOne/replaceRegexpAll - #111005

Open
raimannma wants to merge 51 commits into
ClickHouse:masterfrom
raimannma:dedup-replace-regexp
Open

raimannma wants to merge 51 commits into
ClickHouse:masterfrom
raimannma:dedup-replace-regexp

Conversation

@raimannma

@raimannma raimannma commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

replaceRegexpOne and replaceRegexpAll (REGEXP_REPLACE) with a constant pattern can now evaluate the regexp only once per distinct haystack value within a block on the RE2 path, copying the cached result for repeats (adjacent duplicates by comparing with the previous row, others through a hash map). Real-world string columns such as URLs and referers are highly repetitive, so this is up to an order of magnitude faster on such data. Applies to String and FixedString haystacks; the JIT-compiled regexp path is unchanged.

Whether the cache pays off depends on how the cost of the regexp compares with hashing the haystack, which the share of repeats alone does not tell: a cheap regexp such as ^[a-z] over long haystacks is slower with the cache even when many rows repeat, while a full scan such as [0-9]{50} wins with few repeats. So the rows are processed in windows of 32, the time per byte of each window is measured, and the cheaper of the cached and the plain mode is kept, with the other one probed again at exponentially growing intervals. The state is carried from block to block, so short blocks also reach a decision. The result never depends on the choice.

Also:

  • Rows that do not start with the literal following ^ (e.g. http for ^https?://) cannot match and are copied through without running the regexp.
  • A capture-free existence check runs ahead of the regexp when almost no row matches, for patterns anchored with ^ that have capturing groups, for which RE2 would otherwise reject through a slower engine than its DFA.

Cases 13 and 21 of 04650_replace_cancellation fed one repeated value to replaceRegexpAll and relied on the regexp running once per row to outlast the deadline. They now vary the tail of each haystack, which keeps the per-row work the same and the values distinct.

Changelog category (leave one):

  • Performance Improvement

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

replaceRegexpOne and replaceRegexpAll with a constant pattern evaluate the regexp only once per distinct haystack value within a block when that is measured to be cheaper. This speeds up replacement over repetitive string columns (such as URLs) when the pattern is not covered by the regexp JIT.


Workflow [PR]
Sync PR [sync-upstream/pr/111005]

On the RE2 path, run the regexp once per distinct haystack value within
a block and copy the cached result for repeats: adjacent duplicates are
caught by comparing with the previous row, non-adjacent ones by a hash
map. The map is switched off for blocks of mostly distinct values.
The JIT path is unchanged, as a compiled match is about as cheap as the
hash table probe it would save.
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b59788]

Summary: ✅


AI Review

Summary

The PR caches RE2 replacement results for repeated String and FixedString haystacks, chooses caching and existence prechecks by measured cost, and skips rows lacking a required anchored prefix. The current implementation addresses the previous findings, with focused functional coverage and before/after performance evidence. No remaining actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 24, 2026
Comment thread src/Functions/ReplaceRegexpImpl.h Resolved
…ReplaceRegexpImpl

`bool inserted;` was left uninitialized in the deduplication loop, tripping
clang-tidy's cppcoreguidelines-init-variables check as an error and failing
the arm_tidy build (PR ClickHouse#111005).

Also lower `next_distinct_ratio_check`'s initial value from 4096 to 256, per
review feedback: the old value meant blocks smaller than 4096 rows never
triggered the ratio check, so the mostly-distinct guard never kicked in for
small `max_block_size` settings or naturally short blocks. Added a
performance-test query with `max_block_size = 500` to cover this.
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a1e86495-698e-4a69-8c9c-9f1cd3b0078d
  • MIRAI run: d3b1f76c-7b85-48d4-b678-fe1e6d4fb83d
  • PR check IDs:
    • clickbench_7897_1788867884
    • clickbench_7903_1788867884
    • clickbench_7909_1788867884
    • tpch_adapted_1_official_7920_1788867884
    • tpch_adapted_1_official_7953_1788867884
    • tpch_adapted_1_official_7967_1788867884

Resolve the conflict in ReplaceRegexpImpl.h: master threaded a
ReplaceCancellationBudget through processString and processStringJIT, this
branch split vectorConstantConstant into a JIT loop and a deduplicating RE2
loop. Both loops now charge the budget per row and pass it down, and the
cached-result copy charges the bytes it moves.
Comment thread src/Functions/ReplaceRegexpImpl.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 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: 52/52 (100.00%) · Uncovered code

Full report · Diff report

raimannma and others added 4 commits August 3, 2026 15:08
Address review: the per-block deduplication only covered `vectorConstantConstant`,
while `FunctionStringReplace::executeImpl` routes `FixedString` haystacks to
`vectorFixedConstantConstant`, which kept the old per-row RE2 loop. Move the loop
into `processStringsDeduplicated`, parameterized by how a row is addressed, and use
it from both entry points.

Co-Authored-By: Claude Opus 5 <[email protected]>
Cases 13 and 21 fed one repeated value to `replaceRegexpAll` and relied on the
regexp running once per row. With per-block deduplication the regexp runs once for
the whole block and the other rows are memcpy copies, so the work no longer outlasts
the deadline and case 21 reported `stored expression: no timeout`. Vary the tail of
each haystack, which keeps the per-row work the same and the values distinct.

Also record the deduplication's cached-result copy in the note listing the charged
sites that have no case of their own: it moves at memcpy speed over an output the
5GiB test memory profile already bounds, and the per-row charge at the top of the
same loop bounds the loop regardless.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111005&sha=34785926a56d91fbb2765d71512ad56f962687ef&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29
PR: ClickHouse#111005

Co-Authored-By: Claude Opus 5 <[email protected]>
`Fast test` failed on a hang in `04512_length_fixedstring_parallel_replicas`, which
does not call `replaceRegexpOne` or `replaceRegexpAll` and cannot reach the changed
code: the test has 15751 passes and this one failure over the last 30 days. Its
failure gated the rest of the workflow, so there is nothing else to read yet.
`CH Inc sync` reported `config failed`, which is not one of the states that can be
resolved from the public repository.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111005&sha=8b5803f549b89d3cfe796398eb62c6b4ffee8635&name_0=PR&name_1=Fast%20test
PR: ClickHouse#111005

Co-Authored-By: Claude Opus 5 <[email protected]>
raimannma and others added 2 commits August 9, 2026 23:19
…dget rename

Merging master renamed `ReplaceCancellationBudget` to `CancellationBudget` and
moved it to its own header. The merge was textually clean because master never
touched `processStringsDeduplicated`, but that function still referred to the
old name and the merged tree did not compile.

`04650_replace_cancellation.sh` is being removed as flaky, so the deduplication
gets a test of its own that does not depend on timing. A constant pattern takes
the deduplicating path while a `materialize`d one does not, so the two forms of
the same call have to agree row for row. The cases cover non-adjacent repeats,
adjacent repeats, blocks distinct enough to switch the map off, repeats arriving
after that, repeats within small blocks, cached ranges of length zero, results of
differing length, `replaceRegexpOne` and the `FixedString` entry point.

Every case that can be affected was checked against a build with a deliberate
off-by-one in the cached copy, and fails there.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 5b59788e483b4c56fdf18f19ed6d3f242b98a7b7 was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

Comment thread src/Functions/ReplaceRegexpImpl.h Resolved
A row the regexp does not match comes out identical to its input, so caching it saves
only the match attempt, and for short-circuiting patterns such as '^missing' that
attempt is cheaper than hashing the haystack: benchmarked against the plain loop,
`replaceRegexpOne(url, '^missing', 'X')` over repetitive haystacks was 10% slower on
90-byte rows and 47% slower on 500-byte rows. Track how many rows matched, and once a
block proves to be almost entirely non-matching, run a capture-free existence check
first and copy rejected rows through directly. This restores the plain loop's cost for
rejected rows (measured at parity or slightly faster, since the existence check skips
capture extraction) while keeping the cache for rows that do match, and leaves the
mostly-matching wins unchanged (2.9x on cheap anchored matches, 22x on the
domain-extraction pattern).

ClickHouse#111005 (comment)
Comment thread src/Functions/ReplaceRegexpImpl.h Resolved
The match-ratio checkpoint was gated on `map_enabled`, so once the
distinct-ratio guard disabled the cache, `precheck_non_matching` could
never turn itself off, and a matching suffix behind a rejecting prefix
paid the capture-free pre-check plus the full match for every remaining
row of the block. Decouple the checkpoint from `map_enabled` so the
pre-check re-evaluates itself, and cover the reject-prefix /
matching-suffix shape with a perf case and a functional test.

ClickHouse#111005 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014HRQrtSS2WFur32VEy83WU
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The failure of 03821_drop_workload_during_query_race in Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) is unrelated to this PR (workload scheduler, flaky 1/61 on rerun). The fix is in progress: #126345. The rest of CI is still running on 71fe4e8; there are no unresolved review threads.

@groeneai

Copy link
Copy Markdown
Collaborator

Update to #111005 (comment): #112966 is closed as superseded by #112890. #126191 (merged) fixed the conversion, but master 31d10e5e still returns 0 for that query because of the partition-pruning half; with #112890 it returns 1.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai for the update. The TLP Aggregate mismatch stays unrelated to this PR (it does not touch replaceRegexpOne/replaceRegexpAll); the remaining partition-pruning half is tracked in #112890. Current state of this PR at 713369d8bef: CI is green, all review threads are resolved, and no further changes are needed here.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 I merged the latest master into this branch (e361c7d9ca5, no conflicts; the branch was more than a week behind). master did not change FunctionStringReplace.h or ReplaceRegexpImpl.h since the previous merge. replaceRegexpOne.cpp and replaceRegexpAll.cpp build locally. The update from @groeneai about the unrelated TLP Aggregate mismatch was answered above; that fix is tracked in #112890. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 I merged the latest master into this branch (949a740fe76, no conflicts) to refresh CI. The two failures of the previous run at e361c7d9ca5 are unrelated to this PR:

replaceRegexpOne.cpp and replaceRegexpAll.cpp build locally after the merge. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111005&sha=949a740fe7687e91cb0b69a18bd0e7a13419dd16&name_0=PR&name_1=Build%20profile%20diff and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is the only failure at 949a740fe76: LogClusterNotReady: the endpoint never became ready in ci/jobs/build_profile_diff_job.py, which is unrelated to this PR. It looks like #120462, with a possible fix in #126200 (still open). All other checks are green, including the performance comparison, and there are no unresolved review threads.

@groeneai

Copy link
Copy Markdown
Collaborator

The Build profile diff red on 949a740 is not caused by this PR. The CI logs cluster's read-only service is at its total memory limit and rejects every query, including the SELECT 1 readiness probe: HTTP 500, Code: 241 ... current RSS: 212.84 GiB, maximum: 212.40 GiB (re-measured at 2026-10-28 01:21 UTC). The job log shows every probe failing (No connection to LogCluster) until has_pr_data raises LogClusterNotReady. In CIDB, all 336 Build profile diff runs since 2026-10-26 23:00 UTC are red (253 PRs), none green.

The fix is already in progress in my PR #126200 (related to #120462): a readiness probe that the server rejects for its own load (exception code 202 or 241) ends the job like a read rejected for load, i.e. green with CI logs cluster unavailable, nothing compared, while every other not-ready cause stays red. It is open and waiting for review.

#126200 only stops the job from failing during such an outage. The memory exhaustion of the read-only service itself is on the cluster side and needs someone with access to it.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. The only red check at 949a740fe76 is Build profile diff, failing because the CI logs cluster is out of memory, which has nothing to do with this PR. The job-side fix is in #126200, which is still open. I am not merging master again: the branch was refreshed on 2026-10-27, and master does not have the fix yet, so another merge would not clear this check. All other checks are green and there are no unresolved review threads.

@alexey-milovidov

alexey-milovidov commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

🕵 I merged the latest master into this branch (06a31c46353, no conflicts) to refresh CI. The only red check at 949a740fe76 was Build profile diff, which failed because the CI logs cluster was out of memory (see the analysis above by @groeneai). That outage is over: the check has been passing on other PRs since 2026-10-28. The merge also brings in master commit b7ad07978d7e (calling the regexp JIT matcher through callJITFunction), which touches ReplaceRegexpImpl.h. It merged cleanly, the only JIT call site in this PR already uses callJITFunction, and replaceRegexpOne.cpp and replaceRegexpAll.cpp build locally. There are no unresolved review threads.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 I merged the latest master into this branch (187f77315ed, no conflicts) because the branch was more than a week behind. master did not change FunctionStringReplace.h, ReplaceRegexpImpl.h, or ReplaceRegexpModeController.h since the previous merge, and replaceRegexpOne.cpp and replaceRegexpAll.cpp pass a local syntax check. All checks were green at 06a31c46353, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 I merged the latest master into this branch (e3f441d945b, no conflicts) because the branch was more than a week behind. On the master side, the only changes to the files this PR touches are the [[nodiscard]] annotations in FunctionStringReplace.h. replaceRegexpOne.cpp and replaceRegexpAll.cpp compile on the merged tree. The new master test 05401_replace_regexp_all_quantified_caret (optional leading ^) does not conflict with the required-prefix skip, because the prefix comes from RE2's RequiredPrefix, which reports a prefix only for a mandatory anchor. CI was green before the merge, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The arm_tidy builds failed on modernize-use-nodiscard for carriedWindow, useCache and usePrecheck in ReplaceRegexpModeController.h. I marked them [[nodiscard]] in cad1895f6a5; all other builds were green, and the branch is current with master.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111005&sha=cad1895f6a539186b5d6f92f6576136808dbd783&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%202%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The only red check at cad1895f6a5 is Performance Comparison (amd_release, master_head, 2/6): hashing_serialized_values query #1 (sipHash64 over a JSON column) was 16% slower. This PR only changes replaceRegexpOne and replaceRegexpAll, which that query does not use. The same query also shows as slower on master (2026-11-06 and 2026-11-10) and on unrelated PRs #114043, #130906 and #129615, so the test itself is unstable. I found no open issue or PR for it. The branch was merged with master on 2026-11-16, and every other check is green.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating why hashing_serialized_values query #1 is still unstable on amd after #124728 (the test is mine); I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

I opened #132468, which disables hashing_serialized_values query #1 (disabled="1", so #0 and #2 keep their history) and removes the json_values table that only it read.

The red here comes from the code layout of each build, not from this PR: in this job both servers ran the same work (7.333G vs 7.337G instructions), but this PR's binary took one extra branch miss per row in the JSON hash loop (4.143M vs 0.125M over 4M rows). ASLR is off in the job, so the slow mode is fixed per binary: the confirmation reruns at three stack placements and the dashboard reruns all reproduced it, and the job's two binaries reproduce it locally (0.495 vs 0.595 s). #124728 made this rarer but did not remove it.

One correction to the list: my #129615 does change the code path of #1 (about 11% fewer instructions), so it is not unrelated, although its red shows the same one-extra-miss-per-row pattern.

27rohan pushed a commit to 27rohan/ClickHouse that referenced this pull request Nov 18, 2026
…rmance test

Query 1 (sipHash64 over a JSON column) failed Performance Comparison
(amd_release) on PRs that do not touch its code path (ClickHouse#111005: 0.526 ->
0.611 s, and another PR: 0.534 -> 0.660 s) and is marked slower on
master runs.

Both servers execute the same work (7.333G vs 7.337G instructions in the
ClickHouse#111005 job, within 0.15% in 18 of the 19 profiled runs; the 19th is a
PR that changes this loop), but the per-row loop through
SerializationObject, SerializationDynamic, path iteration and four
hash-map lookups lands in a slow mode in some builds: one or two extra
branch misses per row (0.125M vs 4.143M over 4M rows in the ClickHouse#111005
job), or more cycles at equal misses. ASLR is off, so the mode is fixed
per binary: the confirmation reruns at three stack placements and the
dashboard reruns all reproduced +16.5%. The red job's two binaries
reproduce it locally (0.495 vs 0.595 s, same instructions, 1M vs 21M
branch misses over 5 runs).

Shortening the loop does not remove the dependence (the remaining frames
are about 30% slower in the slow builds too), so the query is disabled with
disabled="1", which keeps the numbers and history of queries 0 and 2, and
the json_values table that only it read is removed. Query 0 still measures
the row-by-row serialization branch of executeGeneric, query 2 the
aggregate-state path.

Related: ClickHouse#111005

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. #132468, which disables the unstable hashing_serialized_values query #1, is merged, so I merged the latest master into this branch (5b59788e483, no conflicts) to pull it in and clear the only red check. master did not touch any file this PR changes, and replaceRegexpOne.cpp and replaceRegexpAll.cpp compile on the merged tree. There are no unresolved review threads.

This branch has not been deployed

No deployments
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 comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants