Skip to content

Try to avoid extra copy - #2

Merged
amosbird merged 1 commit into
amosbird:string-with-size-streamfrom
Avogar:string-with-size-stream
Sep 23, 2025
Merged

amosbird merged 1 commit into
amosbird:string-with-size-streamfrom
Avogar:string-with-size-stream

Conversation

@Avogar

@Avogar Avogar commented Sep 22, 2025

Copy link
Copy Markdown

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Detailed description / Documentation draft:
...

By adding documentation, you'll allow users to try your new feature immediately, not when someone else will have time to document it later. Documentation is necessary for all features that affect user experience in any way. You can add brief documentation draft above, or add documentation right into your patch as Markdown files in docs folder.

If you are doing this for the first time, it's recommended to read the lightweight Contributing to ClickHouse Documentation guide first.

Information about CI checks: https://clickhouse.tech/docs/en/development/continuous-integration/

@amosbird
amosbird merged commit 6f511b0 into amosbird:string-with-size-stream Sep 23, 2025
amosbird pushed a commit that referenced this pull request Nov 19, 2025
…y names

When ClickHouse encounters a distributed table directory with a name that:
- starts with the pattern `shardN_all_replicas` (e.g., `shard3_all_replicas_bkp`)
- but doesn't end with exactly `_all_replicas`

It would crash with a segmentation fault due to out-of-bounds array access.

Trace example:
```
* thread #1, name = 'clickhouse-serv', stop reason = signal SIGSEGV
  * frame #0: 0x000000001194481b clickhouse-server`DB::Cluster::Address::Address(DB::Cluster::Address const&) + 27
    frame #1: 0x0000000011944550 clickhouse-server`void std::__1::vector<DB::Cluster::Address, std::__1::allocator<DB::Cluster::Address> >::__push_back_slow_path<DB::Cluster::Address const&>(DB::Cluster::Address const&&&) + 208
    frame #2: 0x00000000129a6c35 clickhouse-server`DB::StorageDistributed::parseAddresses(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const + 3349
    frame #3: 0x00000000129a589b clickhouse-server`DB::StorageDistributed::getDirectoryQueue(std::__1::shared_ptr<DB::IDisk> const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) + 3675
    frame #4: 0x00000000129a3f22 clickhouse-server`DB::StorageDistributed::initializeDirectoryQueuesForDisk(std::__1::shared_ptr<DB::IDisk> const&) + 2082
    frame #5: 0x000000000f681c48 clickhouse-server`DB::ThreadPoolCallbackRunnerLocal<void, ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >, std::__1::function<void ()> >::operator()(std::__1::function<void ()>&&, Priority)::'lambda'()::operator()() + 136
    frame #6: 0x000000000f68286c clickhouse-server`std::__1::packaged_task<void ()>::operator()() + 44
    frame ClickHouse#7: 0x000000000d83335b clickhouse-server`ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >::ThreadFromThreadPool::worker() + 2395
    frame ClickHouse#8: 0x000000000d839e23 clickhouse-server`void std::__1::__function::__policy_invoker<void ()>::__call_impl<std::__1::__function::__default_alloc_func<ThreadFromGlobalPoolImpl<false, true>::ThreadFromGlobalPoolImpl<void (ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >::ThreadFromThreadPool::*)(), ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >::ThreadFromThre
adPool*>(void (ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >::ThreadFromThreadPool::*&&)(), ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true> >::ThreadFromThreadPool*&&)::'lambda'(), void ()> >(std::__1::__function::__policy_storage const*) + 99
    frame ClickHouse#9: 0x000000000d830602 clickhouse-server`ThreadPoolImpl<std::__1::thread>::ThreadFromThreadPool::worker() + 2242
    frame ClickHouse#10: 0x000000000d8379ba clickhouse-server`_ZNSt3__114__thread_proxyB6v15007INS_5tupleIJNS_10unique_ptrINS_15__thread_structENS_14default_deleteIS3_EEEEMN14ThreadPoolImplINS_6threadEE20ThreadFromThreadPoolEFvvEPSA_EEEEEPvSF_ + 90
```
amosbird pushed a commit that referenced this pull request Dec 28, 2025
Docs: move aggregate functions docs to source (#2)
alexey-milovidov pushed a commit that referenced this pull request Jan 19, 2026
amosbird pushed a commit that referenced this pull request Apr 1, 2026
## #1: Cross-test ownership ratio (find_tests.py)

Replace plain `1/width` scoring with `1/(width × region_test_count)` where
`region_test_count = uniqExact(test_name)` for each region.  A region covered
by 1 test scores 1000× higher than one covered by 1000 tests, naturally
eliminating the hot-region problem without a hard cap.

## #2: Branch direction (LLVMCoverageMapping + coverage_log)

Parse `BranchRegion` (LLVM kind=4) in `readLLVMCoverageMapping`.  Format:
kind-marker → true_counter → false_counter → line/col, producing two
`CoverageRegion` entries with `is_branch=true` and `is_true_branch` set.
Added `branch_flags Array(UInt8)` to `system.coverage_log` (0=code, 1=true,
2=false).  Tests that covered both sides of a changed condition now carry that
information for smarter ranking.

## #3: Indirect call targets (coverage.h/cpp + CoverageCollection)

Read `LLVMProfileData::Values` (LLVM value profiling, kind IPVK_IndirectCallTarget)
to capture which concrete functions were called via virtual dispatch or function
pointers.  Each observation: `(caller_name_hash, caller_func_hash, callee_offset,
call_count)` where `callee_offset = callee_abs − binary_load_base` (from
`/proc/self/maps`), stable across ASLR restarts.  Flushed alongside coverage
counters into `system.coverage_indirect_calls`.  Fixes the fundamental gap where
a test covering `IStorage::read` cannot be distinguished from a test specifically
dispatching to `StorageMergeTree::read`.

## #4: XRay call-depth tracking (coverage.h/cpp + cmake/sanitize.cmake)

New CMake option `WITH_COVERAGE_XRAY=ON` enables `CLICKHOUSE_XRAY_INSTRUMENT_COVERAGE`.
At test start, activates XRay (`__xray_patch`) with a handler that maintains per-thread
relative call depth.  On first activation, builds a `(xray_function_id → profile_data_index)`
map by resolving each function via `__xray_function_address(id)` + `dladdr()` → symbol name
→ FNV64 hash → match against `LLVMProfileData::NameRef`.  This solves the PIE
`FunctionPointer=0` limitation: XRay provides real runtime text addresses where
`LLVMProfileData::FunctionPointer` is always null.  When enabled, `min_depth` in
`CovCounter` contains actual call depth; otherwise falls back to call-count proxy.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
amosbird pushed a commit that referenced this pull request Apr 27, 2026
…079-3df0)

`LimitSeekableReadBuffer::seek` used the expression
`pos + position_change` inside its in-buffer fast-path check. When the
inner buffer has not materialized its memory yet — as is the case for
`EmptyReadBuffer`, `ParallelReadBuffer`, and `ReadWriteBufferFromHTTP`,
all of which start with `pos == nullptr` — and a non-zero seek is
requested before the first `next()`, this triggers undefined behavior
per [expr.add]: "applying non-zero offset N to null pointer". On master
BuzzHouse (arm_asan_ubsan) this surfaced from the BACKUP write path as
STID 3079-3df0:

```
src/IO/LimitSeekableReadBuffer.cpp:97:34: runtime error: applying non-zero offset 1178 to null pointer
  #0 DB::LimitSeekableReadBuffer::seek(long, int)
  #1 DB::BackupWriterDefault::copyDataToFile(...)
  #2 DB::BackupImpl::writeFile(...)
  #3 DB::BackupsWorker::writeBackupEntries(...)
```

Replace the pointer-arithmetic comparison with an equivalent check
expressed via pointer *differences* and integer arithmetic, which is
well-defined regardless of whether `pos` is null. The condition is
mathematically identical to the original for all legal inputs.

Add `gtest_limit_seekable_read_buffer.cpp` covering the null-`pos`
regression plus two sanity tests for the in-buffer and out-of-buffer
seek paths. Without the fix the first test reproduces the exact UBSan
error from CI; with the fix all three pass cleanly under
`-fsanitize=address,undefined`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4b8132993ce0625e9c0ed0bf15ed16eb6df8262b&name_0=MasterCI&name_1=BuzzHouse+%28arm_asan_ubsan%29
amosbird pushed a commit that referenced this pull request May 13, 2026
`getReturnTypeImpl` already constrains the second argument of
`kostikConsistentHash` / `jumpConsistentHash` to an integer type, so the
constant bucket count can be read directly via `IColumn::getInt` /
`getUInt` instead of materialising an intermediate `Field`.

Apart from being a small simplification this fixes a `-march=x86-64-v3`
regression: `Field` is a 32-byte object, and `clang` lowered the
`Field buckets_field = (*arguments[1].column)[0]` copy to YMM
`vmovups`-pairs.  The dirtied AVX upper state then forced `vzeroupper`
before every per-row call to the (separately compiled, scalar-only)
`ConsistentHashing` helper, regressing
`consistent_hashes #0/#2/#4` ~10–13% on AMD release.

After the refactor the per-row hot path no longer touches YMM at all;
the remaining `vzeroupper` instructions left in the function body are in
cold exception-construction paths and execute as no-ops because the
upper YMM state is already clean.

On Sapphire Rapids LTO (100M rows):
  - master:                 0.211–0.215 s
  - PR (no fix):            0.227–0.242 s  (+11 %)
  - PR + this refactor:     0.211–0.214 s  (matches master)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
amosbird pushed a commit that referenced this pull request May 13, 2026
`convertNumericGeneral` runs a per-element `static_cast` loop. For
same-width integer conversions (e.g. `toInt64(UInt64)`, `toUInt32(Int32)`,
`toUInt8(Int8)`) `static_cast` is a pure bit-reinterpret, so the loop is
semantically a memcpy.  Calling `std::memcpy` directly is the natural way
to express that.

It also avoids a v3 codegen issue that caused the recurring CI regression
in `decimal_casts #2` (`SELECT toInt64(x) y, toDecimal32(y, 1),
toDecimal64(y, 5), toDecimal128(y, 6) FROM t` with `x UInt64`):

- At `-march=x86-64-v3` clang's SLP vectorizer widens the trivial copy
  loop to 4-way unrolled 256-bit `vmovdqu ymm` stores in
  `callOnIndexAndDataType<...NameToInt64...>` (232 YMM moves vs master's
  126 XMM `movdqu`).  The wider stores left the upper YMM state dirty,
  triggering an SSE/AVX state-save penalty on Intel cores that serialise
  the transition - reproducible in CI as ~+13.6% on this query, even
  though the YMM loop on its own is no faster (memory-bandwidth-bound).
- Routing same-width integer conversions to `std::memcpy` removes the
  YMM emission entirely and shrinks
  `callOnIndexAndDataType<DataTypeNumber<long>, ..., NameToInt64>` from
  30527 to 4084 bytes.  No XMM, no YMM in the function body.

Local Sapphire Rapids LTO (max_threads=12, 500 iter):
  - master:  0.064s median, 0.072s p90
  - PR:      0.063s median, 0.070s p90

Behaviour preserved: same-width integer reinterprets (e.g. `toInt8(255_u8)
== -1`, `toUInt8(-1_i8) == 255`, `toInt32(0xFFFFFFFF_u32) == -1`) match
the pre-change loop output.  The accurate / overflow-checking strategies
(`AccurateConvertStrategyAdditions`, `AccurateOrNullConvertStrategyAdditions`)
are excluded from the fast path because they need the per-element checks.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
amosbird pushed a commit that referenced this pull request May 13, 2026
At x86-64-v3 the loop and SLP vectorizers widen the per-row Int128
stores in convertToDecimalBatch into YMM/XMM packs (vmovq +
vpunpcklqdq + vmovdqu) wrapping the BMI2 mulxq, costing 4 vmovq
GPR->XMM moves and 2 vpunpcklqdq per 2 elements. The packing
overhead dominates the mulxq win, regressing sum ClickHouse#16 ~12% and
decimal_casts #2 ~7-12% on x86-64-v3 vs v2 master.

Disable the loop and interleave vectorizers for the scaled multiply
loop with a clang loop pragma gated on __AVX2__. Plain GPR stores
keep the mulxq v3 win and match v2 master's hot-loop perf.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
amosbird added a commit that referenced this pull request May 19, 2026
…ax indices

Address PR ClickHouse#101170 review feedback (CI #2):

- Drop the 5 add_minmax_index_for_* members from ProjectionDescription. They
  were stale ad-hoc fields duplicating MergeTreeSettings; with the new generic
  SettingsChanges flow the effective MergeTreeSettings is already the canonical
  representation.
- Thread the already-computed effective MergeTreeSettings (defaults from the
  projection index plus user WITH SETTINGS overrides) into fillProjectionDescription
  and fillProjectionDescriptionByQuery as a new parameter, instead of
  reconstructing it. fillProjectionDescriptionByQuery reads the implicit-minmax
  flags via strongly-typed MergeTreeSetting accessors.
- Add the 5 add_minmax_index_for_* names to ALLOWED_PROJECTION_SETTINGS so the
  feature added in ClickHouse#105137 (Enable Implicit Skip Indices for Projections) keeps
  working under the new settings flow.

The ATTACH validation gap raised by review item #3 is intentionally left as
`mode <= LoadingStrictnessLevel::CREATE` to match the project-wide convention
(InterpreterCreateQuery, registerStorageMergeTree, etc. all validate user input
on CREATE/SECONDARY_CREATE only). The previous loadSettings validated
unconditionally because it had no access to mode; now that we do, aligning with
the rest of the codebase is the consistent choice.
alexey-milovidov pushed a commit that referenced this pull request Jun 6, 2026
ClickHouse#106278 tried to remove the LIMIT-without-ORDER-BY non-determinism by
sampling with WHERE cityHash64(WatchID) % N = 0. Post-merge master data
showed it did not work: it made the measured queries scan the whole table on
every run, so instead of reducing the noise it regressed it badly:

  classification #0: 6.5% -> 76% noisy
  classification #1:  10% -> 90% noisy

(#2/#3/#4 were already clean.)

Materialize the deterministic subset once into its own single-part table
(single-threaded insert + OPTIMIZE FINAL) and measure over that, so the
determinism lives in the setup (like ClickHouse#106249 for reading_from_file) and the
measured queries read only the subset instead of rescanning the source.
alexey-milovidov pushed a commit that referenced this pull request Jul 2, 2026
The "Docker server image" job builds the distroless/alpine/ubuntu images with
`docker buildx build`. buildx resolves the SBOM scanner image
(docker/buildkit-syft-scanner, pulled because of --sbom=true) and base images
from docker.io. When docker.io has a transient outage, the build fails at:

  #2 resolve image config for docker-image://docker.io/docker/buildkit-syft-scanner:stable-1
  #2 ERROR: unexpected status from HEAD request to https://registry-1.docker.io/...

and the downstream "docker library image test" then reports "image does not
exist!" as a secondary victim.

praktika's Shell.run / Result.from_commands_run already support retries with
exponential backoff and an error allowlist, but the buildx build and the
imagetools merge commands ran with no retries. Wire retries=5 and an
allowlist of transient registry/network signatures into both. The allowlist
keeps fail-fast behavior for genuine Dockerfile/build errors. This mirrors the
existing retry hardening for the in-Dockerfile wget downloads (ClickHouse#105139) and the
keeper image S3 artifact fetch (ClickHouse#108675).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Jul 28, 2026
alexey-milovidov pushed a commit that referenced this pull request Jul 31, 2026
The fix in this PR makes three FilterTransform call sites compose their
applied filter into ChunkInfoRowNumbers. Only the two stripped-PREWHERE
fallback filters were covered by 04615; the Iceberg equality-delete
notIn filter was not, so the equality-delete half of the contract was
unproven.

Reverting only the equality-delete call site to the old behaviour makes
the new test fail, and pristine master fails it too: on a table that
carries equality delete files the _row_number column is built from a
stale mask, which either aborts with a column length mismatch
("Expected the argument #2 ('__table1._row_number' of type Int64) to
have 423 rows, but it has 470") or silently yields compacted post-filter
indices instead of physical row positions. Those indices are what the
mutation path writes into positional delete files, so a wrong value
deletes the wrong rows.

The test uses the existing committed fixtures: deletes_db/eq_deletes_table
(equality plus position deletes, also read under PREWHERE so the fallback
filter stacks on top of the notIn filter) and
deletes_db/eq_deletes_required_table (equality deletes only, where the
exact physical row numbers are asserted). The per-file offset assertion is
independent of the engine path: it is checked against the raw Parquet data
files read directly through s3().

Co-Authored-By: Claude Fable 5 <[email protected]>
amosbird pushed a commit that referenced this pull request Aug 20, 2026
A query flagged in `report.html` was dropped when `all-query-metrics.tsv` had
no `client_time` row for it, and a shard whose TSV could not be read dropped
all of its flagged queries. With every flagged query dropped the run ended with
"the comparison ran and was clean" - a non-empty CI report turned into an
all-clear. The cause is deliberate on CI's side: `compare.sh` retracts a query
from the TSV when its confirmation rerun demoted it, while the report still
lists it under both "Changes in Performance" and "Unconfirmed Changes". On
PR ClickHouse#115255 that is `round_down` #2 and #3 and `and_compare_chain_derived` #2.

Those rows carry their own numbers, so they are now read from `report.html` and
marked `*` in the report - CI's verdict on them was already in doubt, which
makes them the most interesting queries to rerun, not the ones to discard. A
flagged query readable from neither source is reported as unresolved, and if
that leaves nothing to rerun the run fails instead of reporting a clean
comparison.

The commit under test drove only the report and binary lookup; the XMLs,
`perf.py`, its `stat_threshold`, and the configs still came from the working
tree. Query indices are positional and substitutions expand them, so a tree
that differs from the measured commit silently reruns a different query - on a
checkout one commit behind master, `and_compare_chain_derived.xml` has no query
#2 at all while CI flagged exactly that, and a `refs/pull/<n>/merge` checkout
is never the commit CI measured. `tests/performance`, `programs/server` and
`tests/config/top_level_domains` are now extracted from that commit into the
work dir and everything runs from there, fetching the commit when the clone
lacks it. `--use-working-tree-tests` opts out for iterating on a local test.

Verified: all six flagged queries of PR ClickHouse#115255 are now kept, the three the TSV
retracts carrying the report's numbers and flagged as unconfirmed; a dry run of
PR ClickHouse#112688 recovers `date_time_64` #5, which had been dropped the same way, and
runs against the extracted tree.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115278&sha=baefff6dcc4dbb3201337a52b5ca54453fb34562&name_0=PR&name_1=Style%20check
Pull request: ClickHouse#115278

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GYYbBbrQpmi2zkYJ8LQw5Z
alexey-milovidov pushed a commit that referenced this pull request Sep 25, 2026
Review asked to keep the block sizes always a power of two, so the fill's
`max_block_size` moves from 65409 to 65536. It now matches the
`max_insert_block_size` beside it and
tests/performance/join_convert_full_to_left_or_right.xml, which pins the same
pair at 65536.

65409 was the current default of the setting (`DEFAULT_BLOCK_SIZE` in
src/Core/Defines.h, 65536 minus the SIMD padding), so the pinned value is now a
deliberate round number instead of a restatement of that default. The comment
dropped the sentence naming 65409 as the default, which the swap makes false,
and states the invariant the pin buys instead.

Nothing the test asserts or measures changes. Both tables still write 16 active
parts, so the `throwIf` oracles stand; the cut moves from 15 x 65409 rows +
18865 to 15 x 65536 + 16960. Measured with `EXPLAIN indexes = 1` on all three
queries, 65409 -> 65536:

  #0  parts 3/16 unchanged, index range 39246 -> 39321 granules, read 3 -> 3
  #1  parts 1/16 unchanged, read 1 -> 1
  #2  parts 12/16 unchanged, 156984 -> 157284 granules, read 133114 -> 133110

The +0.19% is the range the skip index walks, not the data read. With both
sides at one layout the worst arm spread measured on #0 is +9.6% over 5537
jobs, against the check's 15% floor, so the shift is far below either.
amosbird pushed a commit that referenced this pull request Sep 28, 2026
These queries were flagged as slower/faster/unstable on master runs, or scored as confirmed regressions by the performance dashboard on unrelated PRs, because the two compared servers did not measure the same work:

- `and_compare_chain_derived`: both tables are created with `numbers_mt`, which writes a varying number of parts, and the measured runs stop merges, so the servers read different layouts (the join query took 34 ms over 17 parts and 82 ms over one part on the same binary). Merge each table to one part and check it. Query 2 now keeps 2M rows per side (`8000000 < l.v`) and runs at about 150 ms instead of 20 ms.
- `set_index`: the IN set was built from `rand`, so every run looked up a different set, selected different ranges and read a different number of rows before `read_overflow_mode = 'break'`. Use a fixed pseudo-random sample (`toUInt32(cityHash64(number))`) and merge the 500M-row table to one part.
- `formats_columns_nullable`: `SELECT * ... LIMIT 1000` read 6-10 ms, and parallel parsing parsed a varying amount ahead before the LIMIT cancelled it (`LIMIT 30000` of CSV took 197 ms with it and 38 ms without). Disable parallel parsing for that query and read 100000 rows, about 200 ms for text formats.
- `serialization_pool_lookup`: the fixed `max_threads = 16` oversubscribed the 8 pinned cores of the amd runners; query 0 was flagged in 9.3% of amd master runs against 0.4% on arm. Use the harness default of one thread per pinned CPU.

Master flag rates over 14 days (slower/faster/unstable share of master runs): `and_compare_chain_derived #2` 5-8%, `set_index #0` 14% (arm), `formats_columns_nullable #1` 19% (arm), `serialization_pool_lookup #0` 9% (amd).
amosbird pushed a commit that referenced this pull request Sep 28, 2026
Query #0 groups 5M rows by a single-type Dynamic key. For every row the
aggregation looks up the variant's default serialization in
SerializationObjectPool: a shared lock on the key's shard mutex,
weak_ptr::lock, and the release of the returned SerializationPtr. These
are atomic read-modify-writes on two cache lines that every aggregation
thread writes for every row. One key means one shard, so the pool's
sharding cannot spread the load, and the query is bound by how fast those
lines move between cores. That speed is fixed per server process.

CI data (query_metric_runs_v1, arm, 1177 runs since 2026-09-17): the 5-7
samples of one server agree within 0.7% (p50), but the per-process medians
span 0.643-0.840 s (p05-p95). Fast and slow processes do the same work
(same arena bytes, memory, two-level hash tables and page faults) and
differ only in user CPU time (9.5 vs 12.1 s). The wall time does not
depend on the thread count: arm 0.754 s with 16 threads vs 0.775 s with
12, amd 0.669 s with 16 threads on 8 pinned cores vs 0.686 s with 8. So
each A/B run compares two random draws of that per-process speed. Runs
whose new/old median moved by more than 15% (raw samples):

                                 arm PR   arm master   amd PR   amd master
    serialization_pool_lookup #0  123/789     54/558    68/176     220/560
    serialization_pool_lookup #1   41/789     11/558     5/176      20/560
    serialization_pool_lookup #2    0/789      0/558     0/176       0/560
    group_by_dynamic_keys #0        0/782      0/559     0/173       0/559

group_by_dynamic_keys #0 runs the same per-row lookup path with
max_threads = 1. On PR ClickHouse#117533 the performance dashboard scored #0 as a
confirmed regression (arm 5/6, 0.670 -> 0.799 s) that the shard's own
report did not flag.

Run #0 in one thread, from numbers instead of numbers_mt, so it times the
pool's hit path itself, which does not depend on the process. Queries #1
(two keys, where sharding spreads the load) and #2 (the multi-threaded
MergeTree read) keep the contention coverage.

Local check on x86 with the official 26.10.1.820 master build, perf.py,
7 runs: old #0 1.76 s with 12 threads (15.4 s user CPU per run), new #0
0.57 s (0.56 s user CPU), same result. Ten fresh servers pinned to 8
cores with max_threads = 8: old #0 per-process medians 0.68-1.08 s; new
#0 0.56-0.58 s in 8 of them and 0.72-0.73 s in the two whose table
fills were also about 25% slower (9.2-10.0 s vs 7.4-8.6 s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
amosbird pushed a commit that referenced this pull request Sep 28, 2026
Pointing `contrib/nlohmann-json` at the ClickHouse fork makes the copy of
`nlohmann::json` that `ai-sdk-cpp` vendors in
`third_party/nlohmann_json_patched` an ODR violation rather than a duplicate.
Both are version 3.12.0, so both define the same `nlohmann::json_abi_v3_12_0`
symbols, and the two definitions no longer match: the fork holds a
`number_buffer` member in `lexer` that the vendored copy has no field for, and
drops the `decimal_point_char` the vendored copy keeps, so the fork's `parser`
is the larger of the two. The linker resolves this by keeping one definition of
each symbol, so a `parser` laid out by the vendored header is handed to a
`parse` compiled from the fork header, which reads and destroys members past
the end of it.

In a sanitizer build this aborts on the first response of a model, which is how
it was found - every AI client test of
ClickHouse#114043 failed this way:

    ERROR: AddressSanitizer: stack-buffer-overflow
        #0 nlohmann::json_abi_v3_12_0::detail::parser<...>::parse(...)
             contrib/nlohmann-json/single_include/nlohmann/json.hpp:13073
        #1 nlohmann::json_abi_v3_12_0::basic_json<...>::parse<...>(...)
             contrib/ai-sdk-cpp/third_party/nlohmann_json_patched/include/nlohmann/json.hpp:4053
        #2 ai::providers::BaseProviderClient::generate_text_single_step(...)
      [32, 232) 'ref.tmp' (line 4053) <== Memory access at offset 240 overflows this variable

and the `MemorySanitizer` build reports the same defect from the other side,
the `lexer` destructor of that call destroying a `std::string` that was never
constructed. In a release build the same code reads and writes past the end of
a stack object without anything catching it, on the path of the `??` command of
the client and of the server-side `aiGenerate` function.

Nothing on this branch drives a model, which is why its own CI does not show
this, so the fix goes here rather than only in the pull request that found it:
this branch is the one that introduces the second definition.

Build `ai-sdk-cpp` against `contrib/nlohmann-json` instead, so there is one.
The vendored copy exists to keep the number parsing away from the locale, which
the fork does properly, so there is nothing left to keep it for.
`nlohmann-json` is now added unconditionally rather than only for
`google-cloud-cpp` - the two are enabled independently of each other - and its
include directory is marked as a system one, because it now reaches
ClickHouse's own translation units through `ai-sdk-cpp`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
amosbird pushed a commit that referenced this pull request Sep 29, 2026
…columns performance test

`least_greatest_const_columns #2` returns the 256-byte constant `repeat('d', 256)` for every row, so
the result `ColumnString` grows its `chars` by power-of-two `realloc` up to 16 MiB per block. Whether
jemalloc grows that buffer in place or moves and copies it (`large_ralloc` -> `memcpy`) differs
between server processes, and in CI CPU profiles that copy is the only part of the query whose sample
count differs between the two servers. In 14 days the two servers differed by more than 15% in 94 of
775 amd and 23 of 1692 arm runs of this query, and in none for `#3`, which takes the same arguments
with `least` and returns the ~7-byte `toString(number)`.

Add a constant `'e'` that wins every row, so the result is one byte per row. The query still compares
`toString(number)` against the four 256-byte constants that are not materialized since ClickHouse#119108, and
still returns a constant argument.

Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/36432228454/job/109047348805
PR: ClickHouse#122184

Co-Authored-By: Claude Opus 5.5 <[email protected]>
amosbird pushed a commit that referenced this pull request Sep 29, 2026
…ion over a `Nullable` argument

The `-If` null adapters merged the null map with the condition into a buffer
sized by the absolute end row of the call and filled only `[row_begin, row_end)`.
Aggregation in order calls `addBatchSinglePlace` once per key interval, and
window frames once per frame update, so with 8-row groups every call asked for
up to 64 KiB to use 8 bytes. The merges the nested functions do for themselves
(`SingleValueData`, `groupBit*`, the simple moments, `regr_*`,
`timeSeriesLastTwoSamples`) were sized the same way.

On x86_64 every such request above 32 KiB exceeds jemalloc's thread cache
limit (`opt_tcache_max`) and takes the arena large-extent path, whose cost
depends on the state of the process. On aarch64 (64 KiB pages) these sizes are
small size classes served from the thread cache. That is why queries #2 to #5
of `tests/performance/aggregation_in_order_if_null_map.xml` are unstable on
the amd runners only: in the last 14 days CIDB has 2008 of the test's 2174 amd
`unstable` verdicts on #2 to #5, and 8 on arm in total.

With a single `Nullable` argument no merged map is needed:
`addBatchSinglePlaceNotNull` takes the null map and the condition column
separately, and every implementation handles `if_argument_pos`
(`AggregateFunctionIf` already calls them all that way). So
`AggregateFunctionIfNullUnary` with a non-`Nullable` condition passes the
value's null map and the condition at position 1, and
`AggregateFunctionIfNullVariadic` with exactly one `Nullable` argument passes
that argument's null map to the nested `-If` function, which applies the
condition. The merges those calls reach allocate `row_end - row_begin` bytes
and call their kernels with pointers rebased by `row_begin`, as `sum` and
`avg` already do. The same rows are added in the same order, so the results
do not change. Two or more `Nullable` arguments (query #5, `corr(x, w)`), a
`Nullable` condition of a one-argument `-If` function and the TimeSeries
array merges keep their merged buffer.

Measured on a release build (x86_64, `max_threads` 8), base / this change,
per run of each query of the test:
- jemalloc large allocations above 32 KiB: #0 703 / 703, #1 714 / 714,
  #2 302182 / 703, #3 302142 / 663, #4 229046 / 1718, #5 115413 / 115413;
- CPU profiler samples in the jemalloc large-extent path: #2 33% / 0.9%,
  #3 31% / 0.5%;
- perf.py median of 13 runs, two alternating rounds (ms): #2 38.2, 39.8 /
  24.6, 21.7; #3 39.0, 40.2 / 21.3, 19.8; #4 44.3, 45.4 / 28.3, 25.9;
  #0, #1 and #5 unchanged;
- `minIf(x, cond) OVER (ORDER BY k ROWS BETWEEN 100 PRECEDING AND CURRENT
  ROW)` over 1M rows: 340 / 166 ms, and `sumIf(y, cn)` over a `Nullable`
  condition: 301 / 89 ms;
- aggregation without keys over the same table: 12.2 / 12.3 ms.

Query #0, flagged on ClickHouse#118490,
never had such a buffer and is not changed here.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118490&sha=8ded98e22889e53dd536b141b564e136c76482a9&name_0=PR&name_1=Performance%20Comparison%20(amd_release%2C%20master_head%2C%203%2F6)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 3, 2026
…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` #1 (constant mask) and #4 (`UInt32` arguments) have
per-build speed modes and flag unrelated PRs in Performance Comparison
(ClickHouse#122482), while #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`: #1 0.57 (BMI2) / 0.55 (lookup-table path, built
with `-mno-bmi2`), #2/#3/#6 0.45-0.64, #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]>
alexey-milovidov pushed a commit that referenced this pull request Oct 3, 2026
…test

The two compared servers each built a different copy of the fixture:

- `rand64() % 5000000` makes the number of rows with key 5, which queries
  #1 and #3 look up, a fresh draw per server (0 to 3 over 10 local fills);
- each INSERT is squashed into ~5 parts (cut at min_insert_block_size_rows),
  which merge until perf.py's --stop-merges freezes them at a per-server
  point.

#1 and #3 read about one granule per part, so each server read its own
number of granules: in CI the servers read different parts in 80% of runs,
and time follows the rows read (correlation 0.85-0.88). This redded
unrelated PRs (e.g. ClickHouse#118662, arm 4/6, #1 +37.5% confirmed_regression) and
inflated the learned threshold of #1/#3 to 0.41-0.53 (0.04-0.09 for
#0/#2/#4 on the same tables); the dashboard now caps both at
likely_regression as "Flaky lately", so a real regression there cannot red.

Use deterministic data, cityHash64(number, 7) and cityHash64(number, 11)
modulo 5000000 (same key range and duplicate profile; the seeds put key 5
once in each table, the modal case of the random draw, so #1/#3 keep
measuring a non-empty point join), and write each table as one part with
min_insert_block_size_rows = 10000000, min_insert_block_size_bytes = 0
(5M rows give one squashed block). A throwIf on system.parts fails the
fill if the layout ever drifts. Same shape as ClickHouse#122479 and ClickHouse#122660.

Validated through perf.py --stop-merges on two servers, 5 fresh fills per
arm: new fixture identical on all 10 server fills (one part per table, same
data, #1/#3 read 2 granules on both, #0/#2/#4 read 10M rows); old fixture
different on all 5 iterations. Without the insert settings the throwIf
fails the fill.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 3, 2026
On x86, returning the rescan of the matching block from inside the block loop
is unrolled into branchless code that reuses the comparisons of the block.
Rescanning after the loop made it a loop whose exit is mispredicted when the
match position varies: `array_index_simd_numeric` #2 got 36% slower on amd.
Return from inside the loop on x86 again, so its code is the same as before
this PR. Other targets keep the `break`, which ARM needs to vectorize the block
loop for 4- and 8-byte elements (the same query got 25% faster on arm).

Related: ClickHouse#123377

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 4, 2026
Since ClickHouse#122458 the first query of the test (#0-ClickHouse#7, one per format) is
SELECT * ... LIMIT 100000 with input_format_parallel_parsing = 0, so the
text formats are parsed in one thread. On ARM the speed of that parse is
fixed per server process: the 7 runs of one server agree within 1-2%,
while different servers take 0.26-0.55 s for #2 (JSONEachRow). In the
failing job on ClickHouse#101022 (+54.9%, 0.338 -> 0.524 s) the confirmation
restart drew new levels for both servers (0.293 and 0.345 s), and the
slow side read the same rows and bytes with 1.58x the user CPU. #1 and #2
share the factor within a process (r = 0.86); it does not reach the
other 80 queries of the same processes, which read the same files with
parallel parsing. Why the single-threaded parse is per process on ARM is
not established.

Runs whose two servers differ by more than 15% (query_metric_runs_v1,
raw samples, since 2026-09-27):

                         arm PR   arm master   amd PR   amd master
    #0 TSVWithNames      38/200      5/33       0/48       0/42
    #1 CSVWithNames     111/191     19/35       0/42       0/30
    #2 JSONEachRow      112/199     15/31       0/34       0/32
    #3-ClickHouse#7 binary          1/982      0/188      0/180      0/185

The 80 parallel-parsing queries on the text formats: 0 of 7232 ARM runs.

Read the whole file with the default parallel parsing instead: without a
LIMIT the amount parsed does not depend on read-ahead (why ClickHouse#122458
disabled parallel parsing), and no text format is parsed in one thread.
Avro has no parallel parsing, so #3 now takes about 2.7 s on ARM
(report-only "too long"; ClickHouse#75 of this test is already 2.16 s). The text of
#0-ClickHouse#7 changes, ClickHouse#8-ClickHouse#87 are unchanged.

Local check on x86 with the official 26.10.1.1403 master build, server
pinned to 16 cores with max_parsing_threads = 16, perf.py, 7 runs: new
#0-#2 0.43, 0.47 and 0.96 s with 3% spread, #3 2.15 s, #4-ClickHouse#7 0.09-0.53 s;
every query reads all 2000000 rows of the file, #0-#2 in 7-15 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 6, 2026
`getStateType` returns a fresh `DataTypePtr` by value, so
`typeid_cast<const DataTypeAggregateFunction *>(nested.getStateType().get())`
leaves the raw pointer dangling: the temporary `shared_ptr` is the only owner
and is destroyed at the end of the full expression, before
`getVersionIfExplicit` is called on it.

ASan caught it in `haveSameStateRepresentationImpl` on a distributed plan:

    ERROR: AddressSanitizer: heap-use-after-free
    READ of size 8 ... thread T998 (TCPHandler)
    #0 DB::DataTypeAggregateFunction::getVersionIfExplicit() const
    #1 DB::IAggregateFunction::getStateTypeWithVersionOf(...) const
    #2 DB::IAggregateFunction::haveSameStateRepresentationImpl(...) const
    #3 DB::haveCompatibleColumnStructure(...)
    #6 DB::addConvertingActions(...)
    ClickHouse#7 DB::createLocalPlan(...)

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115393&sha=53ec8207537fd066d3952b3d8ac42d93ff4b9224&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%20selected%20tests%29
ClickHouse#115393

The state type is now held in a named variable in both
`IAggregateFunction::getStateTypeWithVersionOf` and the `-Tuple` combinator's
`getStateType`, which had the same pattern.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 6, 2026
Picks up ClickHouse#122073, which passes --stop-merges to the measured performance runs.
Before it only the confirm_changes rerun stopped background merges, so the
measured samples that feed the dashboard verdict were taken while merges ran.
The two dashboard-confirmed regressions on the previous head,
optimize_time_filter_with_preimage #6 and index_bulk_filtering #2, are of that
noise class: the shard's own report calls the first unstable and the second
successful, and neither query can reach this diff, which only parses the
vector search arguments of mergeTreeAnalyzeIndexes.
alexey-milovidov pushed a commit that referenced this pull request Oct 6, 2026
…e test

Query #1 (`FINAL WHERE v = 7 LIMIT 100`) never reaches its limit: only 47 rows
survive FINAL, so it scans all of (k, v) and lazily reads `payload` for those
47 rows. With default granules (~5-6K rows of 2 KB random, incompressible
strings, ~10 MB each) every match decodes ~6 MB of payload, ~285 MB in total.

After ClickHouse#122479 both compared servers read identical data, but on arm one server
of a pair still copies those same bytes out of the page cache ~20% slower in a
few percent of fills, and with merges stopped all runs of the query carry it:
PR ClickHouse#122571 got a confirmed +17.8% on `Performance Comparison (arm_release,
master_head, 6/6)` this way.

With `index_granularity = 256` a granule is ~0.5 MB and one compressed block,
so each match reads ~0.5 MB. Measured on a two-server rig with the XML's own
statements: #1 ReadCompressedBytes 284.1 MB -> 31.8 MB, SelectedRows 1,015,104,
#0 and #2 read less too (58.7 -> 13.3 MB). The test still measures FINAL over
the same two intersecting parts with lazy materialization of the wide payload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
amosbird pushed a commit that referenced this pull request Oct 7, 2026
`ColumnArray::insertFrom` calls the element column's virtual `insertRangeFrom`
once per row (e.g. `FunctionIf::executeGeneric` for `if(cond, [DateTime], [Date])`).
Its bound check threw inline and formatted `start`/`length` through
`toString(const T &)`, which takes their addresses, so since
`-fstack-protector-strong` (ClickHouse#119039) every call paid a canary store and check,
a 0xa8-byte frame and two spills. The `conditional` #2/#3 perf queries stepped
+9% on amd and arm at that merge.

Move the throws of `insertRangeFrom` in `ColumnVector`, `ColumnDecimal`,
`ColumnFixedString`, `ColumnString` and `ColumnArray` into `[[noreturn]] NO_INLINE`
helpers taking values by value, as ClickHouse#119039 does for its own hot paths
(`DataTypesDecimal.cpp`). `NO_INLINE` keeps them out of line under ThinLTO.
Conditions, positions and error codes are unchanged; the out-of-bound message
of `ColumnString` and `ColumnArray` now carries start, length and size.

Measured on an x86 release build against master 7cbb8ad: the 27
`insertRangeFrom` instantiations of these columns go from 5-7 `%fs:0x28`
references to 0 (aarch64 `ColumnVector.cpp`: 18/18 `__stack_chk_guard`
sequences gone), and `conditional` #2/#3 run at 0.91-0.93x of master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
amosbird pushed a commit that referenced this pull request Oct 7, 2026
isValidUTF8 called DB::UTF8::isValidUTF8 once per row. For short strings
the query is a tight per-row call loop into a small function in another
translation unit, and on the CI runners its speed depends on code
placement: across 16 CI builds whose code for both functions is identical,
`is_valid_utf8` query #0 (8-byte ASCII rows) is about 20% slower exactly
in the builds where the loop's cache lines alias (mod 4 KiB) the callee's
hot lines. The performance comparison then reports a confirmed regression
on PRs that do not touch this code.

Now the String and FixedString paths find the length of the column's
leading run of ASCII bytes with one simdutf::validate_ascii_with_errors
call. Rows that end inside that run are valid without being visited; the
row that holds the first non-ASCII byte is validated from that byte (a
leading ASCII run never changes the verdict), and the per-row loop
continues from the next row. An all-ASCII column no longer runs the
per-row loop at all. Builds without simdutf skip the shortcut.

Local A/B, release build (non-LTO), cycles:u of 100 x the query in one
process, medians over 5 rounds and over 4 (base) / 3 (fix) code layouts
(the callee moved by 0 to 3008 bytes, code unchanged):

  query                                     base    fix     fix/base
  #0 repeat('a', 8), 3M rows                3.09e9  1.65e9  0.54
  #2 21 x 3-byte + 'aa', 3M rows            11.6e9  11.7e9  1.01
  #4 96 ASCII + 26 x 2-byte, 3M rows        18.2e9  18.5e9  1.02
  #5 6 x 2-byte, 3M rows                    7.31e9  7.33e9  1.00
  #6 4 x 4-byte, 3M rows                    8.07e9  7.97e9  0.99
  ClickHouse#7 '\xFF' + 15 x 'a', 3M rows             10.8e9  9.94e9  0.92

Single layout: #1 (1023-byte ASCII rows) 0.95, #3 (1023-byte CJK) 1.00.
SELECT isValidUTF8(materialize(repeat('a', 8))) FROM numbers(300000000):
0.689 s -> 0.325 s (median of 15 runs each, 4 cores).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 10, 2026
…ce test

Query #1 cast a String to JSON inside the measured query, so most of its
CPU (about 80% in the arm CI profile, 72% on x86 locally) went to the
JSON parser rather than to the serializing hash the test exists for. The
parse has a per-server-process slow mode, so a slow draw on the tested
server read as a hashing regression and turned unrelated PRs red
(Performance Comparison on ClickHouse#117318: +15.8%, gone after a server restart).

Build the JSON column once at fill time in a Memory table and hash the
stored column, single-threaded as before and as in query #2. JSON parsing
itself stays measured by new_json_type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 12, 2026
`base/base/bigEndianCompare.h` uses the two-64-bit-halves form, which
vectorizes to `vpcmpuq`, only under `__AVX512F__`, which official
x86-64-v3 builds never define. The `x86_64_v4` clone of the IPv6 ordered
comparison kernels therefore inlined the `unsigned __int128` form and
extracted every lane to general purpose registers (16 `vpextrq`, 17
stack accesses, no vector compare), and the `FixedString(16)` kernels had
no AVX-512 clone. These are exactly the four `uuid_ip_comparison`
queries (#2, #3, ClickHouse#10, ClickHouse#11) that are noisy on the amd performance runners.

Define the halves form unconditionally as `lessBigEndian16Halves` /
`compareBigEndian16Halves` (the default selection is unchanged) and run
it in one x86-64-v4 loop, `compareBigEndian16_x86_64_v4`, for `<`, `>`,
`<=`, `>=` on IPv6 and FixedString(16), column-column and
column-constant, when the CPU supports x86-64-v4. The IPv6 constant goes
through a small x86-64-v4 wrapper that takes it by value: passing `&b`
from `vectorConstant` itself added a stack frame and a stack protector
check to the default path.

Release builds, `uuid_ip_comparison` queries x25, 3 rounds, one core:
#2 70 -> 42 ms, #3 57 -> 42, ClickHouse#10 54 -> 32, ClickHouse#11 58 -> 32, the other eight
within 2%. The non-AVX-512 code is unchanged apart from the dispatch, and
ARM is not affected.

The test gains FixedString(16) cases and checks every ordered operator on
both types against `hex()` strings over blocks of 1001 rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 13, 2026
SipHash kept the current partial 8-byte word as a union of a UInt64 and
UInt8[8]. `update` wrote a short tail byte by byte into the byte array
(the remainder of a previous update too, which clang emits as a `memcpy`),
and `finalize` stored the `cnt` byte into the last position and then read
the whole word with one 8-byte load. An 8-byte load that overlaps several
narrower in-flight stores cannot be store-forwarded on x86: it waits until
the stores commit (`ld_blocks.store_forward`). When the hash state lives in
memory across a call, e.g. `UniqVariadicHash::apply` -> virtual
`IColumn::updateHashWithValue` -> `get128`, every row pays this. How often
the blocked load is replayed depends on code placement, so the same
machine code is fast in one build and ~55% slower in another: this is why
`entropy #2` of the performance comparison flips between ~0.33 s and
~0.52 s per build on amd (master builds 4f8c9f2..a0b6517, and
PR builds of ClickHouse#117704, ClickHouse#114690, ClickHouse#119760).

Now `current_word` is a plain UInt64 holding the received bytes of the
current word in little-endian order, the bytes not received yet being zero
(the same numeric value the union had on both endiannesses, so
CURRENT_BYTES_IDX is gone). `loadTail` assembles up to 7 bytes in a
register with overlapping 4/1-byte loads, the remainder path ORs it in at
the right shift, the main loop keeps the word in a local, and `finalize`
folds `cnt` into the top byte in a register. Every access to `current_word`
is now a whole-word store followed by a whole-word load. Hash values are
unchanged.

Validation (release build, CMAKE_BUILD_TYPE=None without ThinLTO, Xeon
6975P, `SELECT entropy(MobilePhoneModel)` over 100M rows of a 92%-empty
sparse String column, max_threads=16, medians of 18 runs):
- base 0.218 s, fix 0.150 s; official master builds 562bdc1
  0.204 s (fast layout) and 4f8c9f2 0.285 s (slow layout).
- 15 queries: ld_blocks.store_forward base 1.54e9, fix 2.7e7 (slow official
  6.07e9); cycles 1.44e11 -> 8.98e10; instructions 5.27e11 -> 4.71e11.
- `uniqExact(toString(number % 1000), toString(number % 7))` over 2e8 rows
  5.23 s -> 2.98 s; sipHash64/sipHash128 of 1..5-byte strings -6.4%/-4.8%;
  sipHash64 of 10..50-byte strings +1.1% (instructions +1.8%); GROUP BY
  two String keys unchanged.
- Hash identity: a throwaway differential gtest against the verbatim
  previous class (every length 0..80 x every 3-way split, 3 key pairs,
  get64/get128/get128Reference, double get, update after get, the
  ColumnString row shape, 300k random streams of raw and typed updates):
  2,038,362 cases, 0 mismatches; a planted mutation (wrong value for 4-byte
  tails only) gives 808,592 mismatches. 02534_keyed_siphash and
  02552_siphash128_reference (official vectors) pass, and SQL sums of
  sipHash64/128, keyed and reference variants over 2e7 strings are equal on
  both binaries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
The performance test `uniq_stored` query #2 (merging 2 million stored
single-element `uniq` states) regressed by 22% on ARM: the chunked read and
the batched merge add overhead that does not pay off for tiny states.
Restore the scalar read for `m_size <= 1` and use the plain merge loop when
the right-hand state has fewer than `insert_many_batch_size` elements.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111493&sha=f844d188b1bf6c9c553a5346b12da46a93d601ed&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
ClickHouse#111493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 13, 2026
…ance test

With `optimize_rewrite_like_perfect_affix=0`, every row of the fixture
matches, so `MatchImpl` calls the dispatched StringZilla `sz_find` once per
row, 10M times per query. On amd the cost of that call varies by 5-10%
between binaries and between server processes (the red run's extra CPU
samples are all in `sz_find_skylake`), so over 30 days the old/new ratio of
`#0` crossed 15% in 29 of 1,193 master-vs-master runs and 26 of 1,316 PR
runs (median 1.001), and reddened `Performance Comparison (amd_release,
master_head, 2/6)` on unrelated ClickHouse#122420 (+20.9%, +17.2% after restart).
`#2` behaves the same. The rewrite-on arms never crossed 15% on amd
(0 of 2,518, p99 1.109 / 1.081).

The harness compares the same query index across builds, never one arm
against another, so the `=1` arms are the detector for the rewrite: if it
stopped applying they would get 1.6x to 1.7x slower. The rewrite-off LIKE
path stays measured by the two `optimize_rewrite_like_perfect_affix = 0`
arms of `regexp_anchored_literal.xml` (0 runs above 12% in over 1,050 amd
runs each), and correctness by `03594_like_perfect_affix_rewrite_pass`.
Same shape as ClickHouse#122156.

The survivors renumber to #0/#1, so their learned thresholds reset to the
0.15 floor, which is above their p99.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 20, 2026
In `master_head` mode the PR performance comparison used master's official
release build as the reference. That build keeps debug info and sets
`-DCLICKHOUSE_OFFICIAL_BUILD=1`, while a PR release build has
`-DDISABLE_ALL_DEBUG_SYMBOLS=1` and no official flag. Both change the
generated code (XRay instruments ~11k more functions when debug info is
present, and the official flag adds code), so the same sources give two
binaries with different code layout. The CI-only ClickHouse#123849 has 0x65500 bytes
less code than the official build of its own base e95690a and was
21.6% slower on `window_functions_distinct #2`. On some master bases a hot
loop lands on a slow placement only in the PR flavour, and every PR on that
base then reds (seen on ClickHouse#100391).

MasterCI's `Build (amd|arm_release_pr_cache_warmup)` jobs already compile
master with exactly the PR cmake flags. They now also link
`clickhouse-self-extracting` and upload it, and take the PGO/BOLT decision
of the release build they mirror, as a PR build does.

For PR runs of the public repository, `find_prev_build` prefers that binary.
When the base has none it walks back only over commits where MasterCI
skipped the warmup job (a skipped job means its inputs did not change, so
the older build has the same sources); anything else falls back to the
official build. Replayed over 14 days of PR references, 332 of 356 get a
build with identical compiled sources and none gets different sources.
Master runs (official vs official) and local runs are unchanged. The report
parsing of `classify_missing_prev_master_run` moves into
`master_job_status`, shared by both walks.

The arm warmup's build-profile upload stays what it was (compiled objects):
the server link trace is deleted before extraction and the symbol table of
the linked binary is not uploaded, so the shared build-profile cluster gets
no new load.

Cost: ~24 min (amd) and ~39 min (arm) of ThinLTO link per warmup run and
~540 MB of S3 per run with default retention. MasterCI wall clock is
unchanged and no PR job is added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 22, 2026
…t have no MasterCI run

A PR performance run looks for `Build (<arch>_release_performance_reference)`
of the master commit it is tested on, and goes back to an older build only
over commits where MasterCI skipped that job. A commit of a batched push has
no MasterCI run at all, so the walk stopped there and the run was compared
with the official build. On 2026-10-22 that happened for every PR based on
a6c5f4a (its parent ffbc6be has no run), although 0ddba95 two
commits back has a reference build of the same sources. The official build
places the code differently from a PR build, and `long_primary_key` #0..#2
were 29-51% slower in the PR build, red on unrelated PRs.

Prove "same sources" by the praktika digest MasterCI records for the job in
`workflow_config_masterci.json` instead: pass over commits without a
reference build and accept the newest older one only if its digest equals
the one of the first commit with an official build. The last part of the
digest hashes the job config, which includes the docker `--memory` computed
from the Config Workflow runner's RAM, so it differs between runs with the
same sources and is not compared. Any missing or unreadable record keeps the
official fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 24, 2026
`applyFunction` caches the result of a monotonic key function over the
index column in `field.columns` under the name
`_0x<function pointer>_<column index>`. It built that name on every call
with a `WriteBufferFromOwnString`, `writePointerHex` and
`"_" + toString(column_idx)`, and it is called for both bounds of every
range the analysis checks: about a million calls per query in the
`long_primary_key` performance test, where `toDate(dt) AS dt` puts
`toDate` on the key in `WHERE`.

Format the name into a stack buffer (byte-identical text: `_0x`, 16
lowercase hex digits, `_`, the decimal index) and look it up as a
`std::string_view`; make a `String` only when an entry is added.

x86 RelWithDebInfo, `clickhouse local`, the test's tables with one part
each, 16 interleaved launches: `FilteringMarksWithPrimaryKeyMicroseconds`
median 227 -> 116 ms (#0), 225 -> 114 ms (#1), 227 -> 114 ms (#2).

Related: ClickHouse#127480

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 25, 2026
Since ClickHouse#109006 (26.8) `max_insert_threads` defaults to auto, so each
`INSERT ... SELECT` of these tests writes its 50-100 parts from 8 (amd)
or 12 (arm) threads instead of one. A Wide part of the `hits_10m_single`
schema is ~475 files; on the IOPS-capped CI disk the parallel writers
wait for the write-back of the previous runs (OSIOWaitMicroseconds per
INSERT 0.17 s -> 8 s, same OSWriteBytes and FileOpen), so every run is
slower than the one before and the three tests became ranks #2, #3 and
#5 of the noisiest performance tests on master (ClickHouse#100759), from 0% over
the report floors before ClickHouse#109006.

Pin the setting to 1, as ClickHouse#109006 documents for restoring the previous
behavior. The queries, parts and files written are unchanged; parallel
INSERT SELECT stays covered by parallel_insert.xml and insert_parallel.xml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 29, 2026
…ee stack placements

Since ClickHouse#126977 both perf servers start with ASLR disabled, so every start of a
binary puts its thread stacks at the same place. A change that only moves the
query threads' frames within their stack pages (on ClickHouse#112928, `ThreadPool` worker
frames 32 bytes larger) then reproduces at every restart: `set_in_clustered_keys`
#2/#3 were 28-32% slower on arm with an instruction-identical `keys256` probe
and equal static TLS, and the confirmation rerun reproduced them (+27.1%,
+29.8%), so the shard stayed red.

`confirm_changes` now reruns the flagged queries at three placements: the main
run's own, and with `glibc.rtld.optional_static_tls` = 512 + 21*64 and
512 + 43*64 for both servers (glibc puts the static TLS block at the top of
every thread stack, so all thread stacks move 1344 and 2752 bytes lower).
`restart` takes the surplus as an optional argument; without it nothing changes.
`eqmed.sql` runs separately per placement, step 5's rule is evaluated per
placement, and `query-metric-stats.tsv` gets, per query, an actual placement
row on the side of the two-of-three majority (the one farthest from the
thresholds), so step 5 and the dashboard check in `performance_tests.py`, which
are unchanged, reach the majority verdict. With fewer than three placements
measured (a failed restart or rerun, the time budget), the placement 0 row is
used, which is the previous behaviour; without it the original verdict stands.
The per-placement verdicts go to `placement-verdicts.tsv` and the job log.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 5, 2026
Each removed query has the same text, settings and tables as a query in
another file, so it measured the same path a second time.

- date_time_short.xml: deleted. 15 of its 16 queries are date_time_long
  ClickHouse#49, 76, 94, 131, 141, 144, 106, 146, 148, 152, 160, 170, 171, 109, 121.
  Its only other query, toUnixTimestamp(toUInt16(t)), is appended to
  date_time_long as ClickHouse#172 (no other index of date_time_long moves).
- external_distinct_tail_spill #0, #2, #3: same as
  external_distinct_coalescing #0, external_distinct_spill_blocks #1 and
  external_distinct_limit_remerge #0. #1, #4, #5 become #0, #1, #2; the
  header comment no longer mentions ordered output.
- if_transform_strings_to_enum #0, #1 (without the setting): same as
  group_by_no_aggregates_string_keys #0, #1. #2, #3 become #0, #1.
- cpu_synthetic ClickHouse#25 (cutQueryString(URL) on hits_100m_single): same as
  url_hits ClickHouse#20. ClickHouse#26-ClickHouse#39 become ClickHouse#25-ClickHouse#38.
- hash_table_sizes_stats ClickHouse#13 (min(MobilePhoneModel)): same as
  agg_functions_min_max_any ClickHouse#16. It was the last query, nothing moves.
- prefetch_in_aggregation #4, #5 (numbers/numbers_mt(10000000) GROUP BY
  number): same as hash_table_sizes_stats #1, #3. The template is pinned to
  50000000; #6-ClickHouse#13 become #4-ClickHouse#11.
- uniq_up_to_saturated_hash #0 (uniqUpTo(5)(SearchPhrase)): same as
  uniq_hits_no_key_other ClickHouse#48. #1 becomes #0.

max_size_to_preallocate_for_aggregation = 1e9 in hash_table_sizes_stats
does not make its copies a different path: it only matters above
1e9 / 16 groups per table, and these queries have at most 10M groups.

Kept as different paths: parse_engine_file #3 / tsv_csv_nullable_parsing #1
(different tables), string_sort ClickHouse#10 /
top_k_dynamic_filtering_single_string_column #2 (the latter sets
use_query_condition_cache = 1), text_index ClickHouse#31-ClickHouse#33 /
text_index_phrase_blocked #4-#6 (different text indexes and settings).

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 14, 2026
The four queries of `rand.xml` have the shape
`SELECT count() FROM (SELECT f() FROM zeros(N))`. `count()` reads no column
of the subquery, so the projection is dropped and `f()` is never called: in
CI `FunctionExecute` is 0 in every run of all four queries on both
architectures, and the queries time `count()` over `zeros()` (4-8 ms for
queries 2 and 3), which is noise. This started with the analyzer becoming
the default (ClickHouse#61652): on master `rand #2` went from 246 ms on 2024-03-26 to
6.3 ms on 2024-03-27.

Performance test queries keep their numbers, so queries 0-3 are disabled
(`disabled="1"`, text unchanged) and queries 4-7 are appended in the
`WHERE NOT ignore(f())` form used by `random_string.xml` and
`synthetic_hardware_benchmark.xml`, with the same row counts. `ignore` is
never constant-folded, so its argument is computed for every row.

Related: ClickHouse#110105, ClickHouse#101039

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 14, 2026
…up window

`NegativeLimitBySortedStreamTransform::consume` sent every group, even one
that starts and ends inside the current chunk, through the sliding window:
`append_run` pushed a `ChunkSlice` into the empty window deque (allocating the
deque map and a block, and copying the chunk `shared_ptr`), `finalizeWindow`
copied it into `pending` (a second `shared_ptr` copy) and then `window = {}`
(libc++: `clear(); shrink_to_fit();`) freed the block and the map. So each
one-row group cost two memory-tracked allocations, two frees and two atomic
increment/decrement pairs, plus one `pending` entry.

The window is only needed for a group that touches a chunk boundary. A group
that ends inside the chunk while the window is empty also started inside this
chunk, so its output is known when its end is found: the last
`min(L, length + offset)` rows of the run without the trailing `offset` rows,
the same rows `append_run` + `dropExcessRows` + `dropOffsetRows` keep for a
one-slice window. Such groups are now staged into `pending` directly, and
`appendToPending` extends the last pending slice when the new rows continue
it in the same chunk, so the one-row groups of a chunk become one slice.
`generate()` produces the same chunk for a merged slice (same rows, first
start and last end). Groups touching a chunk boundary still use the window.

Evidence that this path is what moves the `negative_limit_by_in_order`
queries #0, #1 and ClickHouse#8 (millions of groups): ClickHouse#125000, which changed only the
allocator of these deques, moved them by -19/-16/-17% on master d3ee313 while
#2-ClickHouse#7 stayed flat; and the ClickHouse#125013 perf job's prewarm counters for #0 show
equal instructions on both sides (10301M vs 10333M, ~1030 per group) and +15%
cycles on one build.

Local A/B (release build, `CMAKE_BUILD_TYPE=None`, no ThinLTO, the perf
test's tables and queries, 12 rotating rounds, geomean of per-round ratios
new/base with bootstrap 95% CI):

  #0 10M one-row groups      0.764 s -> 0.096 s  0.123 [0.113, 0.135]
  #1 1M groups of 10         0.098 s -> 0.049 s  0.457 [0.413, 0.510]
  #2 100k groups of 100      0.025 s -> 0.019 s  0.707 [0.642, 0.785]
  #3-ClickHouse#7 100 groups           0.86-1.03, no CI lower bound above 1.0 (4-15 ms)
  ClickHouse#8 5M two-key groups       0.447 s -> 0.116 s  0.250 [0.236, 0.265]

User-space instructions of 5 runs of #0: 60.3G -> 10.2G (~1190 -> ~190 per
group after subtracting 5 runs of #3), cycles 16.2G -> 3.1G; ClickHouse#8: 31.4G ->
6.4G instructions. In the base profile of #0 about half of the samples are
in the deque allocation, `shrink_to_fit`, `CurrentMemoryTracker` and
jemalloc; none of them is in the top 15 after the change.

Replacing only `window = {}` by `clear()` (keeps the deque blocks) gives
0.526 / 0.594 / 0.583 on #0 / #1 / ClickHouse#8, so the direct staging is 4.3x and
2.3x faster than that on #0 and ClickHouse#8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 15, 2026
…ersion

`convertNumericGeneral` checked `isFinite` and could throw for every row. Look for NaN and Inf in a separate
pass without a branch, and convert in a loop without a check, unless the values become NULL
(`accurateCastOrNull`). The conversion loop stays scalar: a value outside of the range of the result type is
converted differently by vector instructions, so the result of a row would depend on its position.
`intDiv` #2 (`toUInt32` of `Float64`) is 1.11 to 1.12 times slower on x86-64 in the performance comparison of
clang 23; with this change it is 25% faster than before locally.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117346&sha=3dd3995a5ef4e0b7c19340ffe509331cf3e91827&name_0=PR
ClickHouse#117346

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 16, 2026
The collation sort (#2, 5M rows) and the single-column string sort (#3,
20M rows) take 1.2-1.9 s on MasterCI on both arches. They get
disabled="1" (text and number unchanged) and are appended as ClickHouse#9 and ClickHouse#10
on a quarter of the rows with max_block_size = 16384, a quarter of the
default 65409. `numbers_mt` hands out blocks of exactly max_block_size
rows, so each copy has as many blocks as its original (77 and 306): the
same number of cursors in every per-stream merge and the same 16-stream
final merge, with a quarter of the rows per block. EXPLAIN PIPELINE of
each original and its copy is identical (16 streams).

Measured on official MasterCI release builds, two servers pinned to 24
cores of one NUMA node, perf.py, 25 runs: copy / original time 0.248
(#2) and 0.252 (#3), projected CI medians 380 / 487 ms amd, 298 / 483 ms
arm. On the builds before/after ClickHouse#115869 (sorted array of cursors) #2 is
1.161x faster and its copy 1.159x; on those before/after ClickHouse#126829
(cheaper collation) 2.179x and 2.111x; #3 and its copy show no change
on either pair (1.005 / 1.008, 1.004 / 1.001), as the heap guard should.

#0 and #1 stay as they are: on this rig the ClickHouse#115869 change did not show
on them beyond the A/A resolution, so there was no measured guarantee
that copies would keep their sensitivity.

About 32 s (amd) and 29 s (arm) of query time less per master
performance job; 9 queries stay enabled, so all of them still run.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 20, 2026
`writeRowEndDelimiter` and the other delimiters wrote two pieces, so the
first `writeSlow` call was not a tail call and the functions needed a stack
frame; with PAC on AArch64 that is a signed return address per row.

Graviton4, PAC + BTI build, `json_key_formatting` before -> after: #0
0.526 s -> 0.498 s, #1 0.529 s -> 0.498 s, #2 0.968 s -> 0.936 s; CI master
without branch protection: 0.495 s, 0.498 s, 0.916 s. Output of all
`JSONEachRow`-family formats is unchanged, with and without pretty printing
and `output_format_json_array_of_rows`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130510&sha=latest&name_0=PR
ClickHouse#130510

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 21, 2026
`read_from_comp_parts` query #2 (`ignore(c1, s1, c3)`) was 14.6% slower on arm, confirmed after a server restart:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131707&sha=f1a4ccd2a6c93aa89b07ed36c163adb00a795587&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%205%2F8)
PR: ClickHouse#131707

It was not noise. `ReadBufferFromFileDescriptorReadBytes` grew from 1.6 GB to 2.2 GB, and the number of reads from 12272 to 18171.
`estimateMarkRangeBytesOneColumn`, which was used before for every column, extends the span of a column to its end in the
next stripe when its mark there is in the middle of a compressed block (see `getRightOffsetOneColumn`). This happens
when substreams share a compressed block, like `String` and `Array` columns in that table. The stripe walk ended every
column in its own stripe. That gave a buffer of about 165 KB instead of about 585 KB, so the reader refilled the buffer
more often and read the skipped columns between the read ones again.

The walk now extends the span in the same way. It costs one more `getMark` per column and stripe, and one more stripe-end
search per stripe, only when some column continues into the next stripe. Locally, on a 10M-row copy of the perf table,
the maximum is now the same as master's for every stream: 80 streams of that table, `05768_compact_part_read_buffer_per_column`,
the `compact_part_subcolumns` tables, and parts with `Nullable`, `LowCardinality`, `Tuple`, `JSON`, several mark ranges and
`compress_per_column_in_compact_parts = 0`. The query reads 323 MB in 2495 reads, as on master (the PR read 440 MB in 3649).
`SELECT data.a0 FROM t_json_2 SETTINGS max_threads = 1` takes 0.92 s, against 2.2 s on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 22, 2026
…n-order-one-thread

Run queries #0-#2 of the `aggregation_in_order` performance test in one thread
alexey-milovidov pushed a commit that referenced this pull request Nov 23, 2026
The two queries of the test (2-15 ms) wait on the server's embedded Keeper.
Its request and response threads poll their queues (BusyWaitBackoff):
100 us sleeps while busy, backing off to dispatch_busy_wait_long_sleep_us
(10 ms) after ~5-8 ms of idleness (ClickHouse#109255). perf.py alternates the server
order (L,R / R,L), so each server's runs alternate between a polling Keeper
(it ran right before: #0 ~5 ms) and a backed-off one (it waited through the
other server's query: #0 ~18 ms). The median lands between the two modes
(in-run CV 47-77% on master CI). perf.py's stop-condition checks before
runs 8, 10, 14 and 20 all precede reference-first runs, which is why on
master CI (two consecutive master builds) the candidate measured 8-20%
faster than the reference.

Disable #0 and #1 (they keep their numbers and history) and append the same
scans run 128 (#2) and 512 (#3) times in one query with loop(view(...)).
LoopSource plans the inner query and builds its pipeline on every pass, so
every pass goes to Keeper again (12800 and 512 ZooKeeperMultiRead per
query); passes 2..N find the Keeper polling, so the wake-up is paid at most
once per query (up to ~20 ms of a 0.5-1 s query).

Validated on CI's amd layout (8 CPUs, one hyperthread per physical core,
max_threads 8, an embedded Keeper per server, master a2126db on both
sides) with CI's stat_threshold method, 10 accepted invocations:
- #2: stat_threshold 0.080-0.119, median |diff| 0.037, in-run CV 6.3%.
  In one invocation |diff| was 0.105, above the 0.10 bar I set for it but
  below its stat_threshold 0.114, so the report would not show it.
- #3: stat_threshold 0.009-0.084, max |diff| 0.066, in-run CV 2.8%.
- Old #0 in the same session: stat_threshold 0.568-0.724, CV 56%; old #1
  0.712-1.127, CV 82%.
- Ratio of the second to the first server position: #2 1.025, #3 1.021,
  old #0 4.07. With dispatch_busy_wait_long_sleep_us=100 the old #0 ratio
  drops from 3.0-4.6 to 0.85-0.96.
- Before ClickHouse#122223 (f0e4854 vs 63c4b93) #2 is 8.2x and #3 19.2x slower
  (#3: 51200 vs 512 multi-reads), so both still measure that change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 23, 2026
`interleave(disable)` made the check-free loop scalar on aarch64 for every
float to integer pair, and `intDiv` #2 (`toUInt32` of `Float64`) became 24%
slower in the arm performance comparison of this PR.

Revert it. Only `Float64` to `Int32`/`UInt32` is inconsistent on aarch64: the
vector conversion goes through 64-bit lanes and keeps the low 32 bits, while
the scalar `fcvtzs w`/`fcvtzu w` saturates. That pair gets its own loop that
clamps the value to the range of the result type before converting, which
gives the scalar result for every finite value and lets the loop vectorizer
use `fmaxnm`/`fminnm` + `fcvtz[su] v.2d` + `xtn`. The same-width pairs keep
the code of master: their vector and scalar instructions saturate alike.

On the aarch64 cross build, toInt32/toUInt32/CAST/Nullable of 1019 values
(out of range both ways, the bounds, fractions, -0.0) give the same results
as the scalar build of the previous commit and as the CI binary of 58726cc,
the first parent of ClickHouse#117346. llvm-mca for neoverse-v2 (the m8g runners of the
arm performance comparison): 0.75 cycles per row, as master; the scalar loop
took 2.0. The x86-64 code is that of master.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=133517&sha=53c88db4bb8b09904e64fcd797dcf581fd9f5706&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F6%29
PR: ClickHouse#133517

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants