Skip to content

Do not buffer the serialized step when computing the hash-table-stats cache key - #115847

Merged
nickitat merged 1 commit into
ClickHouse:masterfrom
groeneai:stream-hash-table-stats-cache-key
Aug 24, 2026
Merged

nickitat merged 1 commit into
ClickHouse:masterfrom
groeneai:stream-hash-table-stats-cache-key

Conversation

@groeneai

@groeneai groeneai commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

Reduced memory usage and query-plan optimization time for keyed aggregations over large constant-folded literals. The aggregation hash-table-statistics cache key is now hashed as it is serialized instead of being accumulated in memory first, so a plan carrying a large literal no longer holds a copy of it during optimization. For an 80 MB literal, peak memory drops by about 250 MB and optimization time by about 2.5x. The computed key is unchanged.

Description

Related: #113736

calculateHashFromStep buffered a step's whole serialized form, then hashed it in a second pass. That stream is hash input only, and serializeConstant writes a constant-folded literal out in full, so a large literal was copied just to be hashed and dropped. This hashes the stream as it is produced, through a small WriteBuffer feeding a SipHash over a 32 KiB window.

The key value is bit-identical to before, since SipHash::update carries state across calls including any sub-word remainder. That matters because a collision is harmless for only one of the three consumers: considerEnablingParallelReplicas uses these hashes as a node matcher across two plan builds, transplanting cached dataflow statistics on a match. Truncating the key would make different constants compare equal there.

Measured with clickhouse local on a GROUP BY over an 80 MB repeat() literal, 3 runs:

80 MB literal QueryPlanOptimizeMicroseconds peak RSS
before 176 / 179 / 175 ms 668 / 671 / 668 MB
after 68 / 70 / 73 ms 407 / 419 / 419 MB
setting off (floor) 43 / 39 / 40 ms 407 / 413 / 407 MB

Peak memory now sits at the floor. Same at 800 MB: 3460 to 1817 MB, floor 1817 MB.

The O(N) term remains: serializeBinary still walks every byte, and each aggregation node serializes its own subtree. Removing it means giving up exact key identity, which given the matcher above is the code owner's call.

A gtest asserts the streamed key equals the previously buffered key across window-boundary alignments, and fails under two deliberate perturbations of the sink. 12 real cache keys spanning constants, Array, Tuple, Nullable, LowCardinality and Decimal are unchanged.

Reported by @ egor-click.


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

Version info

  • Merged into: 26.9.1.35-master (included in 26.9 and later)

… cache key

calculateHashFromStep serialized a query-plan step into a WriteBufferFromOwnString
and then hashed the result in a second pass. That byte stream exists only as SipHash
input: nothing deserializes it, and it never leaves the process. Because
serializeConstant writes a constant-folded literal out in full, a plan carrying a
large literal allocated a copy of the whole literal, walked it again to hash it, and
dropped it. Measured on a GROUP BY over an 80 MB repeat() literal: peak RSS 668 MB
with collect_hash_table_stats_during_aggregation=1 against a 413 MB floor with it
off, and 176 ms of QueryPlanOptimizeMicroseconds against 43 ms.

Hash the stream as it is produced instead, through a WriteBuffer that feeds a SipHash
over a fixed 32 KiB window and discards the bytes. Peak RSS now lands on the
setting-off floor (407-419 MB) and the time drops to 68-73 ms, the latter because the
redundant second pass over the buffer is gone as well. Same at 800 MB: 3460 MB to
1817 MB against an 1817 MB floor.

The computed key is bit-identical to before. SipHash::update carries its state,
including any sub-word remainder, across calls, so chunked hashing yields the same
64-bit value as hashing one contiguous buffer; the window size is therefore not
observable in the result. HashingWriteBuffer could not be reused for this: its
CityHash-128 state is documented as depending on how the stream is split into blocks,
so composing it would both change the key and make it depend on buffer chunking.

Preserving exact identity is deliberate rather than incidental. These hashes have
three consumers, and only the aggregation preallocation hint treats a collision as
harmless. considerEnablingParallelReplicas uses them as a node matcher across the
single-replica and parallel-replicas plan builds, pairing nodes by hash equality and
then transplanting reading-step analysis and cached dataflow statistics onto the
matched node; optimizeJoin's RuntimeHashStatisticsContext consumes them unguarded.
Bounding or reshaping the key, as issue ClickHouse#113736 proposes, would deliberately make two
different constants compare equal there. Note also that the fingerprint the issue is
premised on does not exist at trunk: updateHashFast has no callers in ActionsDAG.cpp,
so a cap on it would be a no-op.

What this does not address: serializeBinary still walks every byte of the constant,
and setAggregationHashTableCacheKeys still serializes each aggregation's subtree
independently, so the cost remains linear in the literal and multiplied per
aggregation node. Removing that requires giving up exact key identity, which given
the matcher above is a design decision for the owners of this code.

Validated by a gtest asserting the streamed key equals the previously buffered key
across window-boundary alignments, sub-word writes and multi-window writes; it was
confirmed to fail under two deliberate perturbations of the sink. Separately, 12 real
cache keys spanning constants, Array, Tuple, Nullable, LowCardinality and Decimal
were captured before and after and are bit-identical, while remaining distinct from
each other. A separate nine-query matrix, which additionally covers Map, returns
md5-identical results. Preallocation was checked end to end, including over
serialize_query_plan=1, and the parallel-replicas matcher still pairs nodes.

Reported by Egor Romanov.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 blockers) - click to expand

Every change here was reviewed by a second model with no access to the authoring
session's notes, then adjudicated against the recorded evidence. Two rounds ran;
round 2 returned one nit and no blocker or major.

❌ Blockers

None.

⚠️ Majors

Tests do not fail if production reverts to buffering, so they do not guard the
memory and time improvement.
- DISAGREE, with evidence.

The fact is correct and I found it independently: reverting the call site alone
leaves the new gtests green. The prescribed remedy, a timing or memory-tracker
regression test, is what I decline, on three grounds:

  • The invariant a wrong answer could come from is the key value, and that is
    already guarded loudly in-tree. 04509_hash_table_sizes_stats_table_functions.sh
    pins AggregationPreallocatedElementsInHashTables to 650000/520000 across four
    pairs, for both local and serialize_query_plan=1 shard-side execution. A key
    that changed, or that collided across the two cardinalities, zeroes that event
    and fails the test.
  • A timing-shaped assertion cannot pass here even when the change is correct: the
    O(N) serialization term survives by design, so key cost stays linear in the
    literal. An oracle that can never hold is worse than none.
  • Only the memory and time win is unguarded, and tests/performance/ is its
    proper venue rather than a stateless test.

Coverage boundary, stated plainly: this PR adds no automated guard against a future
change reintroducing buffering. It does add a gtest pinning the property the whole
change rests on, that streaming produces the identical key, verified to fail under
two deliberate perturbations of the sink.

💡 Nits

  • The destructor comment reads as if finalizing were optional in general. AGREE,
    not fixed. Abandoning a half-written sink is safe, which is what the comment and
    its test are about, but a caller that wants the key must finalize first. No
    correctness impact: the one caller finalizes on the line before it reads the hash.
    Left as-is rather than spending another review round on comment wording.
  • Refuted-alternative prose about HashingWriteBuffer moved from the header to the
    commit message. Fixed.
  • A coverage claim in an earlier draft of this PR body listed Map among the types
    in the 12-key identity corpus. It is not there; Map is covered by the separate
    nine-query results-identity matrix. Corrected in both the body and the commit
    message before publication.
  • Unused include dropped from the new test. Fixed.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [652cdb2]

Summary: ✅


AI Review

Summary

Reviewed the streamed hashing change in calculateHashTableCacheKeys, the new SipHashingWriteBuffer, the added unit tests, the existing PR discussion, and the current all-green CI. I did not find a correctness, compatibility, performance-safety, or test-coverage issue that warrants an inline review comment.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local, GROUP BY over an 80 MB repeat() literal, discriminator collect_hash_table_stats_during_aggregation 1 vs 0: 176-203 ms and 668-680 MB peak RSS with the setting on, 42-49 ms and 415-419 MB with it off. Reproduces every run, and the gap scales with the literal (8 MB: ~12.9 vs ~2.9 ms; 800 MB: ~1.8 s vs ~0.74 s).
b Root cause explained? Yes. calculateHashFromStep buffered the step's whole serialized form into a WriteBufferFromOwnString and hashed it in a second pass. The stream is hash input only, and serializeConstant writes a constant-folded literal out in full, so a large literal was copied (plus realloc churn) purely to be hashed and dropped.
c Fix matches root cause? Yes. The buffering itself is removed: the stream is hashed as it is produced. No cap, no threshold, no truncated or reshaped key, no new setting, no guard at a call site.
d Test intent preserved / new tests added? Yes. No existing test changed or weakened. Three new gtests, the primary one asserting streamed key == previously buffered key.
e Both directions demonstrated? Yes. Base vs fix at 8 / 80 / 800 MB (80 MB: 176/179/175 ms and 668/671/668 MB before, 68/70/73 ms and 407/419/419 MB after, against a 407-413 MB setting-off floor). The identity gtest was also confirmed to FAIL under two deliberate perturbations of the sink (double-feed, and dropping the final partial flush).
f Fix is general across code paths? Yes. Fixed in the key builder, not at a consumer. All three consumers of these hashes verified live: aggregation preallocation (650000 elements preallocated on the second run of a constant-carrying plan), the same over serialize_query_plan=1 (650000 and 520000 on the shard, with distinct keys per size), and the parallel-replicas node matcher (80 candidate top nodes, 74 matched by hash). The two sibling calculateHashFromStep overloads hash small fixed fields directly and never buffered.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 12 real cache keys compared before/after over constants, plain and aggregate GROUP BY, filters, has(...), Array, Tuple, Nullable, LowCardinality, Decimal and a materialized constant: all 12 bit-identical and all 12 distinct. Query results over a 9-query type matrix (adding Map, uniq, groupArraySorted) are md5-identical. The gtest covers empty, sub-word (7/8/9 bytes), every window-boundary alignment, and a multi-window single write.
h Backward compatible? Yes. The key value is bit-identical, so existing cache entries and cross-plan node matching are unaffected. No setting, no default, no serialization format change, so no SettingsChangesHistory.cpp entry applies.
i Invariants and contracts preserved? Yes. Same bytes, same order, same SipHash, so the same 64-bit key. The sink is stack-local and cancels in its destructor, so a serialize that throws mid-stream discards the partial hash and the existing catch-all still skips preallocation for that aggregation (covered by a dedicated gtest). No new shared or concurrent state.

Session id: cron:clickhouse-impl-slot-41:20260821-133300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @CurtizJ, could you review this? calculateHashFromStep buffered a plan step whole serialized form into a WriteBufferFromOwnString before hashing it, so a constant-folded literal was copied just to be hashed and dropped; it now feeds a SipHash as it serializes, leaving the key bit-identical because SipHash::update carries its sub-word remainder across calls.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.52 MiB 701.50 MiB -3.02 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

@nickitat nickitat self-assigned this Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6fc7998f-f50c-4f1b-838d-94eb4a7b9065
  • MIRAI run: c183910c-674a-4b87-8305-f78af545d4e8
  • PR check IDs:
    • clickbench_27977_1787351933
    • clickbench_27983_1787351934
    • clickbench_27994_1787351933
    • tpch_adapted_1_official_28008_1787351933
    • tpch_adapted_1_official_28019_1787351933
    • tpch_adapted_1_official_28047_1787351934

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: 652cdb2

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 4/6) / test_zookeeper_locks.py::test_three_replicas_ten_partitions_rebalance ThreadSanitizer data race inside contrib/librdkafka, raised by cluster.shutdown() a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

The test body passes. helpers/cluster.py:4506 promotes a sanitizer assert found in an
instance log into an exception, and the reported race is a write to the per-toppar version
counter at contrib/librdkafka/src/rdkafka_partition.c:201 reached through
rd_kafka_toppar_fetch_stop. Every frame in the stack is inside the vendored library; no
ClickHouse frame appears. This branch changes only
src/Processors/QueryPlan/Optimizations/SipHashingWriteBuffer.h,
calculateHashTableCacheKeys.cpp and one gtest. Breadth over 30 days, keyed on the
signature and on the test name alike: 3 rows across 3 unrelated pull requests, 0 on master.

Session id: cron:our-pr-ci-monitor:20260822-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the librdkafka rd_kafka_toppar_op_version_bump TSAN data race in test_storage_kafka/test_zookeeper_locks.py (Integration tests (amd_tsan, 4/6)): ClickHouse/librdkafka#21

The race is entirely inside the vendored contrib/librdkafka, so it is not caused by this PR. rd_kafka_toppar_handle_Offset is declared Locality: toppar handler thread but reads rktp_op_version unlocked; on the __DESTROY route rd_kafka_buf_callback invokes the callback directly on a broker thread during termination, which races the bump taken under the toppar lock. Four unrelated pull requests have hit it across two tests since 2026-04-06.

The ClickHouse-side submodule bump follows once the fork PR merges.

@nickitat
nickitat enabled auto-merge August 24, 2026 14:18
@nickitat

Copy link
Copy Markdown
Member

good idea, it might also be generalized to other hash algorithms.

@nickitat
nickitat added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit 2797514 Aug 24, 2026
528 of 532 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
@snelheidai

Copy link
Copy Markdown

good idea, it might also be generalized to other hash algorithms.

It does generalize — though the win turned out to be at another call site rather than under another algorithm, and the sink needs one change to be usable there.

Where the same shape still exists

Sweeping src for a buffer materialized only to be hashed, the one column I found still doing it is ColumnAggregateFunction:

  • updateHashWithValue built a WriteBufferFromOwnString per row before SipHash — a heap allocation plus a full copy of the state for every row hashed;
  • updateHashFast did the same for a whole column at once via serializeBatch;
  • computeHashInto serializes each row into a reused vector before ::updateWeakHash32.

Dynamic, Object/JSON and Variant all recurse into their subcolumns without materializing, so they were already fine.

The per-row site needs the window on the stack

Reusing SipHashingWriteBuffer as merged would have put back the very allocation being removed: its 32 KiB BufferWithOwnMemory window is allocated per construction, and updateHashWithValue runs once per row. So the sink moved to IO/ (Columns cannot include a Processors header) and gained a stack-window variant:

template <size_t window_bytes_ = 1024>
class StackSipHashingWriteBuffer final : public WriteBuffer
{
public:
    explicit StackSipHashingWriteBuffer(SipHash & hash_) : WriteBuffer(nullptr, 0), hash(hash_)
    {
        set(window, window_bytes_, 0);
    }
    ~StackSipHashingWriteBuffer() override { cancel(); }

private:
    void nextImpl() override { hash.update(working_buffer.begin(), offset()); }

    SipHash & hash;
    char window[window_bytes_];
};

which makes the call site

StackSipHashingWriteBuffer<> wbuf(hash);
func->serialize(data[n], wbuf, version);
wbuf.finalize();

Measured

clickhouse local, master 10bec7b8810 vs the same tree plus this change, x86_64 Release/clang-21, 500k rows of AggregateFunction(groupArray, UInt64) at ~320 B per state, 9 paired interleaved repetitions with alternating arm order, median of ClickHouse's own query time:

query before after
SELECT count() FROM (SELECT DISTINCT s FROM st) 0.363 s 0.247 s −32%, 9/9 pairs faster
SELECT uniqExact(s) FROM st 0.328 s 0.243 s −26%, 9/9
SELECT count() FROM st GROUP BY s 0.255 s 0.254 s unchanged
SELECT sum(sipHash64(s)) FROM st 0.307 s 0.309 s unchanged

GROUP BY and sipHash64() evidently do not route through updateHashWithValue, so they are flat. An A/A null on the same protocol gave +2.2% and +1.6% with a within-arm spread of 25–52 ms, and the controls — DISTINCT over a plain Array(UInt64), a numbers GROUP BY, and a finalizeAggregation read — all moved ≤1.5%.

The gain tracks the allocation count rather than the bytes. Holding total state bytes at 160 MB and only changing the shape:

shape before after
500k rows × 320 B 0.361 s 0.245 s −32.1%, 7/7
50k rows × 3.2 KB 0.277 s 0.239 s −13.7%, 7/7
5k rows × 32 KB 0.346 s 0.322 s −6.9%, 7/7

The 32 KB states exceed the 1 KiB window 31×, so the candidate flushes ~31 times per row there and is still faster.

Hash values are unchanged

sipHash64(state) reads the patched path's exact 64-bit output, so it is a direct equality check: 17 aggregate-function families (groupArray, groupUniqArray, uniq, uniqExact, uniqCombined, uniqHLL12, quantiles, quantilesTDigest, sum, avg, min, max, any, topK, sumMap, argMax, corr) × 8 groups, a state-size sweep from 0 to 5000 elements, and empty / Nullable / LowCardinality / array-of-states / tuple / FORMAT Hash cases — 160 hash values, byte-identical before and after.

The existing identity gtest covers the stack variant too now: the same stream shapes, a 64-byte versus 16 KiB window equivalence case, and a one-byte perturbation control. Two things worth knowing if you try a larger window: -Wframe-larger-than=65536 caps it (a 256 KiB window in a test body is a build error), and get64() runs the finalization step, so a test that reads it twice on one object compares against a value that no longer exists — which is what caught me first.

On other hash algorithms specifically

SipHash streams for free because update carries its state, including a sub-word remainder. updateWeakHash32 does not: it consumes 8-byte words, and its tail step re-reads the last 8 bytes (end - 8) and folds the total length into the low byte, so a bit-exact sink must carry both a partial word and the trailing 8 bytes plus the total size — it is not a drop-in. I left computeHashInto alone because for AggregateFunction there is no reachable workload for it: window PARTITION BY and JOIN ON both reject AggregateFunction arguments outright. HashingWriteBuffer's CityHash128 already streams, but with chunk-dependent semantics, so it is not interchangeable either.

One negative, so nobody repeats it

IColumn::getValueName and the large-constant check in buildQueryTreeForShard have exactly this shape too — they materialize a constant's whole escaped text purely to compare its length against optimize_const_name_size — but it is not measurably costly. optimize_const_name_size <= 0 skips that block entirely, so the setting is its own floor, and an 80 MB folded literal shows no difference either way (0.202 s vs 0.200 s through remote(), 0.103 s vs 0.100 s locally). A repeat()-folded constant is named by its source expression rather than by its value, and a literal that does reach getValueName is bounded by max_query_size.

The patch is on a branch here. Happy to open a PR for the aggregate-state part if that looks worthwhile.

@snelheidai

Copy link
Copy Markdown

good idea, it might also be generalized to other hash algorithms.

It does generalize, and the place where it pays turned out to be one level above the algorithms: the SQL hash dispatcher itself. FunctionAnyHash::executeGeneric — the fallback that serves every function in this family, xxHash64, xxh3, cityHash64, murmurHash*, farmHash64, metroHash64, sipHash* — buffered each value and then copied the buffer out again before hashing it:

WriteBufferFromOwnString buf;                                  // per row
serialization->serializeForHashCalculation(*column, i, buf);
auto bytes = buf.str();                                        // str() returns std::string &, so auto copies
hash = apply(key, bytes.data(), bytes.size());

Per row that is an allocation for the buffer, its growth reallocations (it starts at 32 bytes and doubles), and then a second allocation plus a full copy of the value into bytes. As in #115847 the serialized form is hash input only and is dropped immediately, so the buffer can live outside the loop and be hashed in place:

         SerializationPtr serialization;
+        /// The serialized form is hash input only and is discarded immediately, so it does not need
+        /// a fresh buffer per row: one buffer reused across rows keeps its capacity (no per-row
+        /// allocation and no growth reallocation after the first rows), and its contents are hashed
+        /// in place instead of being copied out into a std::string.
+        WriteBufferFromOwnString buf;
         for (size_t i = 0, size = column->size(); i < size; ++i)
         {
             if constexpr (Keyed)
@@
                 if (!serialization)
                     serialization = type->getDefaultSerialization();
-                WriteBufferFromOwnString buf;
+                buf.restart();
                 if (const auto * column_const = typeid_cast<const ColumnConst *>(column))
                     serialization->serializeForHashCalculation(column_const->getDataColumn(), 0, buf);
                 else
                     serialization->serializeForHashCalculation(*column, i, buf);
-                auto bytes = buf.str();
+                const auto bytes = buf.stringView();
                 hash = apply(key, bytes.data(), bytes.size());

Which queries reach it

The types with no dedicated branch in executeAny that are not contiguous: AggregateFunction, JSON, Dynamic, Variant. Worth knowing before looking for this elsewhere: Map never reaches it — executeForArgument unwraps ColumnMap into its nested Array(Tuple(K,V)) and flattens Tuple, so xxHash64(some_map) hashes each key and value separately. My first A/B used a Map(String,String) column and was a flat null (−1.4%, 5/9 pairs) for exactly that reason.

Measured

clickhouse local, master 10bec7b8810 versus the same tree plus this change, x86_64 Release/clang-21, 9 paired interleaved repetitions per query with alternating arm order and a fresh process per repetition, median of ClickHouse's own query time:

query before after
sum(xxHash64(s)), 2M rows × 40 B groupArray state 0.315 s 0.129 s −59.1%, 9/9
sum(xxHash64(v)), 1M rows Variant(UInt64, String, Array(UInt64)) 0.124 s 0.066 s −46.8%, 9/9
sum(xxHash64(s)), 500k rows × 320 B state 0.273 s 0.153 s −44.0%, 9/9
sum(cityHash64(s)), same 0.276 s 0.173 s −37.3%, 9/9
sum(xxh3(s)), same 0.272 s 0.173 s −36.4%, 9/9
sum(sipHash64(s)), same 0.308 s 0.204 s −33.8%, 9/9
sum(xxHash64(u)), 500k rows uniqExact state 0.303 s 0.207 s −31.7%, 9/9
sum(xxHash64(j)), 1M rows small JSON 0.487 s 0.368 s −24.4%, 9/9
sum(xxh3(j)), same 0.476 s 0.361 s −24.2%, 9/9
sum(xxHash64(j)), 200k rows larger JSON 0.256 s 0.217 s −15.2%, 9/9
sum(xxHash64(s)), 5k rows × 16 KB state 0.115 s 0.107 s −7.0%, 9/9

The gain tracks rows rather than bytes hashed, which is the signature of removing per-row bookkeeping rather than hash work: at 40 B per value −59%, at 320 B −44%, at 16 KB −7%.

An A/A null on the same protocol gave +0.36%, +0.63% and +0.21%. Paths the patch cannot execute stayed flat: Map −1.4%, UInt64 ±0.0%, GROUP BY on the state column +0.9%, DISTINCT on it +1.2%, and String and plain Array(UInt64) both ±0.0% (they came out +4.3% and +3.1% in the 9-repetition sweep, so I re-ran them at 15 repetitions with an A/A alongside — the A/A drifted −2.7% and −3.0%, and the deltas went to zero with 7/15 and 6/15 pairs, i.e. it was drift, not the patch). 1M Dynamic rows did not move either (a 27 ms query — too little per-row work there to recover). Peak RSS is unchanged to slightly lower (299/304/298 MB → 294/293/295 MB on the 320 B state query, 303 → 291 MB on the JSON one). The reused buffer holds the largest value seen in the block until the loop ends, but the old code held its buffer and the str() copy at the same time, so the peak does not grow.

Hash values are unchanged

The change hands the same bytes to the same one-shot apply(), and that is checked rather than assumed: 17 algorithms (xxHash32/64, xxh3, cityHash64, sipHash64/128, halfMD5, murmurHash2_64, murmurHash3_64/128, metroHash64, farmFingerprint64, farmHash64, wyHash64, javaHash, gccMurmurHash, kafkaMurmurHash) × Map, Map(String, Array), Map with NULLs, Map of tuples, LowCardinality keys, Variant, Dynamic, JSON, groupArray and uniqExact states, plus raw per-row values, multi-argument combineHashes, sipHash64Keyed/sipHash128Keyed with constant and per-row keys, const-folded and materialized constants, empty input, 1 MB values, and a table alternating 3-byte and 60 KB values in one block — 222 comparisons, all byte-identical. All 109 in-tree *hash* stateless tests also produce byte-identical output on both binaries.

On streaming into the algorithm specifically

Tried it as a separate build, since that was the literal suggestion: a WriteBuffer that feeds XXH64_update / XXH3_64bits_update directly, so nothing is buffered at all. It is bit-exact — the incremental digests equal the one-shot values through this dispatch, all 222 probes identical — but it is slower than hashing the reused buffer, measured against the patch above on the same fixtures:

query reused buffer streamed into the hash
sum(xxHash64(v)), 1M Variant 0.067 s 0.085 s +26.9%, 0/9
sum(xxHash64(s)), 2M × 40 B state 0.130 s 0.162 s +24.6%, 0/9
sum(xxh3(s)), 500k × 320 B state 0.110 s 0.119 s +8.2%, 1/9
sum(xxHash64(j)), 1M JSON 0.367 s 0.389 s +6.0%, 1/9
sum(xxHash64(s)), 5k × 16 KB state 0.108 s 0.108 s ±0.0%, 4/9

cityHash64 and sipHash64 deliberately got no streaming state in that build and moved −0.9% / −0.7%, which is the identical-code control. A per-row incremental state simply costs more than one memcpy into a cache-hot buffer: XXH3_state_t is ~576 bytes with an alignment requirement and XXH3's one-shot path for short inputs is separately optimized, while XXH64_update has to carry a partial-word remainder. The penalty disappears once values are large enough (16 KB) to amortize it.

So for the other algorithms the transferable half of #115847 is not materializing — not feeding the hash incrementally. SipHash is the special case where update is cheap enough that both halves come for free.

Server path and concurrency

Same patch through clickhouse server (one server per arm, alternating, 7 paired repetitions), then oversubscribed:

before after
sum(xxHash64(s)), 500k × 320 B state, 1 client 0.216 s 0.108 s −50.0%, 7/7
same, 4 concurrent clients (wall) 0.862 s 0.501 s −41.9%, 5/5
same, 1 client max_threads=16 0.189 s 0.093 s −50.8%, 5/5
sum(xxHash64(j)) on 1M JSON, 1 client 0.473 s 0.363 s −23.3%, 7/7
same, 4 concurrent clients (wall) 2.169 s 1.715 s −20.9%, 5/5

Nothing contends: the change removes allocator traffic rather than adding shared state, and the buffer is a function-local.

Limitations worth stating: x86_64 only, one build configuration, page cache warm in both arms (no root on this box to drop it), and 4-core wall-clock timings against an A/A floor of about 1%. Happy to open this as a PR if it looks right to you.

@egor-click

Copy link
Copy Markdown
Contributor

@groeneai can you take a look at the comment above from snelheidai and create a follow up PR?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged, I will take this on. I checked the two comments above against master c625830a first, since that decides what a follow-up should actually contain.

FunctionAnyHash::executeGeneric (src/Functions/FunctionsHashing.h:1179, :1184) holds up. The per-row WriteBufferFromOwnString is there, and auto bytes = buf.str(); does copy the serialized value, because str() returns std::string & (src/IO/WriteBufferFromString.h). There is already an in-tree precedent for exactly that fix shape: SerializationObject.cpp:857-864 hoists one buffer out of the loop, takes const auto & data = buf.str();, and calls buf.restart(); per iteration. Scope note: the streaming sink from this PR is not needed there, because apply() bottoms out in Impl::apply(begin, size), one-shot over a contiguous region, so the bytes still have to be materialized for xxHash64/cityHash64/murmurHash*/farmHash64/metroHash64. Reusing the buffer and dropping the copy is the whole win.

ColumnAggregateFunction: the three sites are not equally worth changing.

  • updateHashFast (ColumnAggregateFunction.cpp:477) materializes an entire column purely to hash it. That is the closest analogue to this PR, and it needs no new class, just the existing sink.
  • computeHashInto (:462) already reuses one vector across rows, and updateWeakHash32 is one-shot, so I do not see anything to win there.
  • updateHashWithValue (:455) is the per-row one. It is a const IColumn virtual, so a reused member buffer would be shared mutable state across concurrent callers, which is what makes a stack window the right shape rather than a member. Whether that justifies a new class in IO/ is a measurement question.

What will decide PR versus no PR for me: a perf test showing the executeGeneric copy is measurable on a non-contiguous type (Array/Map/JSON through xxHash64), bit-identical hash results since those are user-visible, and a workload where updateHashWithValue is hot enough to pay for a new class.

I will follow up in this thread with the PR, or with the findings if part of it does not hold.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up: #119322

The three things I said would decide it.

Measurable, yes, but on fewer types than I claimed above. Array and Map never reach executeGeneric: executeAny routes Array and Nullable to their own overloads, executeForArgument flattens Tuple and unwraps Map, LowCardinality is stripped by the default adaptor, and Dynamic is split per internal type. Only JSON/Object, Variant and AggregateFunction get there, which I confirmed by throwing from that branch, so an Array/Map fixture would have measured nothing. Release build, medians of interleaved arms: sum(xxHash64(v)) over 20M rows of Variant(UInt64, String) 1.872s -> 1.126s (-39.9%, disjoint ranges), and sum(sipHash64(j)) over 3M rows of JSON -5.5%.

Bit-identical, yes. Two committed tests already pin these values (03719_generic_hash_over_constant_and_non_constant for Variant, including the ColumnConst branch, and 03639_hash_of_json_column for JSON), byte-identical on base and fix, and three mutant builds redden them, so they are not passing vacuously.

The new class is moot. BufferWithOwnMemory's constructor already accepts caller-owned memory, so a stack window is a constructor argument rather than a new type; the existing sink only had to move to IO/, since src/Columns cannot include a Processors header. uniqExact over 300k 200-byte groupArray states is 33% faster single-threaded, and the gain tracks state size the way the removed reallocations do, so 6-byte states give only -10% and I report that as marginal.

Two parts do not ship. computeHashInto already reuses its buffer across rows. updateHashFast I dropped: it does materialize a whole column, but across nine query shapes (IN lists of state literals, projections, AggregatingMergeTree, subquery sets, a Set-engine table, tuple IN) I only ever reached it with a one-row column of constants, so there was no memory delta to observe. If you know the shape that reaches it with a real column, that part is easy to add.

On generalizing the streaming sink to the other hash algorithms: it does not generalize. Every Impl::apply behind FunctionAnyHash takes one contiguous (begin, size) region, so the bytes still have to be materialized there; only the per-row allocation and the copy could go.

pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Sep 12, 2026
FunctionAnyHash::executeGeneric hashes a value whose type is not
unambiguously represented in a contiguous memory region by serializing it
with ISerialization::serializeForHashCalculation and hashing the result.
It paid for that twice per row:

  - `WriteBufferFromOwnString buf;` inside the row loop.
    WriteBufferFromVectorImpl's constructor resizes an empty backing
    string to initial_size = 32, which is past std::string's small-string
    capacity, so every row allocated regardless of the value's size.
  - `auto bytes = buf.str();`. str() returns std::string &, so `auto`
    deduces std::string and copies the whole serialized value again.

Hoist one buffer above the loop, read the bytes by const reference, and
restart() between rows. restart() re-points the buffer at the start of
the backing string and keeps its capacity, so one allocation is amortized
over the column and the copy is gone.
SerializationObject::serializeBinaryBulkWithMultipleStreams already uses
that shape for the same reason.

This is as far as the streaming sink from ClickHouse#115847 generalizes here: every
Impl::apply behind FunctionAnyHash (sipHash*, xxHash64, xxh3,
cityHash64, murmurHash*, farmHash64, metroHash64, halfMD5) takes a single
contiguous (begin, size) region and offers no incremental update through
that interface, so the bytes still have to be materialized. Only the
per-row allocation and the copy can go.

Hash values are unchanged: the byte stream handed to Impl::apply is the
same, only the buffer it is written into is now reused.

Only JSON/Object, Variant and AggregateFunction columns reach this
branch. executeAny routes Array and Nullable to their own overloads,
executeForArgument flattens Tuple and unwraps Map before dispatch,
LowCardinality and every fixed-layout type take the getDataAt path in the
same loop, and Dynamic is split per internal type by
FunctionBaseDynamicAdaptor.

Release build, medians of interleaved runs per arm:

  sum(xxHash64(v)), v Variant(UInt64, String), 20M rows
      1.872s -> 1.126s   (-39.9%, n=7, ranges disjoint)
  same, max_threads=1, 5M rows
      0.473s -> 0.287s   (-39.3%, n=5, ranges disjoint)
  sum(sipHash64(j)), j JSON, 3M rows
      2.728s -> 2.579s   (-5.5%, n=5, ranges disjoint)
alexey-milovidov pushed a commit to rorylshanks/ClickHouse that referenced this pull request Oct 6, 2026
`calculateHashFromStep` serialized every `ExpressionStep` and `FilterStep` below
an aggregation in full, including the values of folded constants. A scalar
subquery folds its whole result into the DAG, so the `scalar` performance test
(8 `groupBitmap` states) serialized and hashed about 10 MB on every execution:
7.2 ms per query, measured at the call. `QueryPlanOptimizeMicroseconds` on that
query drops from 10.4 ms to 2.1 ms (median), the same as with
`collect_hash_table_stats_during_aggregation = 0`.

These two steps are now keyed by their DAG structure and names without the
constant values. Names identify the constants in practice (`600000_UInt32`,
`__getScalar('<hash>')`), so expressions that differ only in a literal still
get distinct keys. Hashing only the output types would not do: over a
subquery the aggregation key is `__table1.k` for any expression, and the new
test fails that way.

Closes: ClickHouse#115805
Related: ClickHouse#113736
Related: ClickHouse#115847

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to ClickHouse/librdkafka that referenced this pull request Nov 5, 2026
…Offset

rd_kafka_toppar_handle_Offset is declared "Locality: toppar handler thread"
and reads rktp->rktp_op_version without a lock at two sites: the rd_rkb_dbg
argument, and the rd_kafka_buf_version_outdated call that classifies the
reply as outdated. The writer, rd_kafka_toppar_op_version_bump, is correct:
rd_kafka_toppar_fetch_stop takes the toppar lock before bumping.

The locality declaration does not hold during termination.
rd_kafka_buf_callback routes through the reply queue only when the error is
not RD_KAFKA_RESP_ERR__DESTROY and rkbuf_replyq.q is set. This request always
has a reply queue, so every other error is queued to the toppar thread, but
__DESTROY fails the first conjunct before the queue is consulted and the
callback is invoked directly on the calling thread. When
rd_kafka_broker_thread_main drains the send and retry queues on the way down
it passes that error from a broker thread, so the callback runs there.

The __DESTROY test guards the rd_kafka_buf_version_outdated call but not the
rd_rkb_dbg argument, so on that route the debug-log read of rktp_op_version
races the bump. ThreadSanitizer reports exactly that pair: the read at
rdkafka_partition.c:1444 on a broker thread against the bump at :201 on the
toppar handler thread.

Snapshot rktp_op_version into a local inside the critical section this
function already opens to read rktp_leader, and use the local at both sites.
No new lock is acquired and no new critical section is introduced, so there
is no new lock-order edge, and it closes the second read too if a future
dispatch change ever reaches it.

The race reds ClickHouse's Integration tests (amd_tsan, *) jobs: the test
body passes and the harness promotes the sanitizer report to a failure. Four
unrelated pull requests have hit it across two tests since 2026-04-06, so it
is a pre-existing defect rather than any one change.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115847&sha=652cdb2fe2e6f0aca4dc7b6c0e0e5c5a&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Surfaced on: ClickHouse/ClickHouse#115847

Co-Authored-By: Claude Fable 5 <[email protected]>
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 10, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 10, 2026
Backport #115847 to 26.8: Do not buffer the serialized step when computing the hash-table-stats cache key
leshikus pushed a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

8 participants