Skip to content

Reduce cache misses and instructions in aggregation and scan hot paths - #119047

Draft
thevar1able wants to merge 30 commits into
masterfrom
autoresearch-cache-locality
Draft

thevar1able wants to merge 30 commits into
masterfrom
autoresearch-cache-locality

Conversation

@thevar1able

@thevar1able thevar1able commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

A set of small, independently measured changes to the aggregation, scan, decompression and join runtime filter hot paths, found with a perf-counter driven loop over the 43 ClickBench queries and the 22 TPC-H SF10 queries (retired instructions, cycles, L1d demand misses, L2 misses per query; interleaved A/B runs against archived binaries). Each change was kept only when the counters improved and the query outputs stayed identical (up to the known non-deterministic tie sets in ORDER BY count() LIMIT queries, which also differ between two runs of the baseline).

Aggregation:

  • SerializationString: appendStringSizesToColumnStringOffsets resizes once and runs a 64-bit prefix sum with a carry flag instead of a 128-bit add and a push_back per element. Instructions -0.7%.
  • Aggregator::mergeBucketImpl: the destination table is reserved once from the insert rate observed on the first merged source instead of growing by doubling. Q34/Q35 wall time -8%.
  • ColumnString::batchSerializeValueIntoMemory and the IColumnHelper variants keep the pointer array and offsets in __restrict locals. Instructions -0.9%, Q17/Q18/Q19 -4..-6%.
  • Adaptive aggregation: the five parallel per-miss arrays become one 16- or 24-byte record, so the grouped publish touches one cache line per record instead of four (L1d demand misses -3%); staged batches from 8K records are enqueued for the drain as they are instead of being coalesced (Q19 -13%, Q17 -11.5%); the merge tables are reserved for the estimate itself instead of with a 1.25 headroom that pushed most buckets over the next power of two (Q19 -18%); the seal-level count dedup bypasses after one unproductive pass (Q17 -3.4%, Q19 -2.7% instructions).
  • HashTableGrowerWithPrecalculation gets a max_fill_eighths parameter (default unchanged at 4/8); TwoLevelHashTableGrower fills to 5/8, 20% fewer cells to zero on average. ClickBench time -2.0%, Q05 uniqExact(UserID) -20% L1d misses.
  • GROUP BY ... ORDER BY count() DESC LIMIT n: each merged bucket carries an AdaptiveBucketCountTopK fed by the count drain and the simple-count bucket merge, so the bucket-local top-K conversion looks up the k winners instead of scanning every cell of the merged bucket (14.7% of Q19's cycles before). Used for k <= 64, descending ranking, fixed-size and serialized keys; the scan runs as before otherwise. ClickBench time -3.4% (Q19 -15%, Q17 -11%). For the buckets ranked by scan, the states of the adaptive merge arena are ranked in memory order through Arena::forEachChunk instead of in hash order (Q33 cycles -15%).
  • HashMethodSerialized: the serialized_keys array is dropped; each key view is derived from the batch serialization end cursors. Q18 wall time -11%.

Scan and expressions:

  • ColumnString::filter computes the exact result chars size in one pass and reserves it, instead of a proportional estimate that is far off when the filter correlates with the string length (Q13: 2.8% of cycles in large_ralloc).
  • FixedString(N) = constant with a shorter constant pads the constant to N once and compares rows at equal width, a single masked 16-byte compare for N < 16. TPC-H Q10 -3.7% instructions.
  • The wrap-around Decimal operators +=, -=, *= and addOverflow are defined inline; /= and %= stay out of line and UBSan-instrumented. TPC-H Q01 -4.7% time.
  • The zstd decoder sources are built with -fno-unroll-loops, -fno-jump-tables and -fomit-frame-pointer (the compressor is unchanged: it does not benefit). ZSTD_decompressSequences retires more than half of all instructions of a warm pass; the flags remove the mostly-remainder unrolled copies and a spill of the bit container on the critical path. TPC-H SF10 instructions -8.5%, time -4.3%; ClickBench instructions -6.4%, time -1.8%.

Join runtime filters (TPC-H SF10: wall time -8%, instructions -11%; Q21 -21%, Q04 -18%; ClickBench has no joins):

  • 1/2/4/8-byte keys are hashed with a 64-bit multiply-xorshift mixer instead of two CityHash64WithSeed calls; the second hash is the first times an odd constant. Longer keys keep CityHash. The choice depends only on the key length, so build and probe side agree.
  • RuntimeBloomFilter replaces BloomFilter for the runtime filters: all k bits of a key live in one cache-line block selected by the first hash, at nine-bit positions read from the second hash (and, for k > 7, from one more mixing of it, so the whole 1..10 range of join_runtime_bloom_filter_hash_functions is honored). One cache line per probe, no division. BloomFilter itself only gains a mask fast path for power-of-two sizes with identical bit positions.

Allocation clean-ups, neutral on time, about 25% fewer small allocations per query: per-thread scratch containers and queues for ExecutingGraph::updateNode (the queues are released again after an update that readied more than 1024 processors, so a wide fan-out does not pin its peak allocation for the query), the MergeTreeSource tracing span name formatted once instead of per chunk, and no per-block copy of inputs_pos or the consumed vector in ExpressionActions::executeOnColumns.

All measurements: Ryzen 9 9950X3D (Zen 5), 32 threads, warm data, default ZSTD(3) codec, min of 2 interleaved rounds against the unmodified baseline, per-change numbers in the commit messages.

Changelog category (leave one):

  • Performance Improvement

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

Reduced instruction count and cache misses in GROUP BY hot paths (string offsets deserialization, pre-sized two-level bucket merging, batch key serialization, adaptive aggregation staging records and merge table sizing, a tracked top-K for ORDER BY count() DESC LIMIT n), in FixedString comparison with a shorter constant, in Decimal sums, in zstd decompression (the decoder is built without loop unrolling and jump tables and with the frame pointer omitted), and in join runtime filters (a cheaper hash for integer keys and a cache-line-blocked bloom filter). On ClickBench this gives about 2% lower wall time and 4% fewer L1d cache misses overall, up to 18% on individual queries; on TPC-H SF10 about 8% lower wall time from the runtime filter changes alone, up to 21% on individual queries.

🤖 Generated with Claude Code


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

Changes found with a perf-counter driven loop over the 43 ClickBench queries
(instructions, L1d demand misses, L2 misses per query, interleaved A/B against
archived binaries). Each change was kept only when the counters improved and the
query outputs stayed identical.

- `SerializationString`: `appendStringSizesToColumnStringOffsets` resizes once
  and runs a 64-bit prefix sum with a carry flag instead of a 128-bit add and a
  `push_back` per element. Instructions -0.7%.
- `Aggregator::mergeBucketImpl`: reserve the destination table once from the
  insert rate observed on the first merged source, instead of growing by
  doubling while the sources are merged in (same scheme as
  `drainAdaptiveBucketBacklog`). Q34/Q35 wall time -8%.
- `ColumnString::batchSerializeValueIntoMemory` and the `IColumnHelper`
  variants: keep the pointer array and offsets in `__restrict` locals so the
  loop does not reload them after every `char *` store. Instructions -0.9%.
- Adaptive aggregation: the five parallel per-miss arrays become one record
  (16 bytes for fixed-size keys, 24 for byte-staged keys), the bucket is derived
  from the hash. The grouped publish then touches one cache line per record
  instead of four. L1d demand misses -3%.
- `HashMethodSerialized`: drop the `serialized_keys` array and derive each key
  view from the serialization end cursors. Q18 wall time -11%.
- Allocation clean-ups, neutral on time, about 25% fewer small allocations per
  query: per-thread scratch and queues for `ExecutingGraph::updateNode`, the
  `MergeTreeSource` tracing span name formatted once, and no per-block copy of
  `inputs_pos` or `consumed` vector in `ExpressionActions::executeOnColumns`.

ClickBench, 43 queries, warm, Ryzen 9 9950X3D, min of 2 interleaved rounds:
wall time -1.9%, instructions -2.7%, cycles -2.7%, L1d demand misses -4.2%,
L2 misses -2.7%.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d719b47]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Received signal 6 (internal) (STID: 3593-560a) FAIL cidb

AI Review

Summary

This PR bundles a large set of measured hot-path optimizations across aggregation, string handling, zstd decompression, and join runtime filters. Most of the performance-oriented rewrites look internally consistent, but there are still two unresolved contract breaks around retained executor scratch memory and the runtime-filter size setting, so this should not merge as-is.

Findings

⚠️ Majors

  • src/Processors/Executors/Runtime/ExecutingGraph.h:133, src/Processors/Executors/Runtime/ExecutingGraph.cpp:324 updateNode now keeps updated_edges, updated_processors, and pending_expansion alive for the whole query and only clear()s them after each traversal. One wide fan-out can therefore retain O(pipeline size) scratch capacity on every worker that hits it for the rest of the query, carrying that memory into later aggregation/sort phases and potentially forcing earlier spill or MEMORY_LIMIT_EXCEEDED. Suggested fix: apply the same post-burst reset/cap logic as the queue buffers, or keep oversized traversals call-local instead of query-long.
  • src/Processors/QueryPlan/RuntimeFilterLookup.cpp:212 RuntimeBloomFilter no longer honors join_runtime_bloom_filter_bytes below one 64-byte block. With requested_blocks = max(1, bytes / 64), settings 1..63 all allocate 64 bytes, so the actual filter can exceed the configured size and existing queries silently get different setting semantics than before. Suggested fix: reject < 64 at the planning/setting boundary and document the new granularity, or preserve the old exact-size behavior for small filters.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Bound or shrink update_node_scratch after oversized updateNode traversals.
    • Restore a consistent join_runtime_bloom_filter_bytes contract for sub-64-byte values, or reject and document those values explicitly.

LLVM Coverage Report

Measured on commit d719b47.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 677/709 (95.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 9, 2026
`convertOneBucketToChunkTopK` ranks the groups of a two-level bucket by their count, which lives in
the aggregate state row. The table walk visits the states in hash order: one random cache line per
group from a region far larger than the caches, with too little work per group to overlap the
misses, so the pass runs at the DRAM random-access rate. Software prefetch does not help (the loop
already has memory-level parallelism; the limit is the random-access throughput).

In the adaptive merge, the bucket's drained states are rows of one size and alignment in the
bucket's own arena (`adaptive_merge_bucket_arenas`), in insertion order, and for fixed-size keys
without arena-allocating aggregates nothing else lives there. The ranking now reads those rows in
memory order (sequential, hardware-prefetched) through the new `Arena::forEachChunk`, and walks
the cells once more only to attach the keys of the few winners (sorted pointers with an address
envelope prefilter) and to rank the states that live elsewhere (groups merged in from the
pre-freeze tables). If a kept row did not meet its cell, the plain ranking runs instead.

ClickBench Q33 (`GROUP BY WatchID, ClientIP ... ORDER BY count() DESC LIMIT 10`, ~100M groups):
cycles -15%, L2 misses -14%, wall time -2.3%; instructions +22% for the extra cell walk. Overall
(43 queries, 2 interleaved rounds): wall time -2.2%, cycles -7.2%, L1d demand misses -2.2%,
L2 misses -3.3%, instructions +1.5%. A deterministic top-K check (hot keys with distinct counts
among 50M singletons; fixed, two-column and string keys) gives identical results.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d719b47b1 with master 3345498c8 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

288 object files changed (+596.05 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 20.34 MiB 20.91 MiB +584.14 KiB (+2.81%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.73 MiB 5.67 MiB -59.97 KiB (-1.02%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationKernels.cpp.o 1.87 MiB 1.82 MiB -47.38 KiB (-2.48%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +835.5 s (+5%) in total before that adjustment.

Job report

…e filters

The bloom filter of a join runtime filter hashed every probed and inserted key with two
`CityHash64WithSeed` calls over its bytes and then tested three bits at random positions of a
512 KiB filter, each located with a `libdivide` modulo: three dependent cache accesses per key.

Two changes, both confined to the runtime filters, which live for one query:

- For the usual 1/2/4/8-byte integer join keys the two hashes are a 64-bit multiply-xorshift
  mixer of the key value (a few instructions per key). Longer keys keep CityHash. The choice
  depends only on the key length, so the build and probe side of a filter always agree.
- `RuntimeBloomFilter` replaces `BloomFilter` for the runtime filters: all k bits of a key live
  in one cache-line block (512 bits) selected by the first hash, at positions given by the second
  hash. A probe touches one cache line and needs no division; k = 3 is unrolled. The set-bits
  worthiness check and the OR-merge of per-thread filters work as before.

`BloomFilter` itself (also backing the persisted bloom filter indexes) only gains a mask fast path
for power-of-two sizes, which yields the same bit positions as the division.

TPC-H SF10 (22 queries, 32 threads, min of 2 interleaved rounds), cumulative for both changes:
wall time -8%, instructions -11%, cycles -10%, L1d demand misses -7%; Q21 -21%, Q04 -18%,
Q08 -13%, Q22 -12%, Q05 -11%, Q09 -10%, Q03 -5%. All 22 query results identical. ClickBench has
no joins and is unaffected.
The `+=`, `-=`, `*=` and `addOverflow` operators of `Decimal` were explicitly instantiated out of
line, so the running sums of `sum` and `avg` over decimal columns made two calls per row
(`Decimal<Int128>::addOverflow` and `operator+=` were 1.1% of all instructions on TPC-H SF10).
They are trivial and the wide integer implementation is visible wherever `Decimal.h` is, so they
are defined in the class body now. `/=` and `%=` stay out of line and UBSan-instrumented.

TPC-H SF10: Q01 -3.3% instructions, -4.7% time; suite -0.3% instructions.
`ZSTD_decompressSequences` retires 54% (ClickBench) to 58% (TPC-H SF10) of all instructions of a
warm-cache benchmark pass. On raw frames extracted from the hits `URL` and `UserID` columns, the
bundled zstd built by clang at -O3 needs 12% more instructions and 9% more cycles to decompress
than the same source built with `-fno-unroll-loops`, and matches a gcc -O2 build only with the
flag: the per-sequence copies are short, so the unrolled bodies mostly run their remainders.
Compression does not benefit from the flag (+2.5..3.8% instructions), so only the decoder
sources get it.

TPC-H SF10 (22 queries, 32 threads, min of 2 interleaved rounds): instructions -8.5%, cycles
-6.2%, wall time -4.3% (Q06 -12%, Q01 -11%, Q15 -8%). ClickBench (43 queries): instructions
-6.4%, cycles -2.6%, wall time -1.8% (Q23 -11%). All query results identical.
`stageChunk` coalesced every staged batch below half the 4 MiB seal target into one chunk before
it reached the backlogs, copying all of its records. With 65K-row blocks a batch of fixed-size
keys is about 1.3 MB, so a seal merged only three batches for the copy of every record: on TPC-H
SF10 Q18 the seal copies were 12% of the cycles. A batch that already holds 32K records gives the
drain slices of 128 records per bucket on average, which is long enough, so it is enqueued as is.

TPC-H SF10: Q18 -19% time, Q13 -6%, suite -2.5% time, -2.5% L2 misses. ClickBench: Q33 -10%
time, suite -2.8% time, -1.5% L1d misses; instructions unchanged. Q18 SF10 sealed chunks 308 -> 32.
For fixed-size join keys the second hash of the runtime bloom filter was a second full `mix64` of
the key. The blocked filter only needs its bit positions to be independent of the block index,
which the low bits of the first hash select, so the second hash is now the first hash times an odd
constant and the positions are read from the high bits of the product, which mix all bits of the
multiplicand.

TPC-H SF10: -0.5% instructions (Q21/Q22/Q04 -2.3%), time and L2 misses unchanged in two rounds,
runtime filter pass ratios identical (Q21 0.115, Q22 0.129, Q04 0.076).
thevar1able and others added 4 commits September 10, 2026 00:09
`FixedString(N) = constant` with a constant shorter than N compared every row with the generic
zero-padded routine, which walks the common prefix and then the tail of the longer operand per
row. The constant is now zero-padded to N once, so the rows are compared at equal width, and a
width below 16 bytes is a single masked 16-byte compare per row. The result is the same: a
fixed string equals a shorter constant exactly when it equals the constant padded with zero
bytes to its width.

TPC-H SF10: Q10 -3.7% instructions (`l_returnflag = 'R'`), Q19 -2.5%, Q02 -1.3%; suite -0.5%.
On top of `-fno-unroll-loops`, `-fno-jump-tables` for the zstd decoder sources takes another
0.4% of all instructions off a warm ClickBench and TPC-H SF10 pass (stable to 0.1% across
rounds), with wall time flat to -0.9%. On raw frames extracted from the hits `URL` column the
standalone decoder retires 1.3% fewer instructions with the flag.
When count-only staging batches are coalesced, the seal deduplicates keys repeating across
the buffered batches before copying them. Such repeats are rare by construction (a repeat of a
key the thread has already seen usually hits its frozen local table), and a producer thread
seals only a handful of times per query, so with the bypass threshold of four unproductive
passes the dedup ran on nearly every seal while merging nothing: on ClickBench Q13 and Q19 it
merged 0 of 7.3M and 57.8M records at 3-5% of the instructions. The seal dedup now bypasses
after one unproductive pass; the periodic resample re-engages it if the distribution changes.
The publish-level dedup keeps its threshold.

ClickBench: instructions -0.5% (Q17 -3.4%, Q19 -2.7%), wall time -1.3%. TPC-H SF10 unchanged.
Results identical up to tie order in count-ordered LIMIT queries.
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Sep 9, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
thevar1able and others added 10 commits September 10, 2026 20:16
The sequence decoding loop in `ZSTD_decompressSequences` keeps more live
values than x86-64 has registers (bit stream state, three FSE states and
their tables, the repeat offsets, output and literal cursors). With a
frame pointer the bit container is spilled to the stack and reloaded by
the `shlx` that extracts the next bits, on the critical path of the bit
reads; the FSE table pointers are reloaded from the stack per sequence.

Giving the decoder the frame pointer register removes that spill.
Standalone decode of extracted ClickBench frames: -17% cycles on the
64-bit integer column, -3.5% on URLs, -0.5% instructions. In the server
(2 interleaved A/B rounds each): ClickBench time -1.6%, instructions
-1.6%; TPC-H SF10 time -2.3%, instructions -2.0%, every query faster or
flat. Outputs and full-table checksums are identical.

This is a no-op for toolchains that already omit the frame pointer at
-O3 (the ClickHouse CMake never asks to keep it unless
`DISABLE_OMIT_FRAME_POINTER` is set); some distribution toolchains keep
it by default, and the decoder is the one place where that costs
measurable time. Stack traces still work through `.eh_frame`.
The drain of the adaptive aggregation backlog samples the insert rate on
the first eighth of a bucket's records and reserves the bucket's hash
table for the extrapolated number of new keys, times a 1.25 headroom.
The grower then rounds that up to a power of two at most half full. On a
near-distinct stream (ClickBench Q19: 56.4M groups from 56.1M records)
the headroom pushed most buckets over the next power of two, so the
merge tables ended up about 25% full: roughly 8.6 GB of cells zeroed for
1.8 GB of live cells, and `memset` from `HashTable::resize` was 18% of
the query's cycles, bound by DRAM bandwidth with all drains zeroing at
once.

Reserve for the estimate itself. An estimate that lands just under a
power-of-two boundary costs one late resize, which is cheaper on average
than doubling every table. Two interleaved A/B rounds each: ClickBench
time -4.3% (Q19 -18%, cycles -19%, L1d misses -14%), TPC-H SF10 time
-2.7%. Outputs identical apart from the known tie queries.
`HashTableGrowerWithPrecalculation` gets a `max_fill_eighths` parameter
(default 4, i.e. the previous 0.5 load factor) and `set` now picks the
smallest size whose maximum fill holds the requested number of elements,
which is unchanged for the default. `TwoLevelHashTableGrower` uses 5/8.

A bucket table is zeroed in full when it is created or resized, and the
drain of the adaptive aggregation reserves each bucket for its final
size in one go; on a mostly distinct stream that zeroing is bound by
DRAM bandwidth with all drains zeroing at once. The higher fill trades a
slightly longer probe for 20% fewer cells on average. Two interleaved
A/B rounds each: ClickBench time -2.0%, cycles -3.3%, L1d demand misses
-1.7% (Q05 `uniqExact(UserID)` -20%); TPC-H SF10 time -0.4%, cycles
-0.9%. Outputs identical apart from the known tie queries.
A staged batch with at least `adaptive_seal_direct_records` records is
enqueued for the drain without coalescing. The threshold was 32K (128
records per bucket); the batches ClickBench Q19 produces hold about 12K
records, so every one of them was copied (keys, hashes and payload) into
a coalesced chunk, and that copy was 10% of the query's cycles, for
bucket slices the drain no longer benefits from.

Lower the threshold to 8K records (32 per bucket). Two interleaved A/B
rounds each: ClickBench time -3.3% (Q19 -13%, Q17 -11.5%, Q13 -7%),
cycles -4.5%, L1d demand misses -3.0%; TPC-H SF10 -0.4%. Outputs
identical apart from the known tie queries.
`filterArraysImpl` sizes the result chars in proportion to the expected
share of rows. That is far off when the filter correlates with the
string length: `SearchPhrase <> ''` keeps a quarter of the rows, and
those rows hold nearly all the bytes, so the chars buffer doubled
repeatedly through reallocations that copy everything written so far
(2.8% of ClickBench Q13's cycles in `large_ralloc`).

`ColumnString::filter` now computes the exact result size in one pass
over the offsets and the filter and reserves it before filtering. Two
interleaved A/B rounds each: ClickBench L1d demand misses -1.9%, L2
misses -1.7%, time -0.7% (Q13 L1d -10.6%, Q26 -4.9%); TPC-H SF10 time
-2.3%, L2 misses -1.7%. Outputs identical apart from the known tie
queries.
The bucket-local Top-K conversion of a plain `count()` aggregation
ranked every cell of the merged bucket to find its k best groups. With
the adaptive merge the bucket tables are large and only 30-60% full, so
the scan was a bandwidth-bound walk over gigabytes of cells: 14.7% of
ClickBench Q19's cycles, and the same shape in every
`GROUP BY ... ORDER BY count() DESC LIMIT n` query.

Counts only grow, and only two paths change them once a bucket is being
merged: the count drain and the simple-count bucket merge. Each merged
bucket now carries an `AdaptiveBucketCountTopK`, seeded from the
destination's pre-aggregated bucket, told every new count by those two
paths (one compare per record against the smallest tracked count, a
slow path only when a count exceeds it), and consulted by the
conversion, which looks up the k winners and skips the scan. The tracker
keeps the staged byte image of the key plus the table hash and reuses
`emplaceStagedKey` (moved to `AdaptiveAggregationImpl.h`) for the
lookup. It is not used, and the scan runs as before, for k > 64 (the
linear candidate search would cost O(k) per record: a `LIMIT 10 OFFSET
1000` query lost 64% instructions before the cap), for ascending
ranking, for the string hash map (no cell iteration), for the null-key
and low-cardinality shapes and for set methods.

Two interleaved A/B rounds each: ClickBench time -3.4% (Q19 -15%, Q17
-11%, Q15 -8%, Q13 and Q16 -6%), instructions -2.1%, cycles -3.6%, L2
misses -3.7%; TPC-H SF10 unchanged. The top-10 counts of every
count-ranked ClickBench query are identical to the scan's, TPC-H outputs
are identical, and ClickBench differs only in the known tie queries.
…locality

# Conflicts:
#	src/Processors/QueryPlan/RuntimeFilterLookup.cpp
#	src/Processors/QueryPlan/RuntimeFilterLookup.h
Two errors from the `arm_tidy` build:
- `hashFixedSizeColumn` returned the result of a `void` call from a `void`
  function (`readability-avoid-return-with-void-value`).
- `Candidate` in the bucket top-K ranking of `Aggregator` left `value` and
  `mapped` without initializers (`cppcoreguidelines-pro-type-member-init`).

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119047&sha=a426c7641dda1cab986f294854aee0997ed0efb8&name_0=PR&name_1=Build%20%28arm_tidy%29
PR: #119047

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Address review: the per-thread `update_node_queue` and `update_node_async_queue`
kept their capacity for the whole query, so one update that readied many
processors pinned that peak allocation on the worker for later, memory-heavy
phases. The queues are still reused between steps (a typical update readies a
handful of processors, and keeping that much saves an allocation per step), but
after an update whose burst exceeded 1024 processors they are released.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Address review: `RuntimeBloomFilter` silently clamped
`join_runtime_bloom_filter_hash_functions` to 7, while
`BuildRuntimeFilterStep` accepts values up to 10, so a query configured with
8..10 got a different filter than it asked for and than the sizing heuristics
assumed. The second hash holds seven nine-bit positions; the positions past the
seventh now come from one more mixing of it, so the filter supports up to 14
hash functions, and the constructor throws a logical error outside 1..14
instead of clamping.

A test runs the filter with 1, 3, 7, 8 and 10 hash functions on a fixed-size
and on a string key.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
thevar1able and others added 4 commits September 11, 2026 18:07
Address review: `RuntimeBloomFilter` rounded the requested size up to a power
of two, so `join_runtime_bloom_filter_bytes` set to, say, 3 MiB gave a 4 MiB
filter, and the set-bits ratio was measured over the rounded size. The budget
is now rounded down, never exceeded, and the statistics-based size is rounded
up to a power of two before it is clamped to its maximum (itself a power of
two), so the filter sized from the hash table statistics loses nothing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…filter`

Address review: the pass that computes the exact result size read the filter
for every row of the column before `filterArraysImpl` checked that the two
sizes match, so a filter shorter than the column was read past its end before
the `SIZES_OF_COLUMNS_DOESNT_MATCH` exception. The check now runs first.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Address review: the tracked simple-count merge skipped the tracker when a
`parallel_worker` was given but left it marked complete, so a caller combining
the two would have had the conversion trust a tracker that missed counts. No
caller does that today (`mergeBucketImpl` passes no worker); the tracker is
now marked incomplete on that path, and the conversion falls back to the scan.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
/// Work containers of `updateNode`. The traversal grows them on every call, so a caller keeps
/// one instance per executing thread and passes it in: the containers then keep their
/// capacity across calls instead of being allocated anew for every prepared processor.
struct UpdateNodeScratch

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This lifetime change still leaves the new update_node_scratch buffers query-long with no shrink/cap path. A single wide updateNode can grow updated_edges, updated_processors, and pending_expansion to O(pipeline size), and unlike the sibling queues those containers are only clear()ed in updateNode and never reset after the burst.

That means one wide fan-out can still leave each worker that hit it carrying its peak scratch capacity into later memory-heavy phases for the rest of the query. It is also a weaker failure mode than the queue case, because these containers use the default allocators rather than AllocatorWithMemoryTracking, so the retained peak is not charged through the tracked queue path you just fixed.

I think this needs the same "drop oversized capacity after the burst" treatment as the queues, or to keep only a bounded small scratch persistent and allocate oversized traversals call-locally.

…ument` under the direct-publish bar

The test asserts that the adaptive aggregation seal coalesced at least one
chunk (`AdaptiveAggregationSealedChunks`). Since a batch with at least
`adaptive_seal_direct_records` (8K) records is published as-is, the
coalescing is skipped for every batch the test produced: the join squashes
its output up to `min_joined_block_size_rows` (65409 by default), so the
aggregation received 40K-80K row blocks, and `sealed chunks` read 0 on every
stateless configuration.

Turn the join output squashing off and read one 2048-row granule per block,
so a joined block holds 2048 or 6144 rows and every staged batch is
coalesced. The `normalized` assertion still holds (25 normalizations per
query), and the checksums are unchanged.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119047&sha=f6a78f450530f301394952e1a2d37e11385f134a&name_0=PR
PR: #119047
`NgramDistanceImpl` refills a 19-byte (UTF-8: 72-byte) code point array
on the stack with one 16-byte store and reads it back with 4-byte loads
at every offset. When the array crosses a 4 KiB page boundary the split
store is not forwarded to the loads that follow it, and the function
runs the same instructions 25% slower.

The CI perf run of this PR hit exactly that: the executor frame got
64 bytes smaller (the update-node queues moved off the stack), every
executor thread's stack shifted, and `cp` in `executeImpl` landed on
`0xFF0..0x1002` of the page. `ngramDistance` on `hits_10m_single` took
+97% (amd CI) / +25% (local, 16 threads), 0% with `max_threads = 1`,
where the call chain differs. `perf stat`: identical instructions,
branches and cache misses, +10% L1d loads, +26% cycles.

Align the array to its size rounded up to a power of two (32 bytes for
ASCII, 128 for UTF-8): it then never crosses a power-of-two boundary,
whatever the callers' frame sizes are.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119047&sha=f6a78f450530f301394952e1a2d37e11385f134a&name_0=PR
PR: #119047
…e and read narrowly

Same shape as the n-gram code point array: the string key union of
`StringHashTable::dispatch` takes a 16-byte `memcpy` for 17-24 byte keys
and is then read as 8-byte words by `hash_of`, and `readUUIDTextImpl`
copies 32 bytes into `char s[36]` and parses it byte by byte. Neither
could forward the store to its loads if the buffer happened to straddle
a page. Both were reviewed among 13 candidates found by a codebase
search; the rest either have mismatched store and load widths that never
forward regardless of placement, live in registers, or are cold paths.

PR: #119047
…locality

# Conflicts:
#	src/Processors/Executors/Runtime/ExecutingGraph.cpp
#	src/Processors/Executors/Runtime/ExecutingGraph.h
#	src/Processors/Executors/Runtime/PipelineExecutor.cpp
/// A power of two number of blocks: the block is selected by masking the first hash. `bytes` is a
/// budget (`join_runtime_bloom_filter_bytes`, or the statistics-based size, which is already a
/// power of two), so it is rounded down, never exceeded.
const size_t requested_blocks = std::max<size_t>(1, bytes / (RUNTIME_BLOOM_BLOCK_WORDS * sizeof(UInt64)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes the contract of join_runtime_bloom_filter_bytes for values below one blocked-filter chunk. With requested_blocks = max(1, bytes / 64), every setting from 1 to 63 now allocates 1 * 8 * sizeof(UInt64) = 64 bytes here, so the runtime filter can exceed the configured size and existing tiny-filter queries silently get a different setting semantics than before.

I think this needs either a validation step that rejects < 64 (and documents the new granularity), or an exact-size fallback for small filters so the user-facing join_runtime_bloom_filter_bytes contract stays intact.

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Dear @thevar1able, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant