Skip to content

Change default x86 build target from x86-64-v2 (SSE4.2) to x86-64-v3 (AVX2) - #105019

Merged
Algunenano merged 19 commits into
masterfrom
revert-104971-revert-90043-x86v3
Jun 1, 2026
Merged

Algunenano merged 19 commits into
masterfrom
revert-104971-revert-90043-x86v3

Conversation

@Algunenano

@Algunenano Algunenano commented May 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Backward Incompatible Change

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

The default x86 build now targets x86-64-v3 (AVX2) instead of x86-64-v2 (SSE4.2). This requires a CPU with AVX2 support (Intel Haswell or later, AMD Excavator or later). If your CPU does not support AVX2, use the amd64compat build which targets plain x86-64.

The default ClickHouse binary for x86 Linux now requires AVX2 (x86-64-v3). CPUs without AVX2 support will fail with an "Illegal instruction" error. For systems without AVX2, use the compatibility build (amd64compat) available at https://builds.clickhouse.com/master/amd64compat/clickhouse. The install script (curl https://clickhouse.com/ | sh) automatically detects CPU capabilities and downloads the appropriate build.

Closes #105758

@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fb8bdb3]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
Server died FAIL cidb IGNORED

AI Review

Summary

This PR changes the default x86 Linux build target from x86-64-v2 to x86-64-v3, adjusts runtime dispatch/build flags and packaging guidance, and adds several performance/CI follow-ups. I found two correctness/deployment issues that should be addressed before merge.

Findings

⚠️ Majors

  • [docs/_includes/install/universal.sh:15] The installer and CMake host check use avx2 as a proxy for x86-64-v3, but the new amd64 binary may use other v3 instructions. A feature-masked host can get the wrong binary or pass configure before build tools hit SIGILL.
    Suggested fix: check the full v3 feature set via CPUID/XGETBV, or otherwise require every v3 bit before selecting amd64 / accepting X86_ARCH_LEVEL=3.

  • [src/Common/Base58.cpp:240] The fixed-size Base58 decoders allow idx == 74, then read base58_inverse[74] one past the table for input like '{'.
    Suggested fix: reject idx >= std::size(base58_inverse) or adjust the sentinel, and add invalid-character coverage for the first character after 'z'.

Tests

⚠️ Add focused coverage for the Base58 boundary character after 'z' in both 32-byte and 64-byte decode paths.
⚠️ Add coverage or a helper test for CPU selection that proves amd64compat is selected unless all x86-64-v3 requirements are present.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the full x86-64-v3 capability detection and close the fixed-size Base58 decoder bounds hole.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog submodule changed At least one submodule changed in this PR. labels May 15, 2026
Algunenano and others added 4 commits May 15, 2026 13:54
After x86-64-v3 became the default, the MSan WasmEdge stateless-test
check started timing out on ~5% of runs. With AVX2 codegen LLVM keeps
YMM live across hot loops, which forces the X86VZeroUpperInserter to
emit a vzeroupper before every external call from those blocks.
-fsanitize-memory-track-origins=2 inserts a __msan_chain_origin call at
every uninit-value propagation step, so each one now pays a vzeroupper.
The cumulative cost is a 30-60% slowdown on every test on the check.

Drop to track-origins=1 when ARCH_AMD64 && X86_ARCH_LEVEL >= 3.
Level 1 still records the originating allocation of an uninit value
(the punchline of most MSan reports); the chain through intermediate
copies is what is lost. Hot __msan_chain_origin guards drop from
565,983 to 1,932 (-99.7%) in the rebuilt binary.

Also keep -march= / -mcpu= / -mtune= / -mpclmul / -maltivec when
stripping inherited flags in contrib/compiler-rt-cmake so the RTL is
built for the same target microarchitecture as the main binary. This
does not eliminate the caller-side vzeroupper insertion on its own
(LLVM's pass is purely caller-side), but stops the RTL from being
silently downgraded to the toolchain default.

We keep MSan on v3 rather than downgrading the build to v2 so MSan
keeps exercising the same instructions our production binaries do; if
LLVM grows a way to annotate the RTL calls as YMM-preserving (or LTO
becomes feasible on the MSan build), we can revisit and raise this
back to =2.
Even at track-origins=1, the per-call origin maintenance dominates two
hot helpers used by every QueryLog flush:
  - ProfileEvents::dumpToMapColumn (Interpreters/ProfileEventsExt.cpp)
  - SettingsImpl::dumpToMapColumn  (Core/Settings.cpp, already covered)

Each walks hundreds of keys and does tight LowCardinality::insertData
calls in a loop, so the per-call __msan_set_alloca_origin overhead
adds up to seconds per `SYSTEM FLUSH LOGS query_log` and the failing
tests on the MSan WasmEdge 2/2 shard hit the 180 s flush-wait
timeout. The CI logs show Block phase up to 14.7 s for a 5759-entry
batch, dominated by these two functions.

Extend the existing per-file override added in #92716 to also cover
ProfileEventsExt.cpp and SystemLog.cpp. These files are leaf helpers
where MSan checks don't carry uninit values into user code, so
turning origin tracking off here is safe; the rest of the build keeps
origin tracking.
The recent refactor of executeConstBuckets switched from reading the
constant via an intermediate Field to IColumn::getUInt / getInt. Those
narrow any value wider than 64 bits, so e.g.
toUInt128('18446744073709551621') (= 2^64 + 5) was silently truncated
to 5 and the function returned a hash for 5 buckets instead of
rejecting the out-of-range input.

Reject the wide types up-front in getReturnTypeImpl by checking
isNativeInteger instead of isInteger. ILLEGAL_TYPE_OF_ARGUMENT now
fires for UInt128/Int128/UInt256/Int256 (matches what users get when
passing a non-integer). Native integer types are unaffected.

Bot review: #105019 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The earlier override on Settings.cpp / ProfileEventsExt.cpp /
SystemLog.cpp removed __msan_chain_origin / __msan_set_alloca_origin
from the helpers (dumpToMapColumn, flushImpl). But the per-row
LogElement::appendToBlock functions, which are called once per row
inside flushImpl and dominate the Block phase, were still being
compiled with origin tracking at level 1. With ~5000 rows per
query_log flush, the per-call origin-tracking overhead in those
functions added seconds to every SYSTEM FLUSH LOGS query_log.

Cover QueryLog.cpp, QueryThreadLog.cpp, MetricLog.cpp,
QueryMetricLog.cpp. Result on the rebuilt MSan binary:
  QueryLogElement::appendToBlock     57 KB -> 39 KB (-32%), 0 origin calls
  QueryThreadLogElement              9.5 KB -> 6 KB (-37%), 0 origin calls
  MetricLogElement / QueryMetricLog        also 0 origin calls
Compare with PartLogElement::appendToBlock (still origin-tracked):
55 __msan_set_alloca_origin calls in 22 KB.

Also drop the `-fomit-frame-pointer -momit-leaf-frame-pointer` flags
from the override: they were an artifact of exploratory commits in
PR #92716 that didn't move the needle (azat/Algunenano review thread
on Core/Settings.cpp). The single-line override on Common/ThreadFuzzer.cpp
keeps them with a comment pointing at commit d5825ec, where they
were measured to almost double ThreadFuzzer test throughput.
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

Comment thread src/Common/EnvironmentChecks.cpp Resolved
Under -march=x86-64-v3+ with MSan, the AVX2 codegen keeps YMM live in
hot vectorized blocks, and LLVM's X86VZeroUpperInserter emits a
`vzeroupper` before every external call from such a block (operator
new, free, `__msan_set_alloca_origin*`, `__msan_memcpy`, etc.). In
the current MSan binary that's ~1.78M `vzeroupper` instructions in
the .text section — almost all on hot paths, since the MSan RTL is
called per-allocation and per-poison-event.

vzeroupper exists to avoid the AVX-to-SSE transition penalty on
Sandy/Ivy Bridge era cores. On Zen3+ and Ice Lake (the current AMD
CI runners), that penalty is essentially zero, so the inserted
instructions execute for nothing. Disable the inserter under
MSan + v3+ via `-mno-vzeroupper`.

Only kicks in when SANITIZE=memory AND X86_ARCH_LEVEL >= 3, so
non-sanitizer release builds and MSan v2 builds are untouched.
…rt-90043-x86v3

# Conflicts:
#	.github/workflows/pull_request.yml
Comment thread src/Functions/array/range.cpp Resolved
Algunenano and others added 3 commits May 20, 2026 16:07
`executeConstStartStep` did an unconditional `value += step` after writing
each element. For valid runs at the high or low end of the type's range
the trailing increment after the last element overflows (signed UB),
e.g. `range(toInt64(9223372036854775806), toInt64(9223372036854775807), toInt64(2))`
emits a one-element array and then overflows Int64 on the post-write
update.

Peel the last iteration. Inner loop stays branchless so the compiler
can keep vectorising it; the boundary `if (n > 0)` lives outside.
Same observable output, no UB.

Bot review: #105019 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

It looks good with the changes, eliminating vzeroupper with MSAN does produce faster runs, and with the reduction of track-origins=1, and the per-file -fno-sanitize-memory-track-origins on the QueryLog flush path it appears faster than current v2 msan. Running it again to have more data

We added ARM MSan WasmEdge stateless tests in 015485b to compare
runtimes against AMD MSan while diagnosing the x86-64-v3 vzeroupper
slowdown. Now that the fix is in (vzeroupper-inserter disabled under
MSan + v3, per-file -fno-sanitize-memory-track-origins on the QueryLog
flush hot path) and timings match master, the comparison jobs are no
longer load-bearing. Drop them to free CI capacity.

Removes the ParamSets from ci/defs/job_configs.py and regenerates the
two workflow YAMLs via `python3 -m praktika yaml`.
Comment thread src/Functions/array/CMakeLists.txt Resolved
Algunenano and others added 2 commits June 1, 2026 09:35
set_source_files_properties has no APPEND form, so the
PROPERTIES APPEND PROPERTY COMPILE_FLAGS "-ffp-contract=fast" call
overwrote the COMPILE_FLAGS for arrayDistance.cpp, dropping the
conditional -march=x86-64-v2 pin and leaving it compiled at the global
x86-64-v3 target, which is the regression that block avoids.

Set -ffp-contract=fast for arrayDotProduct.cpp directly and use
set_property ... APPEND_STRING for arrayDistance.cpp so both
-march=x86-64-v2 and -ffp-contract=fast survive.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rt-90043-x86v3

# Conflicts:
#	src/Common/Base58fd.h
#	src/Common/EnvironmentChecks.cpp
#	src/Storages/MergeTree/MergeTreeRangeReader.cpp
Comment thread src/Common/Base58.cpp
for (size_t i = 0; i < src_length; i++)
{
size_t idx = static_cast<size_t>(static_cast<uint8_t>(src[i])) - static_cast<size_t>(BASE58_INVERSE_TABLE_OFFSET);
if (idx > BASE58_INVERSE_TABLE_SENTINEL)

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.

This bound lets one byte past the inverse table through. base58_inverse covers characters '1'..'z', so valid indices are 0..73, but BASE58_INVERSE_TABLE_SENTINEL is 74. An input like '{' gives idx == 74, skips this check, and then base58_inverse[idx] reads past the array (same pattern in decodeBase58_64_fd). Please make the check use the actual table size, e.g. idx >= std::size(base58_inverse), or change the sentinel so idx == 74 is rejected.

Comment thread docs/_includes/install/universal.sh Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 92.40% +1.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 740/776 (95.36%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 15 line(s) · Uncovered code

Full report · Diff report

@Algunenano

Copy link
Copy Markdown
Member Author
Latest PR run vs master baseline (last 14 days, master only, picking one duration per commit):

┌─────────────────────────┬─────────────┬────────────┬────────────┬────────────┐
│           Job           │ PR #105019  │ Master avg │ Master min │ Master max │
├─────────────────────────┼─────────────┼────────────┼────────────┼────────────┤
│ WasmEdge parallel 1/2   │ 3727s (62m) │ 4466s      │ 3831s      │ 6562s      │
├─────────────────────────┼─────────────┼────────────┼────────────┼────────────┤
│ WasmEdge parallel 2/2   │ 3851s (64m) │ 4608s      │ 3962s      │ 6241s      │
├─────────────────────────┼─────────────┼────────────┼────────────┼────────────┤
│ WasmEdge sequential 1/2 │ 3899s (65m) │ 4329s      │ 3631s      │ 5217s      │
├─────────────────────────┼─────────────┼────────────┼────────────┼────────────┤
│ WasmEdge sequential 2/2 │ 4858s (81m) │ 5301s      │ 4619s      │ 6379s      │
└─────────────────────────┴─────────────┴────────────┴────────────┴────────────┘

All four MSan WasmEdge stateless jobs pass and finish below the 14-day master average; three of them sit at or under the master minimum. No timeouts. The single failure on the PR is an unrelated Server died event in Stateless tests (arm_asan_ubsan, targeted).

So with x86-64-v3 turned back on plus the MSan-specific mitigations (track-origins downgrade, per-file -fno-sanitize-memory-track-origins on the QueryLog flush hot path, and -mno-vzeroupper), MSan WasmEdge timings are back in line with the pre-AVX2 baseline.

@Algunenano
Algunenano enabled auto-merge June 1, 2026 14:05
@Algunenano
Algunenano added this pull request to the merge queue Jun 1, 2026
Merged via the queue into master with commit d7dce35 Jun 1, 2026
164 of 166 checks passed
@Algunenano
Algunenano deleted the revert-104971-revert-90043-x86v3 branch June 1, 2026 14:36
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants