Repository navigation
Do not buffer the serialized step when computing the hash-table-stats cache key - #115847
Conversation
… 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.
Internal second-model review (2 rounds, 0 blockers) - click to expandEvery change here was reviewed by a second model with no access to the authoring ❌ BlockersNone.
|
|
Workflow [PR], commit [652cdb2] Summary: ✅
AI ReviewSummaryReviewed the streamed hashing change in Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260821-133300 |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units416 translation units recompiled, 3582 s compile time in total, 416 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
CI finish ledger: 652cdb2Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The test body passes. Session id: cron:our-pr-ci-monitor:20260822-050000 |
|
Fixing PR for the librdkafka The race is entirely inside the vendored The ClickHouse-side submodule bump follows once the fork PR merges. |
|
good idea, it might also be generalized to other hash algorithms. |
2797514
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 existsSweeping
The per-row site needs the window on the stackReusing 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
The gain tracks the allocation count rather than the bytes. Holding total state bytes at 160 MB and only changing the shape:
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
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: On other hash algorithms specifically
One negative, so nobody repeats it
The patch is on a branch here. Happy to open a PR for the aggregate-state part if that looks worthwhile. |
It does generalize, and the place where it pays turned out to be one level above the algorithms: the SQL hash dispatcher itself. 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 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 itThe types with no dedicated branch in Measured
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: Hash values are unchangedThe change hands the same bytes to the same one-shot On streaming into the algorithm specificallyTried it as a separate build, since that was the literal suggestion: a
So for the other algorithms the transferable half of #115847 is not materializing — not feeding the hash incrementally. Server path and concurrencySame patch through
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. |
|
@groeneai can you take a look at the comment above from snelheidai and create a follow up PR? |
|
Acknowledged, I will take this on. I checked the two comments above against master
What will decide PR versus no PR for me: a perf test showing the I will follow up in this thread with the PR, or with the findings if part of it does not hold. |
|
Follow-up: #119322 The three things I said would decide it. Measurable, yes, but on fewer types than I claimed above. Bit-identical, yes. Two committed tests already pin these values ( The new class is moot. Two parts do not ship. On generalizing the streaming sink to the other hash algorithms: it does not generalize. Every |
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)
`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]>
…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]>
Backport #115847 to 26.8: Do not buffer the serialized step when computing the hash-table-stats cache key
…uting the hash-table-stats cache key
Changelog category (leave one):
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
calculateHashFromStepbuffered a step's whole serialized form, then hashed it in a second pass. That stream is hash input only, andserializeConstantwrites 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 smallWriteBufferfeeding aSipHashover a 32 KiB window.The key value is bit-identical to before, since
SipHash::updatecarries state across calls including any sub-word remainder. That matters because a collision is harmless for only one of the three consumers:considerEnablingParallelReplicasuses 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 localon aGROUP BYover an 80 MBrepeat()literal, 3 runs:QueryPlanOptimizeMicrosecondsPeak memory now sits at the floor. Same at 800 MB: 3460 to 1817 MB, floor 1817 MB.
The O(N) term remains:
serializeBinarystill 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
26.9.1.35-master(included in26.9and later)