Repository navigation
Introduce PackedStringRef & PackedStringHashTable - #110573
Conversation
`StringViewHash::operator()` returns `size_t`, but `WeakHash32::data` is a container of `UInt32`. The implicit conversion was caught by `-Wshorten-64-to-32` in the `Fast test`, `Build (arm_tidy)`, and `Build (llvm_coverage_build)` jobs. Add an explicit cast to `UInt32`. The lower 32 bits are equivalent since `CRC32Hash` fills both halves with the same value. Report: ClickHouse#93271
…ision The test was added in ClickHouse#90880 to demonstrate a cross-version string serialization bug that only manifests when two-level aggregation is active across servers running incompatible serialization formats. This PR introduces `AggregationMethodPackedString` for the `key_string` slot, replacing `AggregationMethodString` (`StringHashTable`). Because the on-the-wire layout for single-string-key aggregation states is incompatible between the two methods, this PR raises `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` from 54448 to 54484. As a side effect, two-level aggregation is now disabled in distributed queries against any server older than 54484 (including 25.6, used by `node256` in the integration test), and the bug demonstrated by the test cannot be reproduced anymore — the deduplication succeeds and the query returns 10000 instead of 20000. Update the assertion to 10000 and add a comment explaining the change. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93271&sha=6bde8cea7bc1e97b3d8cd5c96e902042f1c7fd60&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%205%2F6%29 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The documented mode detection summary states that medium strings have `high != 0`, but `isMedium` was checking only `getSmallSize() == 0` and classified the empty representation (`high == 0`, `low == 0`) as medium. Add an explicit `isEmpty` helper, exclude it from `isMedium`, and handle the empty case explicitly in `operator std::string_view` so it returns a default-constructed (rather than null-data) view. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…EVISION_WITH_PACKED_STRING_HASH_TABLE` After merging master, `DBMS_TCP_PROTOCOL_VERSION` and `DBMS_MIN_REVISION_WITH_PACKED_STRING_HASH_TABLE` are both 54485, but the aggregation-variant guard was left at 54484. With the old threshold, a rolling upgrade where one side is at 54484 and another at 54485 would still keep two-level aggregation enabled, even though the string-key bucketing logic differs between versions — reintroducing the cross-version partial-aggregation mismatch this guard prevents. Also bump `DBMS_MIN_MINOR_VERSION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` from 1 to 5 to align with the current development minor version (26.5), matching the convention used for the previous bump. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`PackedStringRef` encodes its payload, size bits, and large-string tag into two 64-bit words using `memcpy` into byte offsets that assume the LSB sits at the lowest address. On big-endian builds, the inline payload and tag bits would alias to different bit positions, so `build`, `isSmall` and `operator std::string_view` could misdecode keys and produce incorrect grouping behavior. Add an explicit `static_assert` so the encoding is rejected at compile time on non-little-endian targets, until and unless a portable representation is introduced. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous encoding mixed `uint64_t` value semantics with byte-pointer semantics inside `PackedStringRef::build`: `r.low = hash` placed the hash in the low 32 bits of the `low` word, and the subsequent `memcpy(&r.low + 4, ptr, len)` wrote the inline payload at byte offset 4. On little-endian platforms these two views overlap correctly, but on big-endian the hash sits in the upper 4 bytes of `r.low` (bytes 4-7) and the payload `memcpy` overwrites it. The previous commit added a file-scope `static_assert(std::endian::native == std::endian::little, ...)` to surface this, which broke the s390x build because `<base/PackedStringRef.h>` is included transitively from `src/Common/HashTable/Hash.h` and reaches every `clickhouse_common_io` translation unit. Switch to a byte-stable layout: every field lives at a fixed byte offset inside the struct, written via `memcpy` (or an explicit little-endian shift helper for the 56-bit packed pointer and the 64-bit length). The byte sequence is identical on both endianness, so `operator==` (which compares `low` / `high` as `uint64_t`) still returns the right answer: two values built by the same code produce identical bytes and therefore identical word values, regardless of the host byte order. `keyHolderPersistKey` previously rebound the arena-owned pointer with a direct `holder.key.high = ... | PackedStringRef::LARGE_TAG`, which is also value-semantic and would land the LARGE bit in the wrong byte on big-endian. Replace that with `setMediumPointer` / `setLargePointer` helpers on `PackedStringRef` that update the packed pointer and tag byte together using the same byte-stable path as `build`. Logs of the s390x build that motivated this change: https://s3.amazonaws.com/clickhouse-test-reports/PRs/93271/ec1195d752eea662a6caed4b401d749d0e70751b/build_s390x/build_clickhouse/build_clickhouse.log Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The aggregation-variant guard in `buildPlannerContext` used `major < min_major && minor < min_minor`, which is not a lexicographic version comparison. For an initiator on `25.6` and `min = 26.5` the expression evaluates to `true && false`, so two-level aggregation is not disabled on secondary queries in the planner path, allowing the very cross-version mismatch this guard is meant to prevent. Switch to `std::forward_as_tuple` ordering, matching the comparison already used in `InterpreterSelectQuery::initSettings`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The explanatory comment still referenced revision `54484`, but `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` was bumped to `54485` earlier in this PR. Update the comment so the test rationale matches the actual compatibility guard. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The TSan stateless runs failed on `query_43` (`SELECT URL FROM test.hits WHERE URL LIKE '%yandex%' ORDER BY URL DESC`) because the runtime dataflow output-bytes estimate `RuntimeDataflowStatisticsOutputBytes` is sensitive to the block size. CI's randomization diagnosis isolated `--max_block_size 30152` as the sole culprit: the estimate dropped to ~25-29M against the expected `82404720`, exceeding the 2.5x tolerance, while runs without randomization passed 4/4. Pin `max_block_size` to its default (`65409`), mirroring the existing `max_threads` override, so the estimate stays stable against the randomized settings. CI report: ClickHouse#93271 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`ZeroTraits::set` only cleared `high`, leaving `low` with whatever byte pattern the uninitialized zero-cell storage happened to hold. Since `getHash` reads the low word, a stored empty key could report a non-zero hash and be placed in a different two-level bucket from subsequent empty keys during `convertToTwoLevel`, splitting one empty-string group across buckets. Set both words to zero, matching the documented invariant that an empty `PackedStringRef` is all-zero bytes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review: the server-side checks in `InterpreterSelectQuery::initSettings` and `buildPlannerContext` compared only `connection_client_version_major` / `connection_client_version_minor` against the cutover version. The `PackedStringHashTable` aggregation method changes the bucketing of `key_string` within a single release (both pre- and post-change servers report the same `major.minor`), so a rolling upgrade from a pre-change initiator to a post-change replica left the major/minor comparison false and two-level aggregation enabled, producing the cross-version partial-aggregation mismatch the revision bump is meant to prevent. Compare `connection_tcp_protocol_version` against `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` instead, which is precisely the revision that distinguishes the two methods and mirrors the initiator-side checks in `MultiplexedConnections` and `HedgedConnections`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After switching the secondary-query checks to compare protocol revision, `DBMS_MIN_MAJOR_VERSION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` and `DBMS_MIN_MINOR_VERSION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` have no remaining users. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`HashMethodPackedString` precomputes a 32-bit hash for every row before emplacing. For string keys shorter than 8 bytes it went through `StringViewHash`, whose `hashLessThan8` path is a multiply-heavy CityHash mix. In low-cardinality short-string aggregation (`group_by_sundy_li`, `if_transform_strings_to_enum`) the consecutive-key cache makes the emplace pass nearly free, so this upfront hashing pass dominates the runtime and caused the documented regressions. Hash 1..7 byte keys with a single CRC instruction over the masked word, exactly as `StringHashTableHash` does for `StringKey8`. Keys of 8 bytes or more already use the cheap CRC loop inside `StringViewHash` and are left untouched, so medium and large keys (for example URLs) keep the same hash and bucketing, preserving the existing improvements. The 8-byte load from the key start is safe because `ColumnString::Chars` is a `PaddedPODArray` with at least 15 bytes of right padding, and trailing bytes beyond the key length are masked off so the hash depends only on the key content. Aggregation results are unaffected: small `PackedStringRef` keys compare on their inlined content, not on the hash. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `arm_tidy` build failed on the newly added tiny-key CRC hashing path: - `bugprone-suspicious-stringview-data-usage` on `str.data()`: reading 8 bytes from the key start is intentional and safe (`ColumnString::Chars` is a `PaddedPODArray` with right padding), so annotate with `NOLINT`. - `cppcoreguidelines-init-variables` on `UInt64 word`: initialize it. Also fix correctness on big-endian: `CRC_INT` is defined on s390x, where `memcpy` places a 1..7 byte key in the high bytes of `word`, so the trailing-byte mask must shift left instead of right (mirroring `StringHashTable`). Masking the wrong end folded neighbouring padding bytes into the hash, which is stored in `PackedStringRef::low` and gates `operator==`, and could split a single tiny key into several groups. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ytes_estimation` The aggregation-state size estimate checked by this test is recorded per bucket after the conversion to a two-level hash table. The test randomization can set `group_by_two_level_threshold` and `group_by_two_level_threshold_bytes` as low as 1, forcing the conversion from the very first block, which inflates the recorded estimate for `query_28` to ~59.4M against the expected 23722663 (ratio 2.50x, just over the 2.5x test threshold). Pin both thresholds to their defaults, continuing the test's established pinning pattern (`max_threads`, `max_block_size`). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93271&sha=89902268b9cfacc37dbfeb9871d0d4e18a2ecfb7&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29 PR: ClickHouse#93271 Co-Authored-By: Claude Fable 5 <[email protected]>
… in `HashMethodPackedString`
`master` removed the `WeakHash32` class, `WeakHash.h`/`WeakHash.cpp` and
`IColumn::getWeakHash32` in `5098d93e3ab` ("Add non-allocating
`IColumn::computeHashInto` hash kernel"), so the build broke with
`error: unknown type name 'WeakHash32'` at `HashMethod.h:243` (Fast test
and `Build (arm_tidy)`).
`HashMethodPackedString` only used `WeakHash32` as a thin wrapper around a
`PaddedPODArray<UInt32>` to store the precomputed per-row 32-bit hashes, so
store the hashes directly in a `PaddedPODArray<UInt32>` instead — the same
container the remaining scatter consumers now use after the kernel split.
The custom per-row hashing (tiny-key CRC, `StringViewHash`, length-based
fallback) is unchanged, so bucketing and correctness are preserved.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The latest `master` merge advanced `DBMS_TCP_PROTOCOL_VERSION` to `54486` for `DBMS_MIN_PROTOCOL_VERSION_WITH_INTERNAL_QUERY_FLAG` (from the `log-internal-secondary-queries` change). This PR previously used `54486` as the next-free revision for `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`, so after the merge both the PR's guard and master's unrelated feature shared `54486`, and the branch no longer advanced the wire protocol past `master`. That is incorrect: a stock `54486` server does not have the `PackedStringRef`-based aggregation-variant selection, yet the guard `revision < DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` would treat it as new, re-enabling two-level aggregation across incompatible servers. Move this PR to the next free revision `54487` for both `DBMS_TCP_PROTOCOL_VERSION` and `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`, and update the reference in `test_string_aggregation_compatibility`.
Address review feedback: the existing cross-version cases group by `(id, s2)` where `s2` is `LowCardinality(String)`, so aggregation goes through the multi-key serialized path and never exercises the code this PR changes. `PackedStringRef` replaces the single-`String` `key_string` / `key_string_two_level` variants. Add `test_single_string_key_aggregation_compatibility`, which groups by a single plain `String` key under forced two-level aggregation (`group_by_two_level_threshold = 1`) across a new server and an old (25.6) server. The key column mixes inline keys (<= 11 bytes, fully packed into `PackedStringRef`) with non-inline keys (> 11 bytes, out-of-line), covering both representations. Correct cross-version aggregation must deduplicate the 1000 distinct keys to 1000; a bucketing mismatch between versions would inflate the count. The legacy in-memory serialization scenario (`serialize_string_in_memory_with_zero_byte = 0`) is covered too.
…ash inline The packed-string path lost to `StringHashTable` on low-cardinality single-`String` aggregation (`group_by_sundy_li`, `if_transform_strings_to_enum`) for three reasons: a per-block hash pre-pass in `HashMethodPackedString` (a second pass over the string data plus an allocation per block), a store-to-load-forwarding stall in `PackedStringRef::build` (byte-offset stores immediately reloaded as two 64-bit words, with the variable-length inline payload copy compiling into a libc `memcpy` call per row), and `operator==` re-deriving kind, pointer and length through byte-offset accessors. On little-endian targets `build` now composes `low`/`high` entirely in registers from two masked word loads (`ColumnString::Chars` padding makes this safe - the same guarantee `hashTinyKey` already relies on), the hash is computed inline through a templated functor with unchanged hash values, and `operator==` decides everything from the two words already in registers. Big-endian keeps the byte-wise path. Co-authored-by: Cursor <[email protected]>
|
Workflow [PR], commit [41c1890] Summary: ✅
AI ReviewSummaryThis PR replaces the single- Final Verdict
|
|
Re: the low-cardinality regression flagged in #93271 (comment) (perf report: Confirmed and fixed. I reproduced the regression locally, root-caused it with Reproduction
Root causes (from instruction-level profiles)
At low cardinality the table is L1-resident and none of the design's benefits (prefetching, capacity prediction, compact cells at scale) engage, so this per-row overhead was the entire regression; it grows with row count, which is why the perf report flagged exactly the low-cardinality tests. Fix
Unit tests added for the byte layout, embedded/trailing zero bytes, boundary lengths and crafted collisions ( Perf-test queries from the report, re-run locally (base / before / after)Regressions:
(The gap between CI numbers and "before" is the earlier Improvements are preserved:
The residual ~7-9% on the pathological 4-group case is the cost of the uniform 24-byte cell versus |
|
@alexey-milovidov I've taken over #93271 (now closed) and this PR supersedes it. Added you as assignee/reviewer since you were actively reviewing the original. feel free to point me to other reviewers if you don't have the bandwidth. |
…tringRef test The copy in `EqualityMedium` is intentional: the test needs a second buffer with identical content to exercise the content-comparison path of `PackedStringRef::operator==`. Construct it from (data, size) instead of the copy constructor so the intent stays explicit and clang-tidy does not flag it. Fixes the only failing check on the PR head, Build (arm_tidy): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110573&sha=ede4a5d5ecec044dde2512d76aab5fac92857624&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#110573 Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 232/238 (97.48%) · Uncovered code |
|
Thanks for taking this over! I'm curious, how did you manage to resolve the issue I ran into previously? #93271 (comment) (Sorry, I completely missed your earlier review) |
|
Your finding is still valid. The fix (
The remaining 12..24 B residual is the representational half of your "decoding overhead": |
|
Why did we put it on hold? I think the changes are really good! |
alexey-milovidov
left a comment
There was a problem hiding this comment.
All good, I like it.
|
It shouldn't be on hold. |
…egation` The aggregation method for a single `String` key now follows the setting, but a peer that predates it always uses the packed method (`ClickHouse#110573`), so it cannot follow a query that disables it, and two-level bucket exchange between such servers would split the same key into different buckets. Bump `DBMS_TCP_PROTOCOL_VERSION` to 54489 and `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD` with it, so peers below it fail closed: the initiator zeroes the two-level thresholds for them and re-buckets their single-level blocks itself. The pre-change 26.8 peer cannot be pinned in the integration test (that state existed only as a master snapshot, no released image has it); the 25.6 node exercises the same fenced path for both setting values. Addresses review thread: ClickHouse#112089 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
…mment Measured with pre-built CI binaries against the `hits_v1` dataset under the test's pinned settings: master produced ~57..58 MB for `query_28` continuously since at least 2026-04-01 (2026-04-01: 57.3 MB, 2026-06-10: 57.8 MB, 2026-07-26 just before the merge of #110573: 57.0 MB, current master: 58.2 MB), so nothing regressed in the aggregation or statistics path around the failure. The recorded 23722663 was calibrated on 2025-12-31 on the branch of #93271 and carried unchanged into #110573, whose merge also overwrote the value master had been green with since February, 31064320 (ratio ~1.85 against the actual ~58 MB, which is why master stayed green until the merge). The final head of #93271 (before the `HashMethodPackedString` simplification) measures 58.4 MB as well, so the pull request itself does not change the estimate. With `group_by_two_level_threshold=1` the current estimate is 58170420 vs 58237072 at the pinned defaults, i.e. the threshold no longer affects this value. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=5baed0f5a10c333cd220b9646d6ef4647425079d&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 Co-Authored-By: Claude Fable 5 <[email protected]>
ClickHouse#110573 replaced the single-`String` `GROUP BY` key path with `PackedStringRef`-keyed hash tables. This is faster on average, but structurally slower for very low cardinality `GROUP BY` with keys longer than the 11-byte inline capacity: the legacy `StringHashTable` keeps keys of up to 24 bytes inline in the cell, while `PackedStringRef` dereferences an arena pointer on every probe. Measured on a cardinality-4 `GROUP BY` over 400M rows (ARM, 96 cores): +6..8% for keys <= 11 bytes, +14..19% for 12..24 bytes, +7% for 25..48 bytes (ClickHouse#110573 (comment)). Add a setting to switch between the two methods, default `true` (packed): - The legacy method is restored as the `key_string` / `key_string_two_level` variants, and the packed method is renamed to `key_packed_string` / `key_packed_string_two_level`. `chooseMethod` stays settings-blind and returns the packed type; the `Aggregator` constructor remaps it to `key_string` when `Params::enable_packed_string_keys` is false. - The flag is threaded through both `Aggregator::Params` constructors. The merge-only constructor needs it because `GroupingAggregatedTransform` calls `convertBlockToTwoLevel` on the initiator, and two-level bucket numbers depend on the key hash, which differs between the methods. - `SettingsChangesHistory` records `previous_value = false`, so `compatibility` with versions before 26.8 selects the legacy method, restoring pre-26.8 behavior including its two-level bucketing. - The setting is mirrored in `QueryPlanSerializationSettings` and serialized by `AggregatingStep` / `MergingAggregatedStep` for distributed serialized plans. - `LIMIT BY` also uses `AggregatedDataVariants::chooseMethod`, but only for transform-local hash tables, so it intentionally stays on the packed method. Tests: a trace-log check that the setting and `compatibility` switch the method; an identical-results matrix across both methods, one-level/two-level, external aggregation and distributed memory-efficient two-level aggregation, plus `Nullable(String)` / `LowCardinality(String)` keys; an integration test for distributed two-level aggregation with the setting disabled, including against a 25.6 server that does not know the setting; and a performance test covering the low-cardinality regression shape (4 distinct keys of 8/16/24/32 bytes). Related: ClickHouse#110573 Co-Authored-By: Claude Fable 5 <[email protected]>
…tringRef test The copy in `EqualityMedium` is intentional: the test needs a second buffer with identical content to exercise the content-comparison path of `PackedStringRef::operator==`. Construct it from (data, size) instead of the copy constructor so the intent stays explicit and clang-tidy does not flag it. Fixes the only failing check on the PR head, Build (arm_tidy): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110573&sha=ede4a5d5ecec044dde2512d76aab5fac92857624&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#110573 Co-Authored-By: Claude Fable 5 <[email protected]>
…g-ref Introduce PackedStringRef & PackedStringHashTable
This PR introduces
PackedStringRefandPackedStringHashTable, a compact string key representation and a corresponding hash table implementation, primarily targeting string-heavy aggregation workloads. This is part of #81944.In the past we introduced
StringHashTable#5417 to optimize small string keys. Since then, ClickHouse has continued to evolve and gained more hash table–level optimizations, such as better capacity prediction, prefetching, and more specialized fast paths. These optimizations are generally designed around a single, uniform hash table layout and access pattern. As a result, it has become increasingly difficult to integrateStringHashTablecleanly with them. Some optimizations, such as consecutive key handling, were already awkward withStringHashTable, and the situation has only become more complex as more logic has been added around hash tables.Instead of pushing
StringHashTablefurther, this change moves the optimization to the string representation itself.PackedStringRefencodes small, medium, and large strings into a fixed 16-byte object, storing short strings inline while using tagged pointers for longer strings. Small strings of up to 11 bytes are fully inlined, which already covers a large portion of real-world string keys (such as tags, short identifiers, and common dimension values), making this optimization effective even with a relatively conservative inline threshold.PackedStringHashTableis built around this representation and fits naturally into the existing optimization framework, including prefetching and capacity prediction.At the moment this is only wired for aggregate string keys. Other usages of
StringHashTableare left unchanged. If this approach proves effective, it can be gradually extended to more places and may eventually replaceStringHashTable.No dedicated perf test is added in this PR. Any noticeable regression or improvement should already be covered by existing aggregation-related performance tests in CI.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Introduces
PackedStringRef, a compact 16-byte representation for single-Stringaggregation keys, to reduce hash-table cell size and improve string-heavyGROUP BYworkloads. The change is limited to aggregate string keys; otherStringHashTableusers are unchanged.Documentation entry for user-facing changes
Version info
26.8.1.144(included in26.8and later)