Skip to content

Copy runs of rows that take the same branch at once in if over String - #131699

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:if-string-copy-runs-v2
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:if-string-copy-runs-v2

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130929

Changelog category (leave one):

  • Performance Improvement

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

if with a String result is faster when a branch is a String column, also for CASE with a single WHEN. Single-threaded on x86, evaluating if(c, MobilePhoneModel, 'unknown') with a random condition is 2.8x faster, and evaluating the CASE of ClickBench Q39 is 1.4x faster.

Description

GatherUtils::conditional handles one row per step: it grows the result, branches on the condition and copies the row. The new GatherUtils/conditional.cpp adds conditional overloads for two String sources (at least one a column) into a StringSink. They read the condition 64 rows at a time (bytes64MaskToBits64Mask). A group with at most 16 runs of equal conditions is copied run by run: one copy per run, whose offsets are the source's, shifted. Other groups are written row by row into the reserved result, with a branch when the condition alternates (predictable) and without one otherwise. if.cpp, multiIf, FixedString and constant/constant are unchanged.

On aarch64 a group whose column sources average at least 64 bytes per row is also copied run by run: on Graviton 3 this takes 64- and 128-byte strings in runs of 2 rows from 1.28 and 1.76 of master to 0.68 and 0.79 (#130929). x86 does not use it: the #130929 kernel, which has it, made 65-byte strings in short runs slower than master (up to 1.110 [1.042, 1.182]); without it none of 78 shapes is significantly slower (closest: 1.048 [0.999, 1.099]).

x86 (Xeon 6975P-C), SELECT count() FROM t WHERE NOT ignore(<expr>) SETTINGS max_threads = 1, 10M rows, 6 rounds, ratio = PR / master [95% CI]:

  • if(c_nat, Referer, '') (Q39's condition) 0.718 [0.682, 0.755], if(c_64, Referer, '') 0.618 [0.587, 0.652]
  • random condition: if(c, SearchPhrase, '') 0.509, if(c, MobilePhoneModel, 'unknown') 0.353, if(c, s16, t16) 0.531
  • alternating condition: 0.61-0.79 for 0-16-byte strings, 0.97-0.98 for 64-65 bytes (CI includes 1)
  • results identical (sum(cityHash64(...)) of 80 expressions)

Tests: 05768_if_string_runs checks every path (column/column, column/constant, constant/column, tail groups, growth past the reserve, Nullable, CASE) against an arrayElement oracle; if_string_runs.xml has the gain shapes, the ones a first version made slower, and 64-byte strings in runs of 2 rows.


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

groeneai and others added 5 commits November 14, 2026 20:22
…over `String`

`if(cond, s, t)` with a `String` result and a `String` column in a branch goes through
`GatherUtils::conditional`, which handles one row per step: it grows the result, branches on the
condition and copies the row with the 16-byte small-copy loop. For two `String` sources, at least
one a column, `conditional.cpp` reads the condition 64 rows at a time. A group with few runs of
equal conditions is copied run by run: the rows of a run are contiguous in the source they take, so
the run is one copy and its offsets are the source's, shifted. Other groups are written row by row
into the reserved result, with a branch on the condition when it alternates (predictable) and
without one otherwise. Other sources and sinks are unchanged.

Analysis and patch: ClickHouse#130929

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…over `String`

For `begin == 0` the size_t index `begin - 1` wrapped the raw offsets pointer by SIZE_MAX. The address
is the intended `offsets[-1]` (the zero in the left padding), but UBSan reports the pointer overflow
and aborts. The machine code of the release build is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`tests/performance/scripts/README.md` says queries over a `Memory` table bigger than 1 GB can be
unstable. Split the two tables into four, by the columns each query reads, and give the 65-byte pair
3M rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the comments of conditional over String to the invariants a reader needs: the 64-row grouping, why alternating groups branch, constant sources read row 0 of a padded column, the one-byte reserve and the 15-byte overwrite. Removed rationale: like the generic conditional, the result reserves the larger source and grows; every row copies at least one byte so empty and short strings take one path; long runs come from conditions like CASE WHEN c THEN s ELSE '' END, while alternating or random conditions give one- or two-row runs that are cheaper to copy row by row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The CASE line can run as multiIf when optimize_multiif_to_if is randomized off (05768_if_string_runs.sql) DISAGREE (nit) It reduces to if(c, s, ''), the path col_empty and values check on every run; each of 4 kernel mutations is caught by other lines. The CASE to if rewrite is not changed here.
2 💡 Growth past the reserve is tested only on the row-by-row path AGREE, not blocking The run copy reserves through the same helper.
3 💡 The changelog entry described the implementation AGREE, fixed Rewritten in user terms before publishing.
4 💡 Measured on x86 only AGREE, not blocking The description claims x86 only; the aarch64 performance comparison of this PR decides there.

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

Session id: cron:clickhouse-review-slot-8:20261114-222800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin, could you review this? It adds non-template GatherUtils::conditional overloads for String sources (at least one a column) that read the condition 64 rows at a time, copy a group with at most 16 runs of equal conditions one run per copy, and write other groups row by row into the reserved result, which makes if over String columns faster.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Performance change: a pre-registered x86 benchmark (release builds of master and three kernel variants, 6 rotating rounds, 80 expressions, clickhouse benchmark -c1 -i15, server-side time from system.query_log) shows master's cost in every round.
b Root cause explained? GatherUtils::conditional works one row per step: it resizes the sink, branches on the condition (mispredicted for random conditions) and copies the row with a variable-length 16-byte loop.
c Fix matches root cause? Rows are written straight into the reserved result (no per-row resize), without a branch unless the condition alternates, and a 64-row group with at most 16 runs is copied one run at a time.
d Test intent preserved / new tests added? New 05768_if_string_runs (an arrayElement oracle; an uncommitted path probe showed every path is reached; 4 mutations of the kernel each change its output) and new perf test if_string_runs.xml (9 queries, each Memory table under 1 GB).
e Both directions demonstrated? Ratios to master with 95% CI over 6 rounds (none of 78 shapes significantly slower); sum(cityHash64(...)) identical for 80 expressions; .reference produced by the master binary; 50/50 randomized runs.
f Fix is general across code paths? Overloads for String/String, String/constant and constant/String into a StringSink; constant/constant, FixedString and every other conditional keep the generic template (checked with nm); if.cpp unchanged; libdbms.a defines all three overloads.
g Fix generalizes across inputs (params/datatypes/wrappers)? Strings of 0-96 bytes, empty and non-empty constants, condition values 0/1/2/255, Nullable condition and branch, CASE, blocks of 1/7/1000 rows, tail groups, empty input, a result longer than both branches.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change; results byte-identical.
i Invariants and contracts preserved? Every row is written once, in order; offsets are monotone; chars are reserved or grown before each write; the small copy's overread stays inside PaddedPODArray padding. No ASan/UBSan report on the new test and 258 related tests (offsets[-1] is read through a signed index).

Session id: cron:clickhouse-impl-slot-7:20261114-221800

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [485ba9b]

Summary: ✅


AI Review

Summary

PR #131699 specializes GatherUtils::conditional for String columns, copying consecutive rows from the same branch together and optimizing other condition patterns. No actionable findings after reviewing the current diff, callers, buffer bounds, allocation paths, tests, and prior discussion. The focused stateless test passes on the current head; the same C++ implementation passed 50 ASan/UBSan runs. Repeated x86 and ARM performance comparisons support the claimed improvements.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 14, 2026
groeneai and others added 3 commits November 15, 2026 00:53
In `Stateless tests (amd_asan_ubsan, flaky check)` the test ran 230-247 s
per run (cap 180 s), and 140-165 s in the amd_binary and amd_debug legs.
The job's query_log puts 150 s of each run in the `max_block_size = 1`
query and 83 s in the four `max_block_size = 7` queries: the cost is the
number of blocks, one pipeline handoff per 1 or 7 rows over 10000 rows.

The queries with blocks of 1 and 7 rows now read 50 of every 500 rows
(`n % 500 < 50`, 1000 rows). That keeps every region of the view: all
condition patterns and values 0/1/2/255, all 97 string lengths, empty and
non-empty strings. The filter is applied right above `ReadFromSystemNumbers`,
and `if` still sees blocks of 1 row and of 1..7 rows (`blockSize()`).
The queries with blocks of 1000 rows are unchanged.

Same oracle: the new reference is the output of a master build, and the
fix's output is identical to it, with every `countIf(r != ref)` = 0.
The four mutations of the kernel (column run offset, both row-path source
swaps, constant run copied once) redden exactly the same output lines as
before. ASan, 50 runs at 8 workers on 16 CPUs: p50 11.26 s -> 2.57 s,
max 12.67 s -> 3.27 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A group of 64 rows with more than 16 runs of equal conditions is copied
row by row without a branch. On Graviton 3 (Neoverse V1) that is slower
than master for long rows with short runs: measured by @ snelheidai in
ClickHouse#130929 (comment)
(`SELECT count() FROM t WHERE NOT ignore(<expr>) SETTINGS max_threads = 1`,
6 rounds, ratio to master): 64 B in runs of 2 rows 1.278, 128 B in runs
of 2 rows 1.755, 64 B in runs of 3 rows 1.262. On aarch64 a group whose
column sources average at least 64 bytes per row is now copied run by
run, which gives 0.684, 0.786 and 0.644 there; no measured shape is slower
than master (closest: random 128-byte rows, 0.890), random 65-byte rows
go from 0.781 to 0.871, and `if(c_nat, Referer, '')` from 0.680 to 0.440.

x86 does not use the rule: the release object of `conditional.cpp` has
an identical disassembly before and after this change (forcing the rule
on changes 5413 lines of it). There the rule cost random runs of 4 rows
of 65 bytes 1.188 [1.055, 1.338] against the kernel without it, as the
long-string rule of the ClickHouse#130929 kernel did before (1.110 against master).

Verified on x86 with the rule forced on (`#if 1`): `05768_if_string_runs`
output identical to the reference on debug and ASan+UBSan builds (no
sanitizer report), and a path probe shows the new run-by-run groups for
column/column, column/constant and constant/column (48/49/16 groups) while
row-by-row groups remain. For aarch64: `-fsyntax-only -Werror` with the
cross flags is clean (an `#error` in the aarch64 branch fires, so that
branch is the one compiled), and clang-tidy-22 reports nothing.

`if_string_runs.xml` gets 64-byte strings in runs of 2 rows (5M rows,
693 MiB), the shape the aarch64 performance comparison needs to see this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`if(c_rand, 'x', Referer)` takes the constant/column overload (the one `ifNull`
reaches through `if(isNull(x), y, assumeNotNull(x))`), which no query of the
performance test covered. x86: 0.864 [0.848, 0.880] of master (6 rounds,
10M rows); Graviton 3 (ClickHouse#130929): 0.778, 0.677 with the aarch64 rule.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 91fa9c6

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
Performance Comparison (arm_release, master_head, iceberg_local, 1/3, 2/3, 3/3) and (arm_release, master_head, iceberg_s3, 1/3, 2/3, 3/3) / Insert historical data, Check Results perf CI: this PR adds a performance test and changes no Iceberg code, so each Iceberg job runs only if_string_runs.xml; the report step then stops before writing all-query-metrics.tsv (FileNotFoundError, then Errors while building the report.), the case the fixing PR handles; the same six jobs failed this way on 13 other PRs that change tests/performance/ in the last 5 days #129874 (ours, open)
PR praktika rollup of the rows above #129874 (ours, open)

CIDB has no other FAIL or ERROR row on this head (the Config Workflow / Pre Hooks rows are the run before the can be tested label).

Session id: cron:our-pr-ci-monitor:20261115-053020

The Iceberg configuration of the performance comparison widens the
`UInt8` condition columns of the test's tables to `Int32`, and `if`
rejects an `Int32` condition (`Arguments of function if do not match its
signature ... value provided as 1st argument has type Int32 that is not
MaybeNullable(UInt8)`), so the six `Performance Comparison (arm_release,
master_head, iceberg_local|iceberg_s3, N/3)` jobs, which run only the
changed test, failed on every query. Even if it ran, the test would
measure the conversion of the condition rather than the `UInt8` path it
is about.

`<test iceberg="0">` drops the test from the configuration
(`test_runs_with_table_engine` in `ci/jobs/scripts/perf/test_discovery.py`),
so those jobs are not scheduled for this pull request. The skip list is
not used: `tests/performance/iceberg_skip_list.txt` is one of
`ICEBERG_PERFORMANCE_PATHS`, so changing it would run the whole Iceberg
suite.

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

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 485ba9b4a with master d011c6b84 (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.

Object file sizes

11 object files changed (+8.93 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/GatherUtils/conditional.cpp.o new 21.10 KiB +21.10 KiB

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

31 translation units recompiled, 182 s compile time in total, 30 of them have a recent master baseline.

Job report

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... pr-performance Pull request with some performance improvements

Projects

None yet

1 participant