Skip to content

Speed up min/max on 128-bit and 256-bit types - #111965

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
raimannma:minmax-wide-integers
Jul 31, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
raimannma:minmax-wide-integers

Conversation

@raimannma

Copy link
Copy Markdown
Contributor

min and max on Int128, UInt128, Int256, UInt256, Decimal128 and Decimal256 fell back to the generic per-row loop in SingleValueDataFixed, because has_find_extreme_implementation only covered types up to 64 bits. That loop keeps the accumulator in the aggregate state, so the column data pointer is reloaded on every row, and for Decimal128 / Decimal256 it also calls the out-of-line Decimal comparison operator once per row.

These types now go through findExtreme*. Decimals reuse the existing NativeType routing, so they compare as wide integers inline. The wide-integer kernel updates the accumulator behind a branch rather than a select, because a select would put the 128/256-bit accumulator on the loop-carried dependency chain. findExtreme*Index scans twice and only pays off when the first pass is vectorized, so argMin / argMax and ORDER BY ... LIMIT 1 keep their single-pass loop.

Measured on SingleValueDataFixed::setGreatest over a 65409-row block, across random / low-64-bit / ascending / descending inputs and the min, max, -If and not-null variants:

type speedup
Int128, UInt128 1.16x - 1.76x
Int256, UInt256 1.09x - 1.38x
Decimal128 1.74x - 3.45x
Decimal256 1.84x - 2.01x

Results are unchanged: 04650_min_max_wide_integers passes both before and after the change.

Changelog category (leave one):

  • Performance Improvement

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

Speed up min and max on 128-bit and 256-bit types (Int128, UInt128, Int256, UInt256, Decimal128, Decimal256). Up to 1.8x faster for wide integers and up to 3.4x faster for wide decimals.

raimannma and others added 2 commits July 26, 2026 18:42
`min` and `max` on `Int128`, `UInt128`, `Int256`, `UInt256`, `Decimal128` and
`Decimal256` fell back to the generic per-row loop in `SingleValueDataFixed`,
because `has_find_extreme_implementation` only covered types up to 64 bits.
That loop keeps the accumulator in the aggregate state, so the compiler has to
reload the column data pointer on every row, and for `Decimal128` / `Decimal256`
it also calls the out-of-line `Decimal` comparison operator once per row.

Route these types through `findExtreme*` instead. Decimals reuse the existing
`NativeType` routing, so they compare as wide integers inline. The wide-integer
kernel updates the accumulator behind a branch rather than a select, since a
select would put the 128/256-bit accumulator on the loop-carried dependency
chain.

`findExtreme*Index` scans twice and only pays off when the first pass is
vectorized, so `argMin` / `argMax` and `ORDER BY ... LIMIT 1` keep their
single-pass loop, gated by the new `has_find_extreme_index_implementation`.

Measured on `SingleValueDataFixed::setGreatest` over a 65409-row block
(rand-full / low-64 / ascending / descending inputs, min, max, `-If` and
not-null variants):

    Int128, UInt128      1.16x - 1.76x
    Int256, UInt256      1.09x - 1.38x
    Decimal128           1.74x - 3.45x
    Decimal256           1.84x - 2.01x

No result changes: `04650_min_max_wide_integers` passes both before and after.

Co-Authored-By: Claude Opus 5 <[email protected]>
…h it

`findExtremeWideImpl` took the comparator class only to re-derive a single
`is_min` flag from it; take the flag directly.

`executeMinOrMax` in `arrayAggregation.cpp` hand-lists the types it dispatches
to `executeMinOrMaxNumeric`, so widening `has_find_extreme_implementation` left
`arrayMin` / `arrayMax` on wide-integer arrays behind on the generic `compareAt`
loop while the concept claimed otherwise. Add the four wide integer types to
that list.

Also record why `has_find_extreme_index_implementation` goes through
`NativeType`: without it the concept would admit `Decimal128` / `Decimal256`,
for which the index functions are deliberately not instantiated.

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

@alexey-milovidov alexey-milovidov 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.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Jul 26, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

I would be interested in checking this with #111164

@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af34589]

Summary: ✅


AI Review

Summary

This PR routes min / max on Int128, UInt128, Int256, UInt256, Decimal128, and Decimal256 through the batch findExtreme* path, while deliberately keeping index-based consumers on the existing non-vectorized path for wide types. I reviewed the current code, the PR diff, the prior discussion, and the current CI state, and I did not find a correctness, compatibility, or performance-contract issue that warrants an inline review comment.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 37 queries analysed

This PR only extends the min/max find-extreme kernels and array aggregation to 128/256-bit (wide) integer and Decimal types; the native-width path that every ClickBench query actually uses is left byte-identical (native types still satisfy the new concept and take the same branch). None of the flagged ClickBench queries operate on wide-integer columns, so none can be plausibly affected. The high-confidence Q32 +16.3% regression is therefore downgraded as off-path run-to-run variance, and the envelope-suppressed rows (Q4/Q9/Q15/Q31/Q34) are consistent with that reading — their deltas fall inside master's current variance band. Verdicts are also built on only 6 source runs, which widens the noise floor further.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 9 not_sure 353 389 +10.2% <0.0001 +10.2% is within master's variance band, and Q9 exercises no wide-integer min/max, so this PR can't be the cause.
⚠️ 18 not_sure 1288 1429 +11.0% <0.0001 Baseline is unstable here, so the +11.0% is not trustworthy; Q18 also uses no wide-integer types this PR touches.
⚠️ 28 not_sure 1036 1114 +7.5% <0.0001 The two tests disagree on the +7.5%, and Q28 uses no 128/256-bit min/max, so this PR is not the cause.
⚠️ 31 not_sure 381 422 +10.9% <0.0001 +10.9% is within the variance band and Q31 exercises no wide-integer min/max touched by this PR.
⚠️ 32 not_sure 1334 1552 +16.3% <0.0001 aggregation: Q32 groups on 64-bit columns; this PR only adds 128/256-bit min/max and leaves the native code path byte-identical, so the +16.3% is run-to-run variance, not a PR effect.
⚠️ 34 not_sure 1243 1341 +7.9% <0.0001 +7.9% is within the variance band; Q34 uses no wide-integer min/max, so this PR cannot be responsible.

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: 6319d72c-a7de-45fa-8acd-37d76de164b3
  • MIRAI run: a37e4109-74b2-43b1-90fd-d98d1c1a85bb
  • PR check IDs:
    • clickbench_1003938_1785438159
    • clickbench_1003945_1785438160
    • clickbench_1003961_1785438158
    • tpch_adapted_1_official_1003970_1785438158
    • tpch_adapted_1_official_1003994_1785438159
    • tpch_adapted_1_official_1004008_1785438159

@alexey-milovidov

alexey-milovidov commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Merged master into the branch and re-verified locally: the affected targets build and 04650_min_max_wide_integers passes.

The only red, Stress test (amd_debug) → Logical error query, is the unrelated Inconsistent KeyCondition behavior logical error in MergeTreeDataSelectExecutor::markRangesFromPKRange — it has nothing to do with the findExtreme* value path touched here.

Tracked by #111421, with fixes already in flight: #109023 and #111964.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master into the branch again (it was 361 commits behind) to get a fresh CI run. The merge was clean, and the four translation units this PR touches (src/Common/findExtreme.cpp, src/Columns/ColumnVector.cpp, src/AggregateFunctions/SingleValueData.cpp, src/Functions/array/arrayAggregation.cpp) compile against the current master. No new users of has_find_extreme_implementation / has_find_extreme_index_implementation appeared on master in the meantime, so the concept split still covers every call site.

The previous run's only red was a timeout in 03008_deduplication_several_mv_into_one_table_replicated (Stateless tests (amd_tsan, sequential, 2/2)). The harness re-ran it with the same randomized settings and it passed, and system.checks shows only two such failures in the last 30 days (the other on an unrelated pull request), so it is an unrelated rare flake — this pull request does not touch deduplication or materialized views.

@groeneai, please take a look at that timeout flake: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111965&sha=0e60967f14fb72a0e679fe896b31e14bb59c98ea&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29 — if it is worth a fix, please do it in a separate pull request and link it here.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator

It is worth a fix, and it is not really a random flake: the whole 03008_deduplication_* family got about twice as slow on 2026-06-16, so this test now runs much closer to the 600s per-test budget than it used to.

#90094 added --debug-on-fail True to six of the 03008_deduplication_* drivers. The generated debug statements are guarded (WITH (SELECT count() FROM t) AS c SELECT ... WHERE c != expected), so they print nothing when the test passes, but they are still parsed, analyzed and executed on every case. That is 32 extra statements per case and 2048 per full 64-case run (statements per case go from 31 to 63).

The p50 of passing runs on Stateless tests (amd_tsan, sequential, 2/2) steps exactly at the merge:

test p50 before (06-10..16) p50 after (06-17..23) p50 now
several_mv_into_one_table_replicated 114.0s 161.1s 220.1s
mv_generates_several_blocks_replicated 123.8s 169.0s 212.6s
insert_several_blocks_replicated 111.8s 152.1s 192.1s
several_mv_into_one_table_nonreplicated 98.4s 143.2s 170.1s
mv_generates_several_blocks_nonreplicated 110.4s 157.4s 183.3s
insert_several_blocks_nonreplicated 97.2s 135.8s 156.5s

Two controls make the attribution tight. 03008_deduplication_random_settings comes from the same generator but does not pass the flag, and it is flat across the same boundary (11.9s to 11.8s); so are the other flag-less siblings (cases_from_docs 3.7 to 4.1, remote_insert_select 1.3 to 1.3, wrong_mv 0.6 to 0.6). And every other test on that same check is flat too: p50 3.16s to 3.15s over 623203 runs. The step also shows up on amd_debug (24.1s to 30.5s) and arm_binary (24.0s to 30.4s), so it is test-level rather than something specific to TSan.

One correction to the obvious reading: the guarded probe does not scan the table. On a real server its query_log row is read_rows = 1, result_rows = 0, because count() is answered from part metadata. The cost is per-statement overhead, measured at 2.9 to 4.5 ms per probe on a warm server, so roughly 6 to 9s unloaded for 2048 probes; TSan instrumentation plus sequential contention is what turns that into the ~100s seen in CI. A local A/B on a debug build (3 reps, 8 cases, arms alternated, fresh database per case) gives 0.923s with the flag against 0.819s without.

Current headroom on that check over 14 days: p50 216.8s, p99 297s, max 415.4s against the 600s budget. So a run needs roughly a 2x host slowdown to time out, which is why there are only two such failures in 45 days rather than a steady stream. Both sat exactly at 600070ms, and the other one (on #107030, 2026-07-01) reproduced under the same randomized settings and passed without randomization, which fits "no headroom left" rather than a specific bad setting.

I will send a separate pull request that makes the diagnostics genuinely opt-in so the probes are not executed on the success path, and keep them available when a case actually fails. I will link it here. I am not proposing to raise the timeout.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into ClickHouse:master with commit edf8dde Jul 31, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

As promised above: #112913

It makes the 03008_deduplication_* debug-on-fail diagnostics genuinely opt-in. The probes are
guarded by WHERE c_dst != <expected>, which suppresses their output but not their execution, so
on master they are parsed, analyzed and executed on the success path too: 28 to 32 extra
statements per case, 1792 to 2048 per 64-case run, across six long tests. They now run only
after a case has actually failed, replayed for the phase that failed against the state the
failing run left behind, so the diagnostics themselves are unchanged when a case does fail.

Measured on insert_several_blocks_nonreplicated, system.query_log QueryStart rows drop from
3905 to 2113; across four drivers 446.1s to 336.8s.

No timeout raised.

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 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