Skip to content

Count regexp cache hits once per block in LIKE and match with a non-constant pattern - #122764

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:regexp-local-cache-batch-profile-events
Sep 29, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:regexp-local-cache-batch-profile-events

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121795 (comment)
Related: #100759

Changelog category (leave one):

  • Performance Improvement

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

LIKE, ILIKE, match and their variants are up to 5 times faster with 8 threads when the pattern is not a constant. The RegexpLocalCacheHit and RegexpLocalCacheMiss profile events are now added once per block instead of once per row, which removes contention on a counter shared by all threads of the query.

Description

re2_regex_caching #3 (like with 10 distinct non-constant patterns) was red in Performance Comparison (amd_release, master_head, 3/6) on #121795, which does not touch this code: job, 0.0742 -> 0.1096 s. Over the last 14 days of amd runs (801), #3, #5 and #6 moved by 30% or more in 198, 189 and 120 runs; the constant-pattern queries of the same test in 0 or 1.

Cause. With a non-constant pattern, Regexps::LocalCacheTable::getOrSet runs once per row and incremented RegexpLocalCacheHit or RegexpLocalCacheMiss each time. Since #105056 the user and global levels of ProfileEvents are per-CPU, but the thread group level is a single row, so every thread of the query did an atomic add on the same cache line per row. In the CI CPU profiles that increment is 53-71% of the samples of #3 and #5, and in the red run the whole difference between the two servers is in it (1210 vs 2328 samples, the rest 1058 vs 986).

Change. The table counts hits and misses in two members and adds them once, in its destructor. It is a local of the per-block function, so per-query totals are unchanged.

Validation. Release build, 8 threads on 8 physical cores, 10 server processes per binary: #3 and #5 90 -> 18 ms, #6 94 -> 34 ms, others unchanged; user CPU at 8 threads over 1 thread goes from 5.2 to 1.0 for #3. The new performance test like_match_nonconst_pattern measures String, FixedString and constant haystacks: 1.12-1.23 -> 0.15-0.17 s with perf.py. The stateless test checks the exact hit and miss totals for the same three.

multiMatch* with non-constant needles uses a different, mutex-protected global cache and is not changed.


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

Version info

  • Merged into: 26.10.1.987-master (included in 26.10 and later)

groeneai and others added 2 commits September 28, 2026 20:46
`Regexps::LocalCacheTable::getOrSet` incremented `RegexpLocalCacheHit` or
`RegexpLocalCacheMiss` on every lookup, and `MatchImpl::matchOneRow` does
one lookup per row whenever the pattern of `LIKE`/`match` is not a
constant. `ProfileEvents::increment` does an atomic add at every level of
the counter chain. The user and global levels are per-CPU since ClickHouse#105056,
but the thread group level is a single row, so every thread of the query
wrote the same cache line on every row. The query was bound by that line:
`re2_regex_caching` `ClickHouse#3` took 91 ms at both 8 and 32 threads, and its cost
differed between server processes, which made `ClickHouse#3`, `ClickHouse#5` and `ClickHouse#6` of that
test noisy on the amd performance shards.

The table now counts hits and misses in two members and adds them to
ProfileEvents once, in its destructor. A table is a local of
`vectorVector`/`vectorFixedVector`/`constantVector`, so it lives for one
block on one thread: the totals per query are unchanged (a miss is still
counted before `createRegexp`, so a failed compile still reports it), and
the shared counter is written twice per block instead of once per row.
Tables that did no lookup report nothing, as before. With
`trace_profile_events = 1` these two events now give one `trace_log` row
per block (with the block total) instead of one per row.

Release build, 8 threads pinned to 8 physical cores, 10 server processes
per binary: `ClickHouse#3` and `ClickHouse#5` 90 -> 18 ms, `ClickHouse#6` 94 -> 34 ms, the other queries
of the test unchanged; user CPU at 8 threads over 1 thread for `ClickHouse#3` goes
from 5.2 to 1.0. At 32 threads `ClickHouse#3` goes from 91 to 15 ms.

The new test checks the exact hit and miss totals for the three callers
(String, FixedString and constant haystacks).

Related: ClickHouse#121795, ClickHouse#100759

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the comment on the batched hit/miss counters: 'contend on' instead of 'hit', which read as a cache hit next to the hits member.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test passes with the batching reverted: it checks totals, not how often the counter is written. DISAGREE The only SQL-visible difference is the trace_log row count with trace_profile_events = 1, and those rows are best-effort (the trace pipe drops records on EAGAIN, TraceCollector.cpp:84); an exact trace_log check was removed from 02494_trace_log_profile_events as flaky (bbcd389). The speed-up is covered by re2_regex_caching #3/#5/#6; the new test fails (0 0) if the flush is removed.
2 💡 The exact Miss = 10 assumes the 10 patterns hash to distinct buckets of the 1000-entry table. noted Deterministic with the current std::hash; 50 randomized runs gave 990/10 each time.
3 💡 Changelog entry wording was redundant (ILIKE is the case-insensitive LIKE). fixed Reworded.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-10:20260928-205300

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49c0193]

Summary: ✅


AI Review

Summary

This PR batches RegexpLocalCacheHit and RegexpLocalCacheMiss updates per block in Regexps::LocalCacheTable and adds focused stateless and performance coverage for the non-constant-pattern LIKE / match path. I did not find a correctness, safety, compatibility, or evidence gap in the current patch.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 49c0193.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 28, 2026
@groeneai
groeneai requested review from azat and rschu1ze September 28, 2026 21:38
@@ -0,0 +1,15 @@
-- Regexp cache hits and misses of LIKE and match with a non-constant pattern are counted exactly.

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 Write a xml performance test

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.

Added tests/performance/like_match_nonconst_pattern.xml in 49c0193: the String, FixedString and constant haystacks of this test, each with a non-constant pattern of 10 distinct values over 20M rows. Release build, perf.py with both servers pinned to the same 8 cores: 1.12-1.23 s before, 0.15-0.17 s after.

I kept 05292: with the flush in the destructor removed it reports 0 hits and 0 misses, which the performance test cannot see (the query only gets faster). I can drop it if you prefer.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 28, 2026
The three haystack kinds of 05292 (String, FixedString and a constant),
each with a non-constant pattern of 10 distinct values over 20M rows.

Release build, perf.py with both servers pinned to the same 8 physical
cores: 1.12-1.23 s before this change, 0.15-0.17 s after it (-86% to -88%,
p < 1e-8). Four fix-vs-fix runs with fresh servers stay within 3.1%, with a
stat_threshold of at most 0.123.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49c019325 with master 0b1dbc7b4 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

46 translation units recompiled, 192 s compile time in total, 46 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 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: e812d14f-499e-4641-98d9-6d65de29ad2e
  • MIRAI run: 9eb58bca-04df-4128-9863-2d9e4e0790ad
  • PR check IDs:
    • clickbench_2320421_1790644225
    • clickbench_2320434_1790644224
    • clickbench_2320440_1790644224
    • tpch_adapted_1_official_2320447_1790644224
    • tpch_adapted_1_official_2320477_1790644224
    • tpch_adapted_1_official_2320491_1790644225

@Algunenano Algunenano self-assigned this Sep 29, 2026

@Algunenano Algunenano left a comment

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.

Nice finding. @groeneai Could you please look if other functions might have similar issues where they update profile events per row? If it does, could you address them in a PR and ping me / assign it to me please? No need of performance tests in that one

@Algunenano
Algunenano added this pull request to the merge queue Sep 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm auditing the other functions for ProfileEvents updated once per row; I'll follow up here with a separate PR (requesting your review on it), or with my findings if there is nothing else to fix.

Merged via the queue into ClickHouse:master with commit 00410e2 Sep 29, 2026
149 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 Sep 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano The follow-up is #122920, with your review requested. It fixes three paths that updated profile events for every row: CAST of strings to Nullable(Bool), arrayIntersect and its siblings over elements such as DateTime64 or UUID, and multiMatch* with non-constant needles. No performance test, as you asked; the other paths I checked and left unchanged are listed in its description.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 30, 2026
…eedles

`MultiRegexps::getOrSet` incremented
`RegexpWithMultipleNeedlesGlobalCacheHit` or `...Miss` on every call,
inside the critical section of the process-wide cache mutex. With a
non-constant array of needles, `vectorVector` calls it once per row, so
`multiMatchAny`, `multiMatchAnyIndex`, `multiMatchAllIndices`,
`multiFuzzyMatchAny`, `multiFuzzyMatchAnyIndex` and
`multiFuzzyMatchAllIndices` updated a profile event per row. The profile
event counters of a thread group are shared by all threads of the query
(26.9, 400K rows with `reject_expensive_hyperscan_regexps = 0`: 0.079 s
with 1 thread, 0.213 s with 8). This is the shape `LocalCacheTable` had
before ClickHouse#122764.

Count hits and misses in a `GlobalCacheCounters` owned by the caller and
add them to ProfileEvents once, in its destructor, which also keeps the
counts when the loop throws. The two per-row callers keep one for the
whole block; the callers that look up once (constant needles, text index
analysis) use a two-argument overload that adds them after the lookup.
The totals are unchanged.

Co-Authored-By: Claude Opus 5.5 <[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 comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements 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