Skip to content

Do not update profile events once per row in CAST to Nullable(Bool), arrayIntersect and multiMatch - #122920

Merged
Algunenano merged 6 commits into
ClickHouse:masterfrom
groeneai:batch-per-row-profile-events
Sep 30, 2026
Merged

Algunenano merged 6 commits into
ClickHouse:masterfrom
groeneai:batch-per-row-profile-events

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122764 (review)
Related: #113021

Changelog category (leave one):

  • Performance Improvement

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

CAST of strings to Nullable(Bool) (also accurateCastOrNull(s, 'Bool') and toBool of a Nullable(String)) is up to 7 times faster with 8 threads, and arrayIntersect, arrayUnion, arraySymmetricDifference and arrayJaccardIndex over non-numeric elements such as DateTime64, UUID or Tuple are up to 18 times faster with 8 threads: they no longer allocate memory and update profile events for every row. multiMatchAny and the other multi-regexp functions with non-constant needles now add their cache hit and miss counts once per block.

Description

A follow-up of #122764: other functions that updated a profile event for every row. Each such update is an atomic add on the query-level counter, one cache line shared by all threads of the query, so these queries did not get faster with more threads.

  • SerializationNullable::deserializeWholeText constructed PeekableReadBuffer(istr, true) for every value. Since 6e8c2ab the second parameter is a start size, so true allocated an unused one-byte buffer (IOBufferAllocs) per row. The six such calls now use the default size.
  • Since Build the arrayIntersect hash map from the smallest argument #113021 the key arena of the generic path of arrayIntersect and its siblings was recreated at every row, one new chunk (ArenaAllocChunks) per row; this slowed them down in 26.8. The arena is now recreated only once it holds more than 64 KiB, so its memory stays bounded (by about 128 KiB, or by one row when a row needs more).
  • MultiRegexps::getOrSet incremented RegexpWithMultipleNeedlesGlobalCacheHit/Miss per row for non-constant needles. The caller now counts them and adds them once per block, as LocalCacheTable does since Count regexp cache hits once per block in LIKE and match with a non-constant pattern #122764; the totals are unchanged.

Release build, 8 pinned cores, median of 7, 1 / 8 threads, before -> after: CAST(s AS Nullable(Bool)) over 4M rows 0.629 / 0.465 -> 0.466 / 0.065 s; arrayIntersect over DateTime64 arrays, 4M rows, 0.415 / 0.472 -> 0.160 / 0.026 s; the Bool and DateTime controls are unchanged. multiMatchAny with reject_expensive_hyperscan_regexps = 0, 400K rows, 8 threads: 0.218 -> 0.185 s. The new tests check these counters, the multiMatch batching (trace_log) and a memory bound for arrayIntersect.

Checked and not changed, because the per-row work there costs far more than the counter or is not per row: WebAssembly UDF row calls, formatRow with JSON or XML, file, the ai* functions, estimateCompressionRatio, arrayFold, sleep, and executable UDFs.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 5 commits September 29, 2026 14:05
… text

The second constructor parameter of `PeekableReadBuffer` used to be
`bool use_existing_memory`. Since 6e8c2ab (2021) it is
`size_t start_size_`, so the `true` that six callers still pass became a
start size of one byte. Each such construction heap-allocates a buffer
that is never used (the peekable buffer starts on its stack memory and,
when that is not enough, allocates at least `DBMS_DEFAULT_BUFFER_SIZE`
from scratch) and increments `IOBufferAllocs` and `IOBufferAllocBytes`.

`SerializationNullable::deserializeWholeText` constructs one per value,
so `CAST(s AS Nullable(Bool))`, `accurateCastOrNull(s, 'Bool')`, `toBool`
of a `Nullable(String)` and `accurateCastOrNull(s, 'JSON')` did one
allocation and two profile event updates per row. The profile event
counters of a thread group are shared by all threads of the query, so the
query did not get faster with more threads (26.9, 4M rows: 0.554 s with
1 thread and 0.502 s with 8, while `CAST(s AS Bool)` takes 0.224 s and
0.036 s).

Use the default start size at all six sites. The other five construct the
buffer only when the input buffer ends inside a NULL check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#113021 (a073320, a7ce761) the arena holding the
serialized keys of the generic path is recreated at a row boundary
whenever it holds anything, to bound its memory by one row. `Arena`
allocates its first chunk lazily, so every row that stores a key
allocated a new 4 KiB chunk and incremented `ArenaAllocChunks` and
`ArenaAllocBytes`. The generic path serves every element type except
numbers, `Decimal`, `Date`, `Date32`, `DateTime`, `String` and
`FixedString` (for example `DateTime64`, `UUID`, `IPv4`, `IPv6`, `Enum`,
`Tuple`, `Array`, `Map`) in `arrayIntersect`, `arrayUnion`,
`arraySymmetricDifference` and `arrayJaccardIndex`. The profile event
counters of a thread group are shared by all threads of the query, so the
function stopped scaling with threads: `arrayIntersect` over `DateTime64`
arrays, 4M rows, took 0.264 s with 1 thread and 0.044 s with 8 on 26.6,
and 0.454 s and 0.649 s on 26.8.

Recreate the arena only once it holds more than 64 KiB. Its memory stays
bounded by 64 KiB plus one growth step, or by one row when a single row
needs more; the keys of earlier rows are dead after `map.clear()`, and an
arena grown by a large row is still recreated at the next row boundary.
With 64 KiB the first chunk is kept on 4 KiB, 16 KiB and 64 KiB pages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
The query log of three 1000-row single-block queries: `CAST` to
`Nullable(Bool)` must not allocate an IO buffer per row, `arrayIntersect`
over `DateTime64` arrays must not allocate an arena chunk per row, and
`multiMatchAny` with non-constant needles must still count one global
cache lookup per row (the totals are added once, per block). On the
unfixed build the first two rows show `IOBufferAllocs` and
`ArenaAllocChunks` of about 1000; removing the flush of the multiMatch
counters turns the third row's 1000 into 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ound in the test

The number of `trace_log` entries is the only difference of the
batching that is visible from SQL. The query with 10 KB keys fails with
`MEMORY_LIMIT_EXCEEDED` if the arena is never reclaimed. The
`query_log` check selects its rows by exact `log_comment`: the new query
and `SYSTEM FLUSH LOGS` carry the runner's default one, which also
starts with `05293_`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 29, 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; 2 findings on the first pass, 0 on the recheck of the fix round) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The arrayIntersect query of the test never crosses the 64 KiB arena bound, so removing the reclamation would stay green AGREE, fixed @ 7e8b89d A block of 10 KB keys now runs under max_memory_usage; it fails with MEMORY_LIMIT_EXCEEDED when the arena is never reclaimed
2 ⚠️ The multiMatch row checks only hit + miss totals, which are the same with per-row updates AGREE, fixed @ 7e8b89d The test now also checks system.trace_log: one entry per counter and block instead of one per row
3 💡 Commit message of the Nullable change calls the JSONUtils empty-string check a NULL check noted Wording only

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

Session id: cron:clickhouse-review-slot-10:20260929-161200

@groeneai
groeneai requested a review from Algunenano September 29, 2026 16:47
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [218fdcf]

Summary: ✅


AI Review

Summary

This PR batches the remaining per-row profile-event updates in SerializationNullable/SerializationVariant/JSONUtils, the shared array set implementation, and non-constant-needle multiMatch* execution. On the current head, I did not find a material correctness, coverage, or metadata issue that still needs action.

Missing context / blind spots
  • ⚠️ The full build-and-test matrix is still pending in CI. Green build shards and the remaining stateless/integration jobs would close the last compatibility blind spot.
Final Verdict

✅ No new blockers or majors found in the current revision.

LLVM Coverage Report

Measured on commit 218fdcf.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 62/62 (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 29, 2026
@Algunenano Algunenano self-assigned this Sep 29, 2026
Comment thread src/Formats/JSONUtils.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 29, 2026
A `use-vectorscan` test is skipped on builds without vectorscan
(`Fast test` and `Fast test (arm_darwin)`), and the tag skipped the
`Nullable(Bool)` and `arrayIntersect` checks as well, although neither
depends on vectorscan. They stay in 05293 without the tag, and the
multiMatch check moves to 05294.

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 218fdcf37 with master 80508bd5f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 61fda56c2; 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

50 translation units recompiled, 206 s compile time in total, 50 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 37 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: 5e65ad8d-d99f-43ee-a71d-5a1784791a66
  • MIRAI run: c128e81e-1f49-4cbb-b885-016c875c84c7
  • PR check IDs:
    • clickbench_2444363_1790713700
    • clickbench_2444369_1790713700
    • clickbench_2444375_1790713700
    • tpch_adapted_1_official_2444386_1790713700
    • tpch_adapted_1_official_2444396_1790713700
    • tpch_adapted_1_official_2444433_1790713700

@Algunenano
Algunenano added this pull request to the merge queue Sep 30, 2026
Merged via the queue into ClickHouse:master with commit 61e7503 Sep 30, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 2026
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-review-human PR origin: human review feedback on a groeneai PR 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.

3 participants