Skip to content

Count distinct bytes in stringBytesUniq without a per-row stack bit mask - #125680

Merged
rschu1ze merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/stringbytesuniq-no-per-row-stack-mask
Nov 11, 2026
Merged

rschu1ze merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/stringbytesuniq-no-per-row-stack-mask

Conversation

@groeneai

@groeneai groeneai commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115988

Changelog category (leave one):

  • Performance Improvement

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

Function stringBytesUniq is up to 2.3 times faster on long strings.

Description

string_bytes_functions query #0 (SELECT sum(stringBytesUniq(s))) runs at one of two speeds per arm binary, 0.050 or 0.061 s, so it is slower whenever a PR's binary draws the other mode than its reference: 21 arm PRs plus master in 30 days, never on amd, e.g. #115988 perf 5/6.

StringBytesUniqImpl::process keeps UInt64 mask[4] on the stack and, for every row, zeroes it with one 32-byte store, sets bits with 8-byte stores, then reloads it with one 32-byte load. Its machine code is identical in 8 arm builds; the 4 slow ones are exactly those where the stack depth at entry makes the mask 32-byte aligned, which unrelated caller frames change (#124599, #112705).

The change keeps, per call, the last row number that contained each byte value. A byte is new in a row exactly when its entry is smaller than the row number, so nothing is reset between rows. The only stack accesses left are an aligned 8-byte load and store per byte (checked in the aarch64 object).

x86 release build (Xeon 6975P), median of 30 runs, speed-up vs master:

strings 1 thread 16 threads
0/1 byte (the perf test) 1.16x 1.05x
URLs, ~54 B 1.38x 1.36x
random 8 / 16 / 64 / 256 B 1.29x / 1.22x / 1.06x / 1.18x 1.30x / 1.10x / 1.03x / 1.13x
text, ~1 KB 2.28x 2.00x

stringBytesEntropy (unchanged) 0.99x. Tests: two single-threaded long-string queries (text, random 64 B) in the string_bytes_functions perf test. This PR's arm perf comparison: query #0 0.063 -> 0.035 s, text 0.71 -> 0.29 s, random 64 B 0.24 -> 0.17 s.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1998-master (included in 26.11 and later)

groeneai and others added 4 commits October 13, 2026 18:16
… mask

`StringBytesUniqImpl::process` kept a 32-byte `UInt64 mask[4]` on the stack and,
for every row, zeroed it with one 32-byte store, did a load-or-store per byte and
reloaded all 32 bytes for the popcount. On aarch64 the speed of that per-row
store/reload depends on the alignment of `mask`, which is decided by the stack
depth at the call, i.e. by unrelated caller frames: `executeImpl` is identical in
8 arm builds, 4 fast and 4 slow, and the slow ones are exactly those where `mask`
lands 32-byte aligned (depth at entry mod 32 = 16). ClickHouse#124599 (thread pool worker
frame 592 -> 608 bytes) flipped master to fast, ClickHouse#112705
(`ExpressionTransform::transform` 400 -> 480 bytes) flipped it back to slow, so
`string_bytes_functions #0` runs at 0.050 or 0.061 s per arm binary and is
reported `slower` on PRs whose binary draws the other mode than its reference
(21 PRs plus master in 30 days on arm_release, none on amd_release).

Count with a per-call table of the last row number in which each byte value
occurred instead. It is zeroed once per `executeImpl` call and never cleared
between rows, so the only per-row stack traffic left is the 8-byte, 8-aligned
load and store of the table entry per byte. `alignas` on `mask` was rejected:
the 32-byte-aligned placement is the slow one, so it would pin every build to
the slow mode. A register-resident mask was measured 1.2-1.85x slower on x86.

`FunctionStringBytes::executeImpl` now calls `process` on a local `Impl`, and
`StringBytesEntropyImpl::process` becomes a `const` member; entropy's machine
code is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y` as is

Entries of `last_seen_row` never exceed the current row number, so a byte is new in this
row exactly when its entry is smaller. On x86 the byte loop becomes 7 instructions instead
of 9 (`cmp` + `adc` instead of `xor` + `setne` + `add`), the same count as the old bit mask,
which removes the slowdown the `!=` form had on random binary strings.

The `stringBytesEntropy` hunk is not needed: `impl.process` calls the static member, and
clang-tidy does not flag it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The existing queries only use 0/1-byte strings, so CI did not measure the byte loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the design note from the `last_seen_row` comment, keep its invariant.

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 Oct 13, 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 rounds, 1 finding) plus my own review (two rounds, nits only).

# Sev Finding Verdict Evidence / action
1 ⚠️ The perf test only had 0/1-byte strings, so CI measured neither the long-string speed-up nor the byte-loop cost on arm AGREE, fixed in 5b3fee9 two single-threaded long-string queries in string_bytes_functions; x86 text 2.38x, random 64 B 1.06x (n = 30)
2 💡 Changelog entry stated an arm effect that is not measured AGREE, fixed in the PR text the entry keeps only the measured x86 claim
3 💡 The 2 KiB table is zeroed once per call DISAGREE one 2 KiB memset per block; the 0/1-byte shape (256M rows) is still 1.16x faster single-threaded

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261013-201000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The arm speed is fixed per binary (every run of a binary is at one level). Locally (no arm host) the deterministic oracle is the aarch64 object of stringBytesUniq.cpp: master has a per-row 32-byte stp q0, q0 zeroing and ldp q2, q3 reload of the stack mask; this PR has neither.
b Root cause explained? The per-row 32-byte store and reload of UInt64 mask[4] runs at two speeds depending on the mask's stack alignment. executeImpl is identical in 8 arm builds; the 4 slow ones have the mask 32-byte aligned, which unrelated caller frames change (#124599, #112705).
c Fix matches root cause? Yes: the per-row stack array is removed. alignas(32) was rejected because the aligned placement is the slow one.
d Test intent preserved / new tests added? 03442_string_bytes_functions compares stringBytesUniq with arrayDistinct on 30000 strings (0..69 bytes, 30 blocks): 30000 0. A mutant without ++row gives 29571 mismatches. The string_bytes_functions perf test gains two single-threaded long-string queries (text ~1 KB, random 64 B).
e Both directions demonstrated? aarch64 object: master vs PR as in (a). Oracle: PR 30000 0, mutant 30000 29571. x86 release A/B, n = 30: 1.06x to 2.28x single-thread on 7 shapes, 1.03x to 2.00x at 16 threads, stringBytesEntropy control 0.99x. New perf queries: text 2.38x, random 64 B 1.06x.
f Fix is general across code paths? StringBytesUniqImpl::process is the only implementation and FunctionStringBytes::executeImpl its only caller. stringBytesEntropy shares the template; its source is unchanged and its object code identical.
g Fix generalizes across inputs (params/datatypes/wrappers)? Const, Nullable and LowCardinality reach the same executeImpl through the default implementations. Empty strings return 0 (03593). All 256 byte values and lengths up to ~1 KB give identical sums vs master on 7 tables.
h Backward compatible? (maintainer-approved exception only) Yes: same results and type, no setting, format or serialization change.
i Invariants and contracts preserved? Table entries are written only with the current row number, which only grows, so entry <= row. The table is local to each executeImpl call (zeroed, row 0, first row 1). No cross-block or cross-thread state; a UInt64 row cannot wrap.

Session id: cron:clickhouse-impl-slot-4:20261013-191000

@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ab0812]

Summary: ✅


AI Review

Summary

PR #125680 replaces the per-row bitmask in stringBytesUniq with per-block byte timestamps and adds long-string performance cases. Reviewed head 8ab08121a5d920d4a060bdd6d517f9af14866391, the shared execution paths, existing correctness coverage, and all prior discussion. No actionable findings remain; focused CI measurements support the performance claim on both x86 and ARM.

Missing context / blind spots
  • ⚠️ Latest-head CI is still running. The completed run at 62bc0cac passed the function test and measured the same implementation and performance cases. The final commit only removes a comment and restores existing stateless tests. Completion of current checks would close this validation gap.
Final Verdict

Status: ✅ Approve. No review changes required.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR only rewrites stringBytesUniq, replacing per-row bitmasks with a last-seen-row table reused across rows, and adds tests for it. None of the ClickBench or TPC-H queries call that function. ClickBench Q20 still shows an improvement (-44.1%, CPU time roughly halved). The verdict is fixed by the large-change rule, but this diff cannot cause it, so it most likely reflects a build or baseline difference and should not count as a gain from this PR. Q28 is borderline, and Q33/Q34 at -6.8% sit inside master's normal variance band. Neither result is linked to this change, so the PR's actual effect should be judged with the string_bytes_functions perf test it adds.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 123 -44.1% <0.0001 Locked by the hard trust rule (-44.1%, CPU time roughly halved). This query never calls stringBytesUniq, so the PR's change cannot explain the shift. Check whether the build or baseline differs.
⚠️ 28 not_sure 1058 1000 -5.5% <0.0001 Borderline -5.5%, and the two tests disagree on noisy measurements. The query does not use stringBytesUniq.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 085da4d4-6e9a-43ff-9db3-3561d17d99d6
  • MIRAI run: fe733385-0bbb-457b-985c-6a50b6e5ecff
  • PR check IDs:
    • clickbench_81351_1791937340
    • clickbench_81462_1791937352
    • clickbench_81571_1791937369
    • tpch_adapted_1_official_81694_1791937401
    • tpch_adapted_1_official_81816_1791937470
    • tpch_adapted_1_official_81926_1791937489

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8094f27

Every failure below has an owner: a fixing PR (mine 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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04227_materialized_cte_reused_with_in_subquery not from this PR (it only changes stringBytesUniq): Code: 60 UNKNOWN_TABLE for _materialized_cte_ct_* when a reused MATERIALIZED CTE feeds an IN subquery on parallel replicas. The fix merged after the tree of this run was pinned #123121 (mine, merged)

Mergeable Check and PR are the rollups of this row.

Session id: cron:our-pr-ci-monitor:20261014-040009

@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

@groeneai Merge from master.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in 62bc0ca (no conflicts; the diff against master is unchanged).

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8ab08121a with master c8b19e5bc (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.88, programs/clickhouse-keeper ×1.11 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 8.2 s 16.5 s +9.4 s (+131%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.0 s 8.6 s +5.1 s (+146%)
Compile time of recompiled translation units

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

Job report

Comment thread src/Functions/stringBytesUniq.cpp Resolved
UInt64 mask[4] = {0};
const UInt8 * end = data + size;
/// For each byte value, the number of the last row that contained it (never greater than `row`).
std::array<UInt64, 256> last_seen_row{};

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.

Can we not change this to an array of 256 bits (unsigned char)?

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.

A 256-bit mask has to be cleared for every row, and that per-row 32-byte stack array is what made the arm speed depend on its alignment. So each entry holds a row stamp instead, and nothing is cleared between rows.

I tried std::array<UInt8, 256> stamps (cleared every 255 rows): same results, but on an x86 release build (1 thread, median of 30) it is slower than UInt64 on longer strings and equal on short ones:

strings UInt64 UInt8
text, ~1 KB 0.574 s 0.604 s
random, 16 B 0.250 s 0.277 s
random, 256 B 0.369 s 0.379 s

So I kept UInt64 (2 KiB on the stack per call). If you prefer the smaller array anyway, I'll switch.

03442_string_bytes_functions is back to master's version, as asked.

The table stays std::array<UInt64, 256>. A 256-bit mask has to be
cleared for every row, which is the per-row clear this change removes.
A std::array<UInt8, 256> of row stamps (cleared every 255 rows) gives
the same results, but on x86 release (median of 30, 1 thread) it is
5-10% slower than UInt64 for 16 B to 1 KB strings: text ~1 KB 0.574 ->
0.604 s, random 16 B 0.250 -> 0.277 s, random 256 B 0.369 -> 0.379 s;
short strings are the same.

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

rschu1ze commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

This isn't totally terrible, thanks.

@rschu1ze
rschu1ze added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit 1d9e172 Nov 11, 2026
187 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 11, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 18, 2026
For every row, `StringBytesEntropyImpl::process` zero-filled a 1 KiB
counter table and then scanned all 256 counters with a branch each, so
every call paid about 70 ns whatever the string's length. Query 1 of the
`string_bytes_functions` performance test (256M strings of 0 or 1 byte,
all of entropy 0) measures only that cost: 3.1 s on amd and 2.5 s on arm
per master commit.

The row's smallest and largest byte are now found in a separate loop,
which vectorizes, and the result scan covers only that range, in the
same ascending order. The counters are a member of the `Impl`, zeroed
once per `executeImpl` call as in `stringBytesUniq` since ClickHouse#125680, and
the scan resets every counter it reads, so the table is zero again
before the next row. The skipped counters were zero and never reached
the sum, so the same terms are added in the same order and the result
is bit-identical (checked against master on 200,000 generated strings
plus edge rows, at block sizes 1, 7 and 65409, plain, `Nullable` and
`LowCardinality`).

Release build, single thread, time PR / master: 0/1-byte strings 0.064,
`toString(number)` 0.45, host names 0.69, 32-char hex 0.58, 1 KB text
0.79, random 16 / 64 bytes 0.92 / 0.98, random 4 KiB / 64 KiB / 4 MiB
0.94 / 0.95 / 1.02, `stringBytesUniq` 0.99. `perf.py` over the unchanged
test, both seat orders: query 1 0.066, queries 0, 2 and 3 0.97-1.00.
Long strings that use nearly all 256 byte values gain nothing from the
narrower scan and pay for the extra pass.

Related: ClickHouse#129258

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.

3 participants