Skip to content

Speed up mortonEncode by resolving argument types and mask ratios once per block - #123354

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai-morton-encode-resolve-arguments-once
Oct 2, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai-morton-encode-resolve-arguments-once

Conversation

@groeneai

@groeneai groeneai commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122482

Changelog category (leave one):

  • Performance Improvement

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

Function mortonEncode now resolves the type of each argument and the ratios of a constant range mask once per block instead of once per row, which makes it up to 2x faster.

Description

Requested in #122482 (comment): space_filling_curve #1 (mortonEncode((1, 2), number, number * 2), max_threads = 1) was +15.8% in Performance Comparison (arm_release, master_head, 4/6). On arm, #1 moved by more than 8% in 2984 of 7548 runs in 30 days and #4 (UInt32 arguments) in 917 of 7571, while #2 (two UInt64 columns, no mask) moved in 3: their speed depends on the binary.

All three run the same row loop. Per row and argument it tested the mask, switched on the column width and, with a mask, tested is_const, reloaded the ratio and called the out-of-line expand. Now each argument is resolved once per call into a contiguous UInt64 array with the range expansion applied (a UInt64 column without expansion is used in place), and a constant ratio is applied in one loop per ratio value. The encode loops only encode: in the arm codegen the nd == 2 loop is 31 instructions per row with one branch and no call. A per-row mask keeps the per-row path. Results are unchanged. The cost is a temporary UInt64 buffer of the block's size for each argument that needs widening or expansion.

space_filling_curve.xml on x86, one pinned core, median fix/base ratio of 5 interleaved rounds:

query BMI2 (x86 build) lookup-table path (what arm runs, built with -mno-bmi2)
#1 0.57 0.55
#2, #3, #6 0.45-0.50 0.55-0.64
#4 0.86 0.88
mortonDecode, hilbertEncode (untouched) 1.00-1.03 0.99-1.01

I measured on x86 only; the arm effect can only be checked in this PR's Performance Comparison. The new test pins each row's result for every argument width, mask kind and ratio on both code paths; speed is covered by space_filling_curve.xml.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 1, 2026 21:04
…nce per block

`mortonEncode` with two arguments ran one row loop for every argument type
and mask: per row and argument it tested the mask and `is_const`, reloaded
the ratio, switched on the column width and, with a mask, called the
out-of-line `expand` (36 call sites in the arm `executeImpl`). On arm the
speed of the branch-dense paths depends on the binary's layout, so
`space_filling_curve` ClickHouse#1 (constant mask) and ClickHouse#4 (`UInt32` arguments) have
per-build speed modes and flag unrelated PRs in Performance Comparison
(ClickHouse#122482), while ClickHouse#2 (two `UInt64` columns) is stable.

Now each argument is resolved once per call into a contiguous `UInt64` array
with the range expansion applied: a `UInt64` column that needs no expansion
is read in place, other widths are widened with one type dispatch, and a
constant ratio is applied in one loop per ratio value (`expand` is
`ALWAYS_INLINE` and called with a template-constant ratio, so its switch
folds). A per-row mask keeps the per-row `expand`. `nd == 1` writes the
result column directly. The encode loops only encode.

x86, one core, median fix/base of 5 interleaved rounds over the queries of
`space_filling_curve.xml`: ClickHouse#1 0.57 (BMI2) / 0.55 (lookup-table path, built
with `-mno-bmi2`), ClickHouse#2/ClickHouse#3/ClickHouse#6 0.45-0.64, ClickHouse#4 0.86-0.88, untouched functions
0.99-1.03. Results are unchanged: 545 checksums over every width, mask and
ratio are byte-identical before and after on both code paths, and the new
test fails on both paths under two mutations of the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every checksum in the test was `sum(cityHash64(mortonEncode(...)))`, which
does not change when results move between rows, so a defect that writes the
encoded values to the wrong rows of a block would pass. Hash `number`
together with each result instead. The reference is regenerated with the
unchanged base binary and is byte-identical on the patched one, on both the
BMI2 and the lookup-table code paths.

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 1, 2026
@groeneai

groeneai commented Oct 1, 2026

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

Pre-publication review by an independent model (engine: codex; 4 findings over 3 runs, the last run clean).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test only sums result hashes, so it cannot see a row permutation, nor a reversion of the optimization AGREE (rows), fixed @ 042f365 Each checksum now hashes number with the result; a row-reversal mutation fails it on both code paths. Speed is covered by space_filling_curve.xml (#1 to #4 and #6 run the changed loops)
2 ⚠️ Speedup for UInt8/UInt16 arguments is claimed but not measured AGREE, fixed in the PR text Claim removed from the changelog entry; only the measured queries are cited, and arm is stated as unmeasured
3 ⚠️ Per-argument UInt64 scratch buffers may raise peak memory DISAGREE At most nd * rows * 8 bytes per call, freed at return and tracked by the memory tracker, none for a UInt64 argument without expansion; the cost is stated in the description
4 💡 The BMI2 expand switch has no default, unlike its lookup-table twin noted Unchanged master code; no CI tidy job compiles that arm

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

Session id: cron:clickhouse-review-slot-8:20261001-222600

@groeneai
groeneai requested a review from Algunenano October 1, 2026 22:51
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [042f365]

Summary: ✅


AI Review

Summary

This PR refactors mortonEncode to resolve argument widths and constant range-mask ratios once per block, materializing widened and pre-expanded UInt64 inputs where needed so the inner encode loops operate on plain values. I do not see a correctness, safety, or compatibility regression in the current diff, and the added stateless coverage exercises the changed width, mask, constant, Nullable, and LowCardinality paths well enough for approval.

Missing context / blind spots
  • ⚠️ The current Praktika run was still pending while I reviewed, so I could not independently confirm the fresh cross-architecture Performance Comparison results for PR #123354. This gap closes once the linked PR report finishes.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 042f365.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 61/63 (96.83%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 042f36587 with master 38fd308a8 (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

4 object files changed (-25.30 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/mortonEncode.cpp.o 299.52 KiB 274.24 KiB -25.29 KiB (-8.44%)

719 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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 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: 4efb5ed7-465b-4e60-8d3b-36b711f3b290
  • MIRAI run: d372baec-2e4e-4475-8dca-75cc128f45bb
  • PR check IDs:
    • clickbench_2821011_1790901560
    • clickbench_2821278_1790901709
    • clickbench_2821380_1790901720
    • tpch_adapted_1_official_2821482_1790901737
    • tpch_adapted_1_official_2821595_1790901769
    • tpch_adapted_1_official_2821726_1790901844

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit 26b9e75 Oct 2, 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 Oct 2, 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-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