Repository navigation
Do not materialize a serialized value only to hash it - #119322
Conversation
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)
The sink depends only on IO/BufferWithOwnMemory.h, IO/WriteBuffer.h and Common/SipHash.h, and the next commit needs it from src/Columns, which must not include a header from Processors. The header and its gtest move unchanged apart from the include. The constructor also gains the size/existing_memory pair that BufferWithOwnMemory already accepts: with caller-supplied memory that constructor initialises memory(0, alignment) and allocates nothing, so a caller can hand it a stack window instead of paying for a 32 KiB one. Existing callers keep the 32 KiB owned window by default.
ColumnAggregateFunction::updateHashWithValue serialized one aggregate state into a WriteBufferFromOwnString and then hashed the result. It is a per-row method: uniq, uniqExact, DISTINCT, arrayDistinct, transform, Block::updateHash and the Hash output format all reach it once per row, so each row paid for a fresh buffer, and a state larger than initial_size = 32 paid for the doubling reallocations on top. Write the state straight into a SipHashingWriteBuffer over a 1 KiB stack window instead. SipHash::update carries its state, including any sub-word remainder, across calls, so the hash of a chunked stream equals the hash of the same bytes contiguous: the values are unchanged, which 05175_hash_of_aggregate_function_state_column and the sink's gtest both pin. Release build, uniqExact over a column of groupArray states, max_threads=1, medians of 7 interleaved runs per arm: 300k states, 200 bytes each 0.081s -> 0.054s (-33.3%, ranges disjoint) 2M states, 6 bytes each 0.455s -> 0.408s (-10.3%, ranges overlap) The gain tracks the state size because the removed reallocations do: a tiny state fits the 32-byte initial allocation, a 200-byte one does not. updateHashFast is deliberately left alone. It materializes a whole column of states, which looks worse, but it is only ever reached with a one-row column: the projection matcher's FutureSetFromTuple::computeContentHash was not reachable with an AggregateFunction set from any query shape I could construct (literal IN lists, subquery sets, a Set-engine table, projections, AggregatingMergeTree), and its other caller, ConstantNode, hashes constants. computeHashInto is left alone too: its buffer is already hoisted out of the row loop.
executeGeneric holds one WriteBufferFromOwnString above its row loop, but
the branch that uses it tests
isValueUnambiguouslyRepresentedInContiguousMemoryRegion() on a type that
is fixed for the whole call. The buffer was therefore also constructed for
the types that take the getDataAt path and never touch it, and
WriteBufferFromVectorImpl's constructor resizes its backing string to
initial_size = 32, past std::string's small-string capacity, so that is a
real heap allocation once per call per hashed argument.
Test the invariant once into a local and emplace the buffer only when the
serialize path will be taken. One loop, and the Keyed and first
bookkeeping is untouched.
DateTime64 and Interval are the types this affects: executeAny has no
branch for either, and both report a contiguous representation. Probed by
throwing from the contiguous branch rather than assumed, because two
plausible candidates turn out not to reach executeGeneric at all:
executeAny dispatches Decimal32/64/128/256 to executeBigIntType, and
LowCardinality is stripped by the default adaptor before the body runs,
since FunctionAnyHash does not override
useDefaultImplementationForLowCardinalityColumns().
Hash values on that path are unchanged. Base against this commit, both
byte-identical:
xxHash64(materialize(toDateTime64('2020-01-01 00:00:00.123', 3)))
xxHash64(materialize(toIntervalSecond(7)))
The Variant throughput this branch already claims is unaffected: -39.6%
against base over 7 interleaved runs, against -39.9% measured before this
change. That is expected, since Variant takes the serialize path, where
the buffer is still built exactly once per call.
SipHashingWriteBuffer::nextImpl is the only path by which a byte reaches the hash before finalize, and it runs only once a stream outgrows the window. Nothing committed crossed that boundary through the new size/existing_memory constructor: every gtest shape uses the default 32 KiB owned window, and the states in 05175_hash_of_aggregate_function_state_column are 2 to 6 bytes against updateHashWithValue's 1 KiB stack window. Parameterise the shared shape list on the window size and add one arm that runs it over a 64-byte caller-owned window, twice: from a fresh hash, and from one pre-seeded with a 3-byte prefix so the first written byte lands on the sub-word remainder SipHash::update carries. That is what hash128 produces when it feeds a second key column, which is how ColumnAggregateFunction is reached in practice. The arm compares the 128-bit output rather than get64(), since that is what those callers consume and get64() is only its fold. Add one statement to the SQL test whose states are about 2 KiB and differ only in their leading bytes, so each state flushes the window more than once and a discarded non-final window collapses the distinct count. Both additions are non-vacuous. A build whose nextImpl drops full windows and keeps only the final partial one leaves the pre-existing statement at 50 50, turns the new one into 2, and fails the new gtest arm.
Internal second-model reviewReviewed in two rounds, each by my own cold pass plus an independent second model: round 1 agreed 6 findings and bounced the two substantive ones, round 2 returned none from either pass. The one worth surfacing: no committed test crossed this sink's flush boundary through a caller-owned window, so a build that dropped every non-final window left the whole suite green. Round 2 added one gtest arm over a 64-byte window (entered from a pre-seeded hash, compared on the 128-bit output) and one Measurements are |
|
Workflow [PR], commit [8302b85] Summary: ✅
AI ReviewSummaryThis PR removes per-row materialization and copying on two serialized-hashing paths: Missing context / blind spots
Final Verdict✅ No new findings in the current head. LLVM Coverage ReportMeasured on commit 8302b85.
Changed lines: Changed C/C++ lines covered: 41/41 (100.00%) · Uncovered code |
|
cc @antaljanosbenjamin @Algunenano, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+43.22 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units14 translation units recompiled, 49 s compile time in total, 14 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR reworks how serialized values and aggregate-function states are hashed (a stack-owned SipHashing window plus buffer reuse in FunctionAnyHash), plus a header move and new tests. The only flagged query, clickbench Q33, is a wide many-column SUM(ResolutionWidth + N) aggregation that never serializes values for hashing, so it cannot plausibly exercise the changed code. The math already placed its +5.7% inside master's current variance band with essentially unchanged CPU (16594 vs 16710 ms), so this is run-to-run noise, not a PR effect. No regressions or improvements are attributable to the change on these benchmarks. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…fication (fixes 05141_time_series_select_join_settings)
CI finish ledger - aaec9e5Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Cause and fix, measured rather than inferred: #117356 ("Unify the spill trigger for hash joins") Rule 3c, not 3d, decided at the FAILING head rather than at the live one: the failing legs' server Session id: cron:our-pr-ci-monitor:20260911-020045 |
executeGeneric reuses one WriteBufferFromOwnString across the rows of a block. An uncapped restart() keeps the high-water capacity, so a single outlier row pinned its allocation for the rest of the block in every thread hashing such a column. restart() takes a max_capacity for exactly this, and MessageQueueSink passes DBMS_DEFAULT_BUFFER_SIZE in its per-row loop for the same reason. Hash values are unchanged: the bytes handed to Impl::apply are identical, only the allocation behind them is released earlier. Verified byte-identical over Variant, JSON and AggregateFunction columns with the outlier row placed first, in the middle, last and alternating, across xxHash64, sipHash64, cityHash64, farmHash64, metroHash64, murmurHash3_64, xxh3, sipHash128 and sipHash64Keyed. The buffer doubles and the allocation overshoots, so a 530 KB value already reports a capacity of 1572863 bytes and crosses the 1 MiB cap. Values under about 520 KB never reach it: this PR's 20M row Variant fixture measures +0.2% user CPU, median of 24 runs. Columns whose values exceed it pay the per-row allocation again, 15 to 25% on this path, which is what master did before this PR.
|
@groeneai update this branch once all the CI found issues are fixed. |
…hout-materializing
Three things kept tests/performance/hashing_serialized_values.xml from
producing a comparison.
1. perf.py expands {parameter} substitutions by running every query text
through str.format, so the brace of the JSON literal was read as a
substitution field and the whole file aborted before a single query
ran, failing the two Performance Comparison shards that own it
(amd_release 2/6 and arm_release 3/6 at 47d7d45):
File "./tests/performance/scripts/perf.py", line 366, in substitute_parameters
values = [available_parameters[k] for k in keys]
KeyError: '"a"'
Doubling the braces is what the other performance tests with JSON
literals do: json_string_value_formatting.xml,
json_advanced_shared_data_read_paths.xml, concat_hits.xml.
2. The aggregate-state query took 0.028 s with default parallelism, below
the 0.1 s that ci/jobs/scripts/perf/report.py requires (the
"Unexpected Query Duration" table, action required for every item). It
is now single-threaded, which tests/performance/scripts/README.md
names as one remedy and which matches the measurement quoted in the
changelog, and the fixture doubles to 2M states so the arm keeps its
margin over the floor on a faster machine.
3. The JSON query's worst single run was 1.56 s against the 2 s per-run
ceiling of get_allowed_single_run_time in the same report script, the
tightest of the three arms, so it hashes 2M rows instead of 3M.
Measured with the runner itself against a release server, 7 runs per arm:
medians 1.182 s, 1.040 s, 0.353 s with spreads of 2.1%, 0.5% and 2.5%,
all inside the 0.1 s to 2 s window; 21 s for the whole file on one server.
CI finish ledger - 47d7d45Branch updated as asked: master
None of the last three is reachable from this diff, which touches only the hashing sink, and each keeps firing on unrelated branches until its fix lands. The two perf shards were one defect. The braces are doubled now, as in the other performance tests with JSON literals. Only Running the file through the runner against a release server exposed two more contract violations CI had never reached, because the file never got that far: the aggregate-state query took 0.028s, below the 0.1s minimum in The CIDB query behind those countsSELECT countIf(pull_request_number = 0 AND head_ref = 'master') AS master_rows,
uniqIf(commit_sha, pull_request_number = 0 AND head_ref = 'master') AS master_trees,
uniqIf(pull_request_number, pull_request_number > 0) AS distinct_prs,
count() AS rows_total, min(check_start_time), max(check_start_time)
FROM default.checks
WHERE test_status IN ('FAIL', 'ERROR')
AND position(test_name, 'Invalid number of columns in chunk pushed to OutputPort') > 0
AND check_start_time > now() - INTERVAL 14 DAYSession id: cron:clickhouse-premium-slot-25:20260911-095600 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Hashing a value that has no contiguous in-memory representation (
JSON,Variant,AggregateFunction) no longer allocates and copies a buffer per row.xxHash64over aVariantcolumn is about 40% faster,sipHash64over aJSONcolumn about 5%. Counting distinct aggregate states withuniqExactis about 33% faster for 200-byte states;uniq,DISTINCTandarrayDistincthash states through the same path.Description
Follow-up to #115847, requested by @ egor-click at #115847 (comment), answering @ nickitat's question there about generalizing it.
FunctionAnyHash::executeGenerichashes a value whose type is not unambiguously represented in a contiguous memory region by serializing it. Per row it built aWriteBufferFromOwnString(whose constructor resizes the backing string to 32 bytes, past small-string capacity, so every row allocated) and read the bytes back withauto bytes = buf.str();str()returnsstd::string &, soautocopied the whole serialized value again. One buffer is now hoisted out of the loop, read by reference, andrestart(DBMS_DEFAULT_BUFFER_SIZE)ed between rows, so one outlier row's allocation is not pinned for the rest of the block.ColumnAggregateFunction::updateHashWithValuedid the same per row, and a state larger than 32 bytes also paid the doubling reallocations. It now writes into aSipHashingWriteBufferover a stack window. That sink moves toIO/(src/Columnscannot include aProcessorsheader) and gains the caller-owned-memory argumentBufferWithOwnMemoryalready supports.The sink does not generalize further: every
Impl::applybehindFunctionAnyHashtakes one contiguous(begin, size)region, so the bytes must still be materialized. Only the allocation and the copy can go.Hash values are unchanged by construction (identical byte stream) and pinned by
03719_generic_hash_over_constant_and_non_constant,03639_hash_of_json_columnand the new05175_hash_of_aggregate_function_state_column.Not changed, deliberately:
computeHashInto(buffer already hoisted out of its row loop),updateHashFast(materializes a whole column, but I could not reach it with a column of more than one row from any query shape I tried), andexecuteGeneric's re-serialization of row 0 for aColumnConst.Measurements (release build, medians of interleaved runs per arm)
sum(xxHash64(v)),v Variant(UInt64, String), 20M rowsmax_threads=1, 5M rowssum(sipHash64(j)),j JSON, 3M rowsuniqExact(st), 300k 200-bytegroupArraystates,max_threads=1tests/performance/hashing_serialized_values.xmlcovers all three shapes in CI.Workflow [PR]
Sync PR [sync-upstream/pr/119322]