Skip to content

Use a counter-mode generator for random bytes on AArch64 and x86-64 - #116133

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:aarch64-random-counter-mode
Aug 25, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:aarch64-random-counter-mode

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

Speed up random data generation. rand, rand64, randConstant, randomString, randomFixedString, generateUUIDv4, generateUUIDv7 and dateTimeToUUIDv7 now generate bytes with ARS (reduced-round AES in counter mode) wherever the CPU has AES instructions: on AArch64 chosen at build time, on x86-64 chosen at run time when VAES is present. Targets and CPUs without those instructions keep the previous generator unchanged.

Description

Closes: #116077

FunctionsRandom.cpp had one dispatch test, #if !defined(__AVX2__), so all of AArch64 took the
scalar four-chain LCG at 16 bytes per iteration while x86-64 took the AVX2 arm at 128. Since
#90043 made x86-64-v3 the default x86 target, that is what every default build gets.
randomFixedString(10) over 100M rows is 1.5359x slower on ARM than AMD as a result.

It was never simply vectorised because AArch64 NEON has no 64-bit-lane integer multiply. I
confirmed that with clang-22: uint64x2 * uint64x2 becomes extract-to-GPR, scalar multiply,
reinsert, and every LCG-preserving vector design I measured lands at 0.46x-0.93x of the scalar
arm. Widening the scalar chain count is not portable either: x86-64-v2 goes to 0.76x.

So this adds an #elif defined(__aarch64__) && defined(__ARM_FEATURE_AES) arm using ARS (Salmon
et al., "Parallel Random Numbers: As Easy as 1, 2, 3", SC'11), which issues on the cryptographic
pipe instead of the integer multiply unit. AES is unconditional in the AArch64 server profile
(cpu_features.cmake:53 passes +crypto) and clang defines __ARM_FEATURE_AES there but not
under compat, so no runtime dispatch is needed and the compat build keeps the scalar arm.

The design and the ARM measurements are @ egor-click's, from #116077: two interleaved 21-run
Neoverse-V2 sessions, 29.86% and 30.12% wall-clock reduction across the four affected
performance-CI queries, and rand() 1.1004x, rand64() 1.1561x, generateUUIDv4() 1.1241x. He
also discloses 3.98% slower small buffers (max_block_size=64, where the round keys are not
amortised) and adds no size threshold. I have no ARM host, so the authoritative number here is
this PR's own Performance Comparison (aarch64) job.

Also corrects two documentation gaps: three sites called the generator a "linear congruential
generator", already imprecise since the arms differ. The FunctionsRandom.h overwrite contract is
restored to PADDING_FOR_SIMD - 1 after being reverted per review - "15 bytes" was only ever
accurate for the scalar arm, the AVX2 arm has required 63 since it was written, and both new x86
arms measure exactly 63.

x86-64

The same conclusion holds on x86-64 for a different reason. There the LCG arm is already vectorised, so the AArch64 rationale does not apply - but AES still generates bytes faster, because VAESENC retires several AES blocks per instruction on the cryptographic pipe while the generator competes for the multiply ports.

VAES belongs to no x86-64 microarchitecture level - Zen 3 has it with no AVX-512 at all, Intel only from Ice Lake - so the build flags cannot imply it and it needs runtime dispatch. TargetArch gains an x86_64_vaes bit, and RandImpl::execute becomes: VAES and x86-64-v4 -> ARS over 512-bit VAESENC; VAES only -> ARS over 256-bit VAESENC (Zen 3); no VAES -> the existing AVX2 LCG arm, untouched. The two conditions together also keep AES off Skylake-SP and Cascade Lake, which are x86-64-v4 but have no VAES, and which are the parts where 512-bit code costs the most in clock frequency.

Generator throughput against the LCG arm, single thread, one default block of randomFixedString(10):

ARS 256-bit ARS 512-bit
Zen 4 (Ryzen 9 7950X3D) 1.91x 2.34x
Granite Rapids (Xeon 6975P-C) 2.07x 2.98x
Sapphire Rapids (Xeon 8488C) 2.08x 2.94x
Ice Lake (Xeon 8375C) 1.94x 2.75x
Zen 3 (EPYC 7R13) 1.47x no AVX-512

End to end on Zen 4, best of 7 against a binary built from the same tree with only this arm reverted: randomFixedString(10) over 400M rows 1.38x, generateUUIDv4 1.40x, rand64 1.35x. The 512-bit tier adds a further ~6% on top of that - well under its generator ratio, because generation is no longer the dominant cost once it is already twice as fast.

One caveat, recorded in the code: on Intel a call of a few MB or more makes the 512-bit arm slower than the 256-bit one, 0.79x at 8 MB on Ice Lake and 0.80x on Sapphire Rapids, while AMD shows no crossover. It is not the memory system running out of bandwidth - that would make the two converge, not invert - and a frequency effect fits better. One default block is 640 KiB, so no size threshold was added.

x86-64 validation

Both arms verified against an independent scalar ARS-5 reference, block by block, over 609 sizes (1..600 plus block boundaries to 640 KiB): output matches the reference, the 256-bit and 512-bit arms produce byte-identical streams for the same key and counter, and neither writes more than PADDING_FOR_SIMD - 1 bytes past size - both peak at exactly 63.

Codegen checked per section: the dispatcher contains no VAES and no AVX-512, so it stays legal without either; executeArs contains no zmm or mask registers, so it stays legal on Zen 3; executeArs512 has the expected vaesenc/vaesenclast counts. 69 stateless tests covering the eight affected functions pass, with two pre-existing ZooKeeper/replication failures that reproduce against an unmodified binary.

Not covered locally: the 256-bit arm needs a CPU with VAES but no AVX-512, so every local run took the 512-bit path. No sanitizer run either - the 512-bit tail store lands exactly on the padding boundary, so the ASan job is the meaningful check.

Validation (AArch64)

clang-22 (the CI pin), project flags from this tree. RandImpl::execute codegen:

target pre-fix post-fix
x86-64-v3 (AVX2 arm) md5 37bb61e6, 30 vpmuludq identical
x86-64-v2 (scalar arm) md5 175224d4 identical
ppc64le (scalar arm) md5 adfa0eed identical
aarch64 compat armv8+crc md5 9b7a9430, 0 aese identical
aarch64 armv8.2-a+crypto md5 9b7a9430, 0 aese 45 aese, 36 aesmc

45 aese = 5 rounds x 8 blocks + 5 tail. Whole-TU assembly on the unchanged targets differs only
in debug line tables. __ARM_FEATURE_AES measured defined under the server profile, undefined
under compat, and defined for aarch64-apple-darwin with no -march at all, so that build takes
the new arm too. The arm compiles clean under -Weverything -Werror.

ARM binary under qemu-aarch64-static, running the exact loop from the patch, each assertion
paired with a liveness control: overwrite worst case exactly 63 bytes past size and never more,
size == 0 writes nothing, two complementary pre-fills agree on every byte in [0, size) for
sizes 1..600, and the 4-byte randConstant call gives 64 distinct values. Distribution over
64 MiB:

arm byte chi2 (dof 255) worst-bit dev 16-bit chi2 (dof 65535)
scalar (today) 280.8 0.000237 65655.6
ARS (this PR) 200.2 0.000324 65647.9
negative control 67109126.6 0.500000 100728677.7

The control is ARS output with the top bit of each byte cleared; all three reject it. UBSAN with
-fno-sanitize-recover=all is clean.

x86-64 is no longer unchanged; see the x86-64 section above. 27 of the 31 stateless tests touching the eight affected functions pass; the 4 failures need
ZooKeeper or a cluster, and reproduce against the unmodified binary.


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

Version info

  • Merged into: 26.9.1.123 (included in 26.9 and later)

src/Functions/FunctionsRandom.cpp had exactly one dispatch test,
"#if !defined(__AVX2__)", with no #elif and no __aarch64__ anywhere in the
file. Every non-AVX2 target therefore took the scalar arm: four
LinearCongruentialGenerator chains at 16 bytes per iteration. x86 takes the
AVX2 arm (16 chains as four UInt64x4, 128 bytes per iteration) by default,
since ClickHouse#90043 made x86-64-v3 the default x86 target. randomFixedString(10)
over 100M rows is 1.5359x slower on ARM than on AMD as a result, recomputed
from performance-CI history.

RandImpl::execute is the single random-byte source for rand, rand64,
randConstant, randomString, randomFixedString, generateUUIDv4,
generateUUIDv7 and dateTimeToUUIDv7, so one arm reaches all of them.

The reason this was never simply vectorised on ARM is architectural:
AArch64 NEON has no 64-bit-lane integer multiply, so the LCG recurrence
cannot be vectorised there. Confirmed at instruction level with clang-22
under the project's ARM flags: uint64x2 * uint64x2 becomes extract both
lanes to GPRs, scalar multiply, reinsert, while uint32x4 * uint32x4 is a
single mul v0.4s. x86 has the same architectural hole but LLVM auto-emits
the three-partial-product decomposition, which is why the AVX2 arm can
write a portable "gens * a + c". Measuring loop-body instructions per
generated byte, every LCG-preserving vector design for ARM is slower than
today's scalar arm: 0.46x for the portable 64x64 decomposition at both two
and four 64-bit lanes (16 GPR/vector transfers per iteration), 0.93x for a
split-state (lo32, hi32) form. Widening the scalar chain count is not the
portable answer either, since it regresses a shipped configuration:
x86-64-v2 goes from 13.85 to 10.56 GB/s at eight chains, 0.76x.

So the generator has to change on ARM and it has to use a different
execution unit. This adds an additive
"#elif defined(__aarch64__) && defined(__ARM_FEATURE_AES)" arm holding ARS,
reduced-round AES in counter mode, from Salmon et al., "Parallel Random
Numbers: As Easy as 1, 2, 3", SC'11: five AES rounds per 16-byte block,
eight counter blocks in flight to cover AES latency, and round keys drawn
from a Weyl sequence so there is no key schedule inside the loop.
AESE/AESMC issue on the cryptographic pipe rather than competing for the
integer multiply unit.

The gating needs no runtime dispatch. cmake/cpu_features.cmake:53 passes
-march=armv8.2-a+simd+crypto+dotprod+ssbs+rcpc+bf16 for the AArch64 server
profile and clang defines __ARM_FEATURE_AES under those flags; under the
compat profile (NO_ARMV81_OR_HIGHER, -march=armv8+crc at :20) it does not,
so that build keeps the scalar arm. Both measured.

x86 is unaffected by construction: the new arm is inserted before the
existing two, so their bodies are untouched and each x86 build still selects
the arm it selects today. Verified rather than asserted. RandImpl::execute
assembly is byte-identical pre-fix and post-fix at -march=x86-64-v3 (the
AVX2 arm, 30 vpmuludq), at -march=x86-64-v2 (the scalar arm), on ppc64le,
and on the AArch64 compat profile; only the AArch64 server profile changes,
from 16 mul and 4 madd with zero cryptographic instructions to 45 aese and
36 aesmc, which is five rounds times eight blocks plus five for the tail.
Whole-translation-unit assembly on the four unchanged targets differs only
in debug line tables and is identical once those are stripped.

The generated stream changes on AArch64. That is not a new property: the
scalar and AVX2 arms already produce different sequences from each other,
using a different chain count, a different subset of the seed array and a
different bit selection. rand declares isDeterministic() == false and is
reseeded from randomSeed() on every call, so no caller may depend on the
exact sequence.

Correctness of the new arm was checked on an ARM binary under
qemu-aarch64-static, running the same eight-block interleaved loop, with a
liveness control beside each assertion: the overwrite past size peaks at
exactly PADDING_FOR_SIMD - 1 = 63 bytes and never exceeds it, size == 0
writes nothing, two complementary pre-fills agree on every byte in
[0, size) for sizes 1 to 600, and the four-byte randConstant call yields 64
distinct values across 64 seeds. Distribution over 64 MiB against the
scalar arm: byte-histogram chi-square 200.2 against 280.8 for 255 degrees of
freedom, worst per-bit deviation 0.000324 against 0.000237, 16-bit-word
chi-square 65647.9 against 65655.6 for 65535 degrees of freedom. A negative
control of the same output with the top bit of each byte cleared is rejected
by all three statistics, so the screen discriminates. UBSAN with
-fno-sanitize-recover=all is clean. Throughput was never read from qemu,
which interprets each SIMD operation.

Two documentation defects are corrected alongside. rand.cpp, rand64.cpp and
FunctionsRandom.h described the generator as a linear congruential
generator, which is already imprecise given that the two existing arms
differ, and is untrue on the AArch64 server profile after this change; the
descriptions now name the property, that the generator is non-cryptographic
and predictable from its initial state, rather than the algorithm.
FunctionsRandom.h also documented the overwrite contract as 15 bytes, while
the AVX2 arm has required PADDING_FOR_SIMD - 1 = 63 since it was written.
Every call site is backed by a PaddedPODArray, whose pad_right is exactly
PADDING_FOR_SIMD - 1, so nothing was unsafe; the comment was wrong.

The design and the AArch64 A/B measurements in the linked issue are
egor-click's work. On a 32-core Neoverse-V2 he measured two independent
interleaved sessions of 21 runs per side: 29.86% and 30.12% wall-clock
reductions across the four affected performance-CI queries, plus rand()
1.1004x, rand64() 1.1561x and generateUUIDv4() 1.1241x out of sample. He
also discloses a 3.98% regression on small buffers, at max_block_size=64
where the six round keys and three seed derivations are not amortised, and
deliberately declines a size threshold for it on the grounds that a
size-conditional branch shaped around the benchmark that exposed the cost is
the wrong shape for this file.

Closes: ClickHouse#116077
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, adjudicated)

Independent cold review of this diff plus a second-model pass, adjudicated against the
implementation evidence. No blockers or majors. The one substantive item was in this PR's
description, not in the code, and is already corrected above.

# Finding Verdict
💡 The validation matrix listed x86-64-v3, x86-64-v2, ppc64le and the AArch64 compat profile, but omitted that the aarch64-apple-darwin build also selects the new arm ⚠️ Agreed - text gap. cmake/darwin/toolchain-aarch64.cmake sets CMAKE_SYSTEM_PROCESSOR=aarch64, so cmake/arch.cmake sets ARCH_AARCH64 and the cpu_features.cmake ARM branch applies; clang defines __ARM_FEATURE_AES for that triple with no -march at all. Correct behaviour (AES is mandatory on Apple silicon), but the omission understated the change set. Description updated.
💡 Wrap identifiers such as LinearCongruentialGenerator and PaddedPODArray in the new comments in inline code, per repository convention ❌ Disagreed - the premise does not hold. Across all 954 .cpp files in src/Functions and src/Common, CamelCase symbol mentions inside comments are 255 backticked against 5389 bare. FunctionsRandom.cpp:177 and randCanonical.cpp:27, the two pre-existing lines the new comment is modelled on, both write PaddedPODArray bare; backticking only the new lines would make the file internally inconsistent.

Also checked and found clean, recorded because each was a plausible blocker for this class of change:

  • No new runtime CPU requirement. cmake/cpu_features.cmake:53 passes +crypto
    unconditionally for the AArch64 server profile, and absl/hash/internal/hash.cc:44 already
    compiles vaeseq_u8/vaesmcq_u8 into absl::hash, which is built and linked. AES instructions
    are already in today's ARM binary. The compat profile defines neither __ARM_FEATURE_AES nor
    __ARM_FEATURE_CRYPTO, so arm_v80compat keeps the scalar arm.
  • The 63-byte overwrite bound is tight, not slack. Brute-forcing sizes 1..4999 plus the
    boundary cases, the worst case past size is exactly PADDING_FOR_SIMD - 1 = 63, hit at
    size == 65. Every call site is a PaddedPODArray whose pad_right is at least that. The
    header's previous "15 bytes" was already wrong for the AVX2 arm, which writes 128 bytes per
    iteration behind the same test.
  • Existing ARM tests do reach both new loops, traced rather than assumed: randConstant's
    4-byte call is 0 main + 1 tail iteration; 02310_generate_multi_columns_with_uuid at 48 bytes is
    0 main + 3 tail; the second block of 01277_random_fixed_string is 27024 main + 2 tail. Those
    tests assert a byte-histogram floor and independence, which a stuck, zeroed or short-writing
    generator fails.
  • The two remaining "linear congruential" strings in
    docs/reference/functions/regular-functions/random-functions.mdx were deliberately left alone:
    they sit inside the AUTOGENERATED region that check_autogenerated_regions.py protects, and
    the nightly generator rebuilds them from the FunctionDocumentation strings this PR edits.
  • One note for a reader who finds the header comment long: two of its sentences describe
    measurements rather than a local invariant and are the first candidates to cut. The rest states
    why AES is used instead of a vectorised LCG, why five rounds, and why the byte stream may differ
    per target, which is the kind of "why" a comment should carry.

randCanonical and randomPrintableASCII use their own pcg64_fast and are untouched.

Session id: cron:clickhouse-review-slot-11:20260824-140300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. This is a performance defect, so the on-demand check is codegen identity, not a red test: with clang-22 and this tree's own project flags, RandImpl::execute on aarch64 is byte-identical to the aarch64 compat profile (md5 9b7a9430, 16 mul, 0 aese), proving ARM took the scalar arm. The user-visible symptom, randomFixedString(10) over 100M rows at 1.5359x AMD, was recomputed from performance-CI history.
b Root cause explained? Yes. One dispatch test, #if !defined(__AVX2__), with no #elif and no __aarch64__ in the file, so every non-AVX2 target took the scalar 4-chain LCG at 16 bytes per iteration while x86 took the AVX2 arm at 128 (the default since #90043). It was never vectorised on ARM because NEON has no 64-bit-lane integer multiply: uint64x2 * uint64x2 compiles to extract-to-GPR, scalar multiply, reinsert.
c Fix matches root cause? Yes. Adds the missing dispatch arm with a generator that uses a different execution unit (AESE/AESMC on the cryptographic pipe) instead of the multiply unit that limits the scalar arm. Every LCG-preserving vector design measured 0.46x-0.93x of the scalar arm, and widening the scalar chain count takes x86-64-v2 to 0.76x, so neither alternative is the fix. No widened bound, no tag, no masked upstream bug.
d Test intent preserved / new tests added? Preserved; no new test, by design. Nothing behavioural is fixed, the contract is unchanged, seeded output cannot be pinned (isDeterministic() == false, reseeded from randomSeed() per call), and a timing test would be noise. The four affected queries already exist in rand.xml, random_string.xml and random_fixed_string.xml. 27 of the 31 stateless tests touching the eight affected functions pass; the 4 failures need ZooKeeper or a cluster on port 9000, reference no random function, and reproduce identically against the unmodified binary.
e Both directions demonstrated? Yes. Without the fix: aarch64 has 0 aese, md5 9b7a9430. With it: 45 aese + 36 aesmc (5 rounds x 8 blocks + 5 tail), md5 f5d64682, while the aarch64 compat profile stays at 9b7a9430. Correctness of the new arm verified on an ARM binary under qemu-aarch64-static; throughput never read from qemu.
f Fix is general across code paths? Yes. Fixed at the single source, RandImpl::execute, so all six call sites and eight functions benefit rather than any one caller being patched. Sibling generators randCanonical and randomPrintableASCII draw from pcg64_fast directly and are correctly out of scope. All other targets verified byte-identical: x86-64-v2, x86-64-v3, ppc64le, aarch64 compat.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The ARM harness sweeps size from 0 to 600, covering the empty case, every 16-byte tail remainder and the 128-byte main-loop boundary, plus the 4-byte minimum caller shape from randConstant.cpp explicitly. Distribution screened over 64 MiB against the current scalar arm with a negative control that all three statistics reject.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization format, so no SettingsChangesHistory.cpp entry applies. The byte sequence changes on aarch64, which is not a compatibility surface: the function is non-deterministic by declaration, is reseeded on every call, and the existing scalar and AVX2 arms already produce different sequences from each other. The compat ARM profile is unchanged.
i Invariants and contracts preserved? Yes. The contract is: fill [output, output+size) with well-distributed pseudo-random bytes, overwriting at most PADDING_FOR_SIMD - 1 bytes past size. Measured worst case is exactly 63 bytes at size=65 and never more, with a liveness control confirming the probe can see an overwrite; size == 0 returns before any store; two complementary pre-fills agree on every byte in [0, size). Every call site is backed by a PaddedPODArray with pad_right = 63. The header comment now states that real bound instead of the stale 15 bytes.

Session id: cron:clickhouse-impl-slot-40:20260824-131300

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3fdcc79]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, distributed plan, 4/4) FAIL
test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR replaces the old random-byte generator with ARS on AArch64 and adds VAES-based x86 paths selected at runtime. The AArch64 part looks coherent, but the new x86 dispatch still has two material gaps: the optimization disappears entirely from x86-64-v2 multitarget builds, and the unconditional v4 choice knowingly regresses wide-string workloads on Intel once a single column buffer crosses the measured executeArs512 crossover.

Findings

⚠️ Majors

  • [src/Functions/FunctionsRandom.cpp:54] The x86 implementation is gated on __AVX2__, so a supported -DX86_ARCH_LEVEL=2 build never emits executeArs / executeArs512 at all. In that build profile the binary can still run on VAES-capable CPUs, but RandImpl::execute stays on the old fallback instead of doing the runtime dispatch the PR promises. Suggested fix: keep the x86 code available for defined(__x86_64__) && USE_MULTITARGET_CODE, use a true baseline implementation for the fallback, and move the v3 / vaes / v4+vaes code into function-specific target attributes.

  • [src/Functions/FunctionsRandom.cpp:508] The dispatcher always selects executeArs512 on x86_64_v4, even though the code comment documents that this path is slower than the 256-bit arm on Intel once the buffer reaches a few MiB. That crossover is not exotic: randomFixedString.cpp:77 passes the whole column buffer to RandImpl::execute, so at the default ~65k-row block size randomFixedString(128) is already ~8 MiB. Suggested fix: add a size-based or Intel-specific fallback to executeArs past the measured crossover.

Final Verdict

Changes needed before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 72/124 (58.06%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @Algunenano, could you review this? RandImpl::execute had one dispatch test, #if !defined(__AVX2__), so every AArch64 build took the scalar 4-chain LCG while x86 took the AVX2 arm, and the LCG cannot be vectorised on NEON at all because there is no 64-bit-lane integer multiply, so this adds a third arm using reduced-round AES in counter mode gated on __ARM_FEATURE_AES. x86, ppc64le and the ARM compat profile are byte-identical pre-fix and post-fix.

@groeneai

groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4d88123

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
Build (arm_tidy) / Build ClickHouse PR-caused: modernize-loop-convert errors at src/Functions/FunctionsRandom.cpp:129 and :131, both inside the new AArch64 arm PR-caused → fixed in this PR
request-reviews-fork superseded run cancelled by a newer push of the same workflow; 3 later runs of the same job on this head are skipped not a test failure; no owner needed

Finish Workflow succeeded and no other check failed on this head. The two clang-tidy errors are
in the loops this PR adds, so I am fixing them here rather than tracking them elsewhere.

Session id: cron:our-pr-ci-monitor:20260824-160000

@Algunenano Algunenano self-assigned this Aug 24, 2026
Build (arm_tidy) failed on this branch with two clang-tidy errors
(-warnings-as-errors) at the two loops in RandImpl::execute that iterate the
whole `state` array using the index only:

  FunctionsRandom.cpp:129:13: error: use range-based for loop instead
  FunctionsRandom.cpp:131:9:  error: use range-based for loop instead

Both are full traversals of `state` where the index is used exclusively to
subscript that one array, so a range-based for expresses them directly. The two
neighbouring loops keep their index because they use `i` arithmetically (as the
per-block counter offset and as the store displacement), which is also why
clang-tidy did not flag them.

Verified by cross-running clang-tidy-22 on the single translation unit at the
arm_tidy target and flags (aarch64-linux-gnu,
-march=armv8.2-a+simd+crypto+dotprod+ssbs+rcpc+bf16, Debug): 2 diagnostics
before, 0 after, with the full .clang-tidy configuration and no other
diagnostic in the file. arm_darwin behaves the same (2 before, 0 after);
arm_v80compat and x86-64 are unaffected because they select a different arm.

The change is codegen-neutral where it matters: at -O3, the shipped AArch64
profile, the disassembly of RandImpl::execute is byte-identical before and
after (45 aese / 36 aesmc / 29 eor either way). A control that changes `blocks`
from 8 to 4 moves that comparison (25 aese / 20 aesmc), so the identity is a
measurement rather than a blind compare. The correctness and distribution
harness, built in both loop shapes and run under qemu-aarch64, produces
byte-identical output and passes all 7 checks with its biased control still
failing as designed.
01276_random_string and 01277_random_fixed_string were the coverage this
branch's new AArch64 arm relies on, but their oracle could not fail the way it
was read as failing. `GROUP BY byte` only creates a row for a byte value that
actually occurs, so `SELECT DISTINCT c > 30000` says "every byte value that
appeared, appeared often" and says nothing about how many appeared. A generator
emitting one constant byte produces a single group of 10000000 and returns `1`,
exactly like a healthy one.

Measured against the shipped binary, substituting a constant-byte generator of
the same width into each test: the old oracle passes the mutant in both files,
the new `count() = 256 AND min(c) > 30000` form fails it in both. A partial
mutant restricted to 128 distinct values also passes the old form and fails the
new one, so the added term discriminates diversity and not merely the
one-value extreme. The healthy generator returns 256 groups, so the references
are unchanged and both tests still print `1`.

`ORDER BY byte` is dropped because the aggregate no longer depends on row
order. The memory pins stay: these queries exist to hold `randomString` and
`randomFixedString` under 600Mi, and the strengthened form was re-measured
inside that cap over five runs.

@Algunenano Algunenano 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.

Some things to consider for follow-ups:

  • For AVX2 we can also derive one seed and fan it out with a Weyl sequence the way the PR already does for round keys. This would reduce setup cost noticeably.
  • We should consider adding VAES as a x86 target (via dynamic dispatch)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Build (arm_tidy) fix, and a correction to my own earlier claim on this PR

e9a215c (2 commits, one push).

The build failure. arm_tidy failed on 4d88123 with two modernize-loop-convert errors
under -warnings-as-errors, at the two loops in RandImpl::execute that walk the whole state
array using the index only. Both are now range-based. The two neighbouring loops keep their index
because they use i arithmetically (counter offset, store displacement), which is also why
clang-tidy did not flag those.

Verified by cross-running clang-tidy-22 on the single translation unit at the arm_tidy target
and flags (aarch64-linux-gnu, -march=armv8.2-a+simd+crypto+dotprod+ssbs+rcpc+bf16, Debug):
2 diagnostics before, 0 after, full .clang-tidy config, no other diagnostic in the file.
arm_darwin behaves identically (2 before, 0 after). arm_v80compat and x86-64 are unaffected
because they select a different arm; I confirmed that is structural and not a vacuous zero by
re-running each against the pre-fix file.

Codegen-neutral where it matters: at -O3, the shipped AArch64 profile, the disassembly of
RandImpl::execute is byte-identical before and after (45 aese / 36 aesmc / 29 eor either
way). A control changing blocks from 8 to 4 moves that comparison to 25/20, so the identity is
a measurement rather than a blind compare. The correctness and distribution harness, built in
both loop shapes and run under qemu-aarch64, gives byte-identical output and passes all 7
checks with its biased control still failing as designed.

The correction. Reviewing this, I found that a coverage claim I posted earlier on this PR was
wrong. I said 01276_random_string / 01277_random_fixed_string assert that all 256 byte values
appear. They do not. GROUP BY byte only creates a row for a value that actually occurs, so
SELECT DISTINCT c > 30000 says "every value that appeared, appeared often" and says nothing
about how many appeared. Measured against the shipped binary: substituting a constant-byte
generator of the same width, the old oracle returns 1 and the test passes; a mutant restricted
to 128 distinct values also passes.

Since those tests are the coverage this arm relies on, they are now
count() = 256 AND min(c) > 30000. Both mutants fail the new form and the healthy generator
returns 256 groups, so the references are unchanged and both tests still print 1. The memory
pins stay, and the strengthened form was re-measured inside the 600Mi cap over five runs. That
weakness is pre-existing on master and not introduced here; I am fixing it in this PR because
this PR is what leans on it.

Session id: cron:clickhouse-maint-slot-13:20260824-161900

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3fdcc79b4 with master 34a01adf1 (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
Binary Master PR Δ
programs/clickhouse-stripped 710.08 MiB 707.04 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR only rewrites the rand()/rand64() number generator (switching to AES-based ARS on capable CPUs) plus a CPU-feature-detection enum; it does not touch the query-execution path that ClickBench exercises, and none of the ClickBench queries call random functions. The six flagged queries all moved +9.5% to +17.3% in the same direction with CPU time rising in step, a uniform pattern that indicates run-to-run environment variance rather than a real regression. The two provisional regressions (Q16, Q17) are downgraded to not_sure on that basis, and the remaining four were already correctly held within master's variance band. No plausible PR-attributable regression was found.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 596 699 +17.3% <0.0001 cpu: This PR only rewrites the rand()/rand64() generator; ClickBench Q16 runs no random functions, so the +17.3% is off-path and consistent with node-level variance.
⚠️ 17 not_sure 242 269 +11.2% <0.0001 cpu: Q17 executes no random functions, and this PR touches only the rand generator. The +11.2% is off-path and reads as run-to-run variance.
⚠️ 18 not_sure 1034 1176 +13.7% <0.0001 cpu: Deterministically kept within master's current variance band, and off-path for a rand-generator-only change. The +13.7% is variance.
⚠️ 32 not_sure 1299 1422 +9.5% 0.0122 cpu: Mixed signals from the two tests and off-path for this PR; the +9.5% is best read as variance.
⚠️ 33 not_sure 1192 1320 +10.7% <0.0001 cpu: Within master's variance band and off-path; Q33 runs no random functions, so the +10.7% is variance.
⚠️ 34 not_sure 1187 1320 +11.2% <0.0001 cpu: Within master's variance band and off-path; the +11.2% is consistent with environment variance, not this PR.

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: 709de44a-04fb-4163-a28c-826b5d1512a1
  • MIRAI run: 328a5b02-ea8c-4be3-b969-816b8d7d71e5
  • PR check IDs:
    • clickbench_362772_1787687626
    • clickbench_362784_1787687627
    • clickbench_362790_1787687628
    • tpch_adapted_1_official_362797_1787687627
    • tpch_adapted_1_official_362829_1787687627
    • tpch_adapted_1_official_362843_1787687629

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e9a215c

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
Stress test (arm_debug) / Hung check failed, possible deadlock found uninterruptible h3 polygon size estimation in contrib/h3, trunk a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Not caused by this PR. I read hung_check.log rather than the CIDB context, which keeps only the
last 32 KiB and discards the processlist. There is exactly one hung query and it is a Select:
elapsed: 3080.85, is_cancelled: 1, read_rows: 200, thread_ids: [13430, 10015]. The stack for
thread 13430, which the processlist row names, ends in maxPolygonToCellsSizeExperimental
(contrib/h3/src/h3lib/lib/polyfill.c:775) via iterStepPolygonCompact and cellToBBox, reached
from h3PolygonToCellsWithContainment under ExpressionActions::executeOnColumns. That h3 walk has
no callback and no budget, so the per-row cancellation check in the ClickHouse function, one frame
above it, cannot fire while it runs.

This PR changes only the AArch64 random-bytes generator: four files under src/Functions
(FunctionsRandom.cpp, FunctionsRandom.h, rand.cpp, rand64.cpp) plus two stateless tests.
Counted over the artifact's bytes, it contains RandImpl 0, randomFixedString 0,
FunctionsRandom 0, generateRandom 0, rand64 0 and TargetSpecific 0, against positive controls
Select 196 and thread_ids 1 in the same bytes. A codegen change to the random functions cannot
park a server thread inside the h3 library.

h3PolygonToCellsWithContainment.cpp is byte-identical at this head and on master, so no merged fix
is missing here. Breadth over 14 days: the hung-check family is 661 rows across 314 distinct pull
requests with 72 rows on master, and the narrower h3 polygon sub-signature is 25 rows across 14
distinct pull requests by several authors.

Session id: cron:our-pr-ci-monitor:20260824-220000

@Algunenano

Copy link
Copy Markdown
Member

Performance improvements look good:

image

-- that memory again. Do not drop `max_block_size`: both peaks scale with it, so without the pin
-- a cap loose enough for a high draw stops catching a revert on a low one.
SELECT DISTINCT c > 30000 FROM (SELECT arrayJoin(reinterpret(randomString(100), 'Array(UInt8)')) AS byte, count() AS c FROM numbers(100000) GROUP BY byte ORDER BY byte) SETTINGS max_memory_usage = '600Mi', max_block_size = 65409;
-- `count() = 256` is load-bearing: `GROUP BY byte` only creates a row for a byte value that occurs,

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.

@groeneai Undo the changes in this test and in 01277_random_fixed_string.sql‎.

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.

Reverted in a55fc14; both files are byte-identical to master again.

One note in case you want it kept elsewhere: the restored oracle is SELECT DISTINCT c > 30000 over GROUP BY byte, and GROUP BY only creates a group for a byte value that occurs, so it also returns 1 for a generator emitting one byte 10,000,000 times (checked with a constant-byte mutant). That weakness is pre-existing on master, not introduced here.

Comment thread src/Functions/FunctionsRandom.h Outdated
* rand - values from the range 0 .. 2^32 - 1.
* rand64 - values from the range 0 .. 2^64 - 1.
*
* Which generator produces those bytes is selected per target at compile time, so the

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.

@groeneai Remove the comment on l. 31-32.

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.

Removed in a55fc14.

Comment thread src/Functions/FunctionsRandom.h Resolved
Comment thread src/Functions/FunctionsRandom.cpp Outdated
}

#if !defined(__AVX2__)
#if defined(__aarch64__) && defined(__ARM_FEATURE_AES)

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.

@groeneai Replace the AES-based implementation by a vectorized linear congruential generator, even if it's slightly slower.

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.

First, a correction to my own comment in this file. It says synthesising a 64x64 product from vmull_u32 "costs more instructions per generated byte than the scalar MADD it would replace, and measures slower". That is not supported for the shape you are asking for.

Measured, clang-22, -O3 -DNDEBUG, --target=aarch64-linux-gnu -march=armv8.2-a+simd+crypto+crc, inner-loop instructions per output byte:

variant insns/byte
today's scalar arm, 4 chains 0.8125
all-NEON split-state exact LCG, 16 chains 0.7656
ARS as in this PR, main loop 0.8750

A vectorized LCG keeping the exact current = current * a + c is viable: hold the 64-bit state as (lo, hi) in uint32x4_t, partial products via vmlaq_u32, carry from vmull_u32/vmull_high_u32 + vuzp2q_u32, emit bits 16..47 as today. It needs no __ARM_FEATURE_AES gate, so unlike ARS it would also speed up arm_v80compat. My earlier numbers used a portable operator* decomposition, which lowers to extract-to-GPR/multiply/reinsert (16 transfers per iteration); that is not this shape.

Two caveats:

  1. Instruction counts cannot rank these two: AESE/AESMC issue on the crypto pipe, MUL/MLA on the integer-vector pipes. I have no ARM host, so only this PR's Performance Comparison (aarch64) job can settle it.
  2. Avoid the 32-bit-lane form (one mla v.4s, 0.3750 insns/byte). With a 32-bit state the output is the state, so the >> 16 that drops the weak low bits is unavailable and bit k has period 2^(k+1). Measured: bit 0 0101..., bit 1 period 4, bit 2 period 8, so rand() % 2 would strictly alternate.

Shall I push the 16-chain split-state arm so the ARM perf job compares it against ARS directly? If you want the LCG regardless of that result, I will do that instead.

@rschu1ze

Copy link
Copy Markdown
Member

@Algunenano Sorry, I didn't see that you assigned already.

The current ARM-NEON implementation uses AES instructions. To keep the complexity low, I guess it makes sense to use (vectorized) linear congruential generation on ARM as well?

@Algunenano

Copy link
Copy Markdown
Member

Stress test failure related to missing cancellation: Fixed here

Three review asks from @rschu1ze on ClickHouse#116133:

  - Undo the changes in 01276_random_string.sql and 01277_random_fixed_string.sql.
    Both files are now byte-identical to master again.
  - Remove the added note in FunctionsRandom.h about the generator being selected
    per target.
  - Retain the original "must be 15-bytes padded" comment on RandImpl::execute.

The overwrite bound the reverted comment described is unchanged by this revert: the
AVX2 arm has required PADDING_FOR_SIMD - 1 = 63 bytes of padding since it was
written, and every caller's PaddedPODArray supplies at least that. The comment
understating it as 15 predates this PR and is left as it was.

The generator question raised in the fourth review comment is answered in the thread
and is not addressed by this commit.
@Algunenano

Copy link
Copy Markdown
Member

The current ARM-NEON implementation uses AES instructions. To keep the complexity low, I guess it makes sense to use (vectorized) linear congruential generation on ARM as well?

I trusted @groeneai 's assumptions, but it seems that it comes from @egor-click 's initial issue as it's not measuring runtime, just instructions. I don't think @groeneai has an ARM machine, so probably giving it these kind of issues does not make any sense. It can't iterate

@Algunenano

Copy link
Copy Markdown
Member

I've been having a look and testing a VAES implementation and it seems we get a 2x in some cases so it's worth the extra complexity:

Ratios vs today's AVX2 v3 arm at 655360 bytes. — means the CPU lacks the instruction set and the arm is skipped.

┌──────────────────────┬───────┬───────┬──────────┬───────┐
│         arm          │ Zen 4 │  SPR  │ Ice Lake │ Zen 3 │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ single thread        │       │       │          │       │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ LCG VPMULLQ ymm      │ 2.42x │ 1.34x │    1.33x │     — │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ LCG VPMULLQ zmm      │ 2.42x │ 1.40x │    1.42x │     — │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ ARS-5 AES-NI         │ 1.19x │ 1.48x │    1.48x │ 1.18x │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ ARS-5 VAES 256       │ 1.94x │ 2.07x │    1.94x │ 1.47x │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ all cores, aggregate │       │       │          │       │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ LCG VPMULLQ zmm      │ 2.23x │ 1.64x │    1.57x │     — │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ ARS-5 AES-NI         │ 1.32x │ 1.27x │    1.33x │ 1.09x │
├──────────────────────┼───────┼───────┼──────────┼───────┤
│ ARS-5 VAES 256       │ 2.00x │ 1.84x │    1.73x │ 1.37x │
└──────────────────────┴───────┴───────┴──────────┴───────┘

So I think it's ok to use it for for x86 (when supported) and for NEON (always since we always have AES). I'll add it here

@egor-click

Copy link
Copy Markdown
Contributor

The current ARM-NEON implementation uses AES instructions. To keep the complexity low, I guess it makes sense to use (vectorized) linear congruential generation on ARM as well?

I trusted @groeneai 's assumptions, but it seems that it comes from @egor-click 's initial issue as it's not measuring runtime, just instructions. I don't think @groeneai has an ARM machine, so probably giving it these kind of issues does not make any sense. It can't iterate

yeah, my bot had arm machine to test this, performance comparison also looks good for ARM as far as i can see

https://performance.ci.clickhouse.com/runs/pr-116133-e9a215c284fb7445939babacac5b3783e3501669

The x86-64 arm of `RandImpl::execute` is already vectorised, unlike the
AArch64 one, but AES still generates bytes faster than the linear
congruential generator does: `VAESENC` retires two AES blocks per
instruction on the cryptographic pipe, while the generator competes for
the vector multiply ports.

So add ARS on VAES as a second x86-64 arm, selected at runtime. VAES is
not part of any microarchitecture level - Zen 3 has it with no AVX-512
at all, and Intel only from Ice Lake onwards - so neither `x86_64_v4`
nor `x86_64_icelake` describes the CPUs that have it, and `TargetArch`
gets a feature bit of its own.

The constants and the seeding are shared with the AArch64 arm through
`ArsParams`. Only the round itself differs, because the two instruction
sets order the key addition differently.

Generator throughput against the arm it falls back to, at one default
block of `randomFixedString(10)`, single thread and then saturating
every core:

  Zen 4 (Ryzen 9 7950X3D)        1.94x / 2.00x
  Sapphire Rapids (Xeon 8488C)   2.07x / 1.84x
  Ice Lake (Xeon 8375C)          1.94x / 1.73x
  Zen 3 (EPYC 7R13)              1.47x / 1.37x

End to end on Zen 4, best of 7: `randomFixedString(10)` over 400M rows
1.384x, `generateUUIDv4` 1.397x, `rand64` 1.345x.
@Algunenano Algunenano changed the title Use a counter-mode generator for random bytes on AArch64 Use a counter-mode generator for random bytes on AArch64 and x86-64 Aug 25, 2026
@Algunenano

Copy link
Copy Markdown
Member

I've updated the PR to implement ARS with VAES for x86, both for x86v4 and v3, via dynamic dispatching. Linear congruential generator is kept for systems without AES.

@groeneai Could you review the changes please?

Comment thread src/Functions/FunctionsRandom.cpp Resolved
Comment thread src/Functions/FunctionsRandom.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reviewed 3fdcc79b4695. It looks correct to me, and I have one finding that is about the tests rather than your code.

I have no ARM host, but I do have VAES here, on a Xeon 6975P-C, which is the Granite Rapids row of your table, so I checked the parts that are measurable rather than only reading them.

Dispatch. Verified live rather than by inspection: with breakpoints on all three arms, a randomFixedString query enters executeArs512 on this CPU, and enters executeArs when I gate the x86_64_v4 sub-check off, so both branches are reachable and pick the arm you intend. The new x86_64_vaes bit follows the existing cumulative pattern in getSupportedArchs, and toString covers it. objdump on the in-tree object shows vaesenc/vaesenclast in both arms and no zmm operand anywhere in executeArs, so the missing no-prefer-256-bit on the v3 attribute does not let AVX-512 into the arm meant for Zen 3.

Bounds. Both arms write at most 63 bytes past size, executeArs worst at size 65 and executeArs512 worst at size 1, and a guard page placed at exactly size + 63 is never touched. Your executeArs512 tail comment is accurate that this leaves no margin.

Output. Over 64 MiB per arm, byte chi2 is 236.2 against 255 dof, no bitwise period up to 32 in any bit position, and all 40960 blocks inside one 640 KiB call are distinct. Sizes 1..300 fully overwrite [0, size). The two arms are byte-identical for the same seed and address across the 16 sizes I tried, which is a useful property because it makes them differentially testable.

Throughput, best of 9, pinned, against the LCG arm they fall back to: at 640 KiB 2.32x for the 256-bit arm and 2.99x for the 512-bit one; at 8 MiB 1.80x and 1.72x, so 512-vs-256 is 0.96x. Your table says 2.07x and 2.98x for Granite Rapids and your caveat says 0.96x at 8 MB there, so both reproduce, including the Intel crossover.

The finding. The suite cannot detect a broken ARS arm. If I replace the five AES rounds in executeArs512 with block = round_keys[0], leaving every store and size intact, then uniqExact(randomFixedString(16)) over 1000 rows is 1 and uniqExact(rand64()) over 100000 rows is 4, and 01276_random_string, 01277_random_fixed_string, 01015_random_constant, 00396_uuid and 00396_uuid_v7 all still pass. The restored SELECT DISTINCT c > 30000 oracle bins bytes and asserts each bin exceeds 30000; under that mutant only 29 distinct byte values occur, each with count 216193, so the predicate stays uniformly true and the result collapses to a single 1. It constrains the counts, never the number of bins. Of the 403 stateless tests that reach RandImpl::execute, the only one I found that catches it is 01533_distinct_nullable_uuid, via COUNT(DISTINCT generateUUIDv4()) = 10000. Three other tests failed on the mutant but fail on a clean build here too, so they are artifacts of my sandbox and not detections.

That gap is not introduced by your commit, but it becomes more relevant with it, because which arm runs is now a runtime property, and executeArs only runs where there is VAES without AVX-512, which in practice means Zen 3 and so probably nothing in CI. I force-ran that arm here and it passes all of the above. The count() = 256 AND min(c) > 30000 form that does catch the mutant is what I reverted in a55fc14 at @ rschu1ze's request, so I have not reinstated it unilaterally. Happy to put it back, in 01277 alone if you prefer, if you both think it is worth it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Two automated findings landed on FunctionsRandom.cpp after I started reviewing. I checked both, and I think both are right, so adding them to the review above rather than leaving them to be judged on their own.

The __AVX2__ gate at line 54 is stricter than the compiler needs. It is not only a selection gate: at -DX86_ARCH_LEVEL=2 it stops executeArs and executeArs512 from being compiled at all, so a binary that ends up on Zen 3 or Ice Lake silently runs the LCG arm with no dispatch. That is avoidable, because both bodies already carry __attribute__((target(...))). Compiling your two bodies unchanged in a -march=x86-64-v2 TU with clang-22 succeeds and still emits vaesenc in both, while __AVX2__ is undefined at that level, so it is only the #if that excludes them. Keying on defined(__x86_64__) && USE_MULTITARGET_CODE would keep v2 builds dispatching.

The x86_64_v4 choice at line 508 does reach your documented Intel regression. randomFixedString.cpp:77 passes the whole column buffer, so at the default block size of 65409 rows randomFixedString(128) is 7.98 MiB in one call, which is the size range your own comment records as 0.79x on Ice Lake and 0.80x on Sapphire Rapids.

I measured the crossover here, on Granite Rapids, arms interleaved within each rep so drift hits both equally, median of 15 per-rep ratios (512 over 256):

  0.62 MiB  1.285      4.00 MiB  0.973
  2.00 MiB  1.284      8.00 MiB  0.948
  3.00 MiB  1.015     16.00 MiB  0.946
  3.50 MiB  1.002     32.00 MiB  0.943

So it reproduces, but it starts around 4 MiB rather than at the 8 MB your comment cites, and it then stays flat out to 32 MiB. Worth noting the earlier onset makes the affected width range wider than the comment suggests: randomFixedString(64) is already 3.99 MiB per block. It is also not a capacity effect, since L2 here is 2 MiB per core and the ratio is still 1.015 at 3 MiB, which is consistent with the frequency explanation you gave. My separately-taken best-of-9 numbers had this at 0.96x at 8 MiB, matching your figure; the interleaved median is the more reliable of the two, and I would not read the third digit of either.

Whether that deserves a size threshold in the dispatcher is your call, and my earlier point stands that I cannot rank these two arms on Ice Lake or Sapphire Rapids myself.

@Algunenano

Copy link
Copy Markdown
Member
image

@Algunenano
Algunenano added this pull request to the merge queue Aug 25, 2026
@egor-click

Copy link
Copy Markdown
Contributor

thanks @Algunenano !

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3fdcc79

Every failure below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, distributed plan, 4/4) / test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write pre-existing flaky NATS JetStream reconnect test; trunk-wide at 158 hits across 118 distinct PRs and 7 master rows in 30 days (first seen 2026-07-30) #115343 (ours, open)

Not reachable from this diff, which touches only FunctionsRandom / TargetSpecific / rand /
rand64. #115343 names this exact test as the failure its fix addresses: an asynchronous JetStream
pull subscription re-sends SUB on reconnect but not the pull request the broker was holding, so a
consumer still behind when the broker stops never fetches the undelivered messages.

Session id: cron:our-pr-ci-monitor:20260825-223000

Merged via the queue into ClickHouse:master with commit bf256b0 Aug 25, 2026
176 of 178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Aug 31, 2026
A stress test hung on a fuzzed `h3PolygonToCellsWithContainment` query whose
polygon had a vertex at latitude -1.7976931348623157e308. It spent about 45
minutes inside one H3 call, observing neither `max_execution_time` nor
`KILL QUERY`.

Two causes. H3 picks the coarse resolution for its size estimate by dividing
the polygon's bounding box area by the average cell area, and a vertex off the
sphere makes that area negative, so the reduction never triggers and the
estimate counts every cell of a polygon covering much of the globe: 2.6e8 cells
at resolution 9. And the cells of one polygon were filled inside a single H3
call, so the only cancellation checkpoint was between rows.

Vertices are now rejected unless longitude is in -180..180 and latitude in
-90..90 degrees, and the cells are enumerated one at a time through H3's cell
iterator, charging the shared `CancellationBudget` per cell. Both functions
share one implementation now, which also drops the staging buffer the results
were copied through.

`h3PolygonToCells` had the same shape, plus H3's legacy algorithm allocating
two estimate-sized buffers outside the memory tracker. It goes through the same
iterator with `CONTAINMENT_CENTER`, the containment rule its own H3 source
documents for itself. On a 20 by 20 degree box at resolution 9 it returns the
same 58823612 cells in 0.64 s instead of 47 s, with 1.35 GB of peak RSS instead
of 4.5 GB.

Measured on a release build: a valid 20000-vertex polygon at resolution 10 took
7.5 s per row for the first function and 29 s for the second, and both now stop
1.1 s after a 1 s deadline. Clean under MSan and TSan.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116133&sha=e9a215c284fb7445939babacac5b3783e3501669&name_0=PR&name_1=Stress%20test%20%28arm_debug%29
ClickHouse#116133

Co-Authored-By: Claude Opus 5 (1M context) <[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 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.

RandImpl has no aarch64 path — random generation runs a scalar 4x LCG on ARM

5 participants