Skip to content

Introduce PackedStringRef & PackedStringHashTable - #110573

Merged
alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-ref
Jul 26, 2026
Merged

alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-ref

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces PackedStringRef and PackedStringHashTable, 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 integrate StringHashTable cleanly with them. Some optimizations, such as consecutive key handling, were already awkward with StringHashTable, and the situation has only become more complex as more logic has been added around hash tables.

Instead of pushing StringHashTable further, this change moves the optimization to the string representation itself. PackedStringRef encodes 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.

copied-2025-12-31-16_51_22_144

PackedStringHashTable is 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 StringHashTable are left unchanged. If this approach proves effective, it can be gradually extended to more places and may eventually replace StringHashTable.

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):

  • Performance Improvement

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

Introduces PackedStringRef, a compact 16-byte representation for single-String aggregation keys, to reduce hash-table cell size and improve string-heavy GROUP BY workloads. The change is limited to aggregate string keys; other StringHashTable users are unchanged.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.144 (included in 26.8 and later)

amosbird and others added 22 commits July 15, 2026 11:02
`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]>
@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Jul 15, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

Supersedes #93271, original work by @amosbird

@harikrishnan94 harikrishnan94 added the pr-performance Pull request with some performance improvements label Jul 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [41c1890]

Summary: ✅


AI Review

Summary

This PR replaces the single-String aggregation path with PackedStringRef-backed hash tables, adds the protocol-revision guard that disables incompatible two-level aggregation during rolling upgrades, and adds focused unit/integration coverage for the new packed-key path. After reviewing the current diff, the prior inline thread, the compatibility tests, and the posted performance evidence, I did not find any remaining correctness, compatibility, or evidence gaps that justify a new review finding on the current head.

Final Verdict
  • Status: ✅ Approve

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

Re: the low-cardinality regression flagged in #93271 (comment) (perf report: group_by_sundy_li, if_transform_strings_to_enum).

Confirmed and fixed. I reproduced the regression locally, root-caused it with perf, and pushed a fix in 819b694. Summary below.

Reproduction

group_by_sundy_li-style table (d Date, os String, n UInt64, 4 partitions), scaled to 1.12B rows / 21 GB so the query runs long enough to profile, 4 distinct keys, SELECT os, count() FROM a GROUP BY os, medians over 24 order-swapped runs on ARM (96 cores):

key length pre-PR (StringHashTable) PR before fix PR after fix
2 bytes (inline path) 75 ms 176 ms (2.35x) 82 ms (1.09x)
25..48 bytes (pointer path) 188 ms 297 ms (1.65x) 202 ms (1.07x)

Root causes (from instruction-level profiles)

  1. A per-block hashing pre-pass. The HashMethodPackedString constructor hashed every row of the block into a PaddedPODArray before aggregation started: a second pass over all string data plus an allocation per block (8-18% of query runtime depending on key length).
  2. A store-to-load-forwarding stall on every probe. PackedStringRef::build assembled the value through byte-offset stores into a stack object; the caller immediately reloaded it as two UInt64 words. The reload overlaps several smaller stores, which defeats store-to-load forwarding — 43% of the aggregation loop samples piled up on the single instruction consuming that load. The variable-length inline payload copy (1..11 bytes) also compiled into a libc memcpy call per row.
  3. Branchy comparison. After the two word compares, operator== re-derived kind, pointer and length through isMedium/isLarge accessor chains and byte-offset re-loads before reaching memequalWide.

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

  • build now composes low/high entirely in registers on little-endian targets, reading the payload with two masked word loads (ColumnString::Chars padding makes this safe — the same guarantee hashTinyKey already relies on). No stores, no memcpy call, no stack round-trip. Big-endian keeps the byte-wise path.
  • build takes a templated hash functor and computes the hash inline, so string data is read once while hot; the pre-pass and its per-block allocation are gone. Hash values are unchanged, so two-level bucketing and the protocol-revision guard are unaffected. When the Aggregator prefetch pipeline is active, the look-ahead getKeyHolder hashes a second time — the same behaviour as the StringHashTable prefetch path this replaces, and invisible next to the cache misses that regime is dominated by (verified below).
  • operator== decides everything from the two words already in registers: one tag comparison, then a single memequalWide shared by medium and large.

Unit tests added for the byte layout, embedded/trailing zero bytes, boundary lengths and crafted collisions (gtest_packed_string_ref.cpp). Aggregation results are byte-identical to pre-PR master on all datasets tested, including a 50M-group mixed-length two-level checksum.

Perf-test queries from the report, re-run locally (base / before / after)

Regressions:

query CI (arm) pre-PR before after
group_by_sundy_li #1 +167.9% 9 ms 12 ms 9 ms
if_transform_strings_to_enum #1 (transform, numbers(1e8)) +162.0% 632 ms 1416 ms 664 ms
if_transform_strings_to_enum #0 (hits_100m_single) +23.5% 81 ms 90 ms 83 ms

(The gap between CI numbers and "before" is the earlier hashTinyKey commit, which had already removed part of the regression.) The remaining flagged entries (group_by_fixed_keys, removing_group_by_keys, set_index, aggregation_in_order_2, queries_over_aggregation, limit_by_with_order) are numeric-key or SetVariants paths this PR does not touch; all of them measure flat across the three binaries locally, so they look like threshold noise in that report.

Improvements are preserved:

query CI (arm) pre-PR before after
clickbench #12 (SearchPhrase) -19.4% 72 ms 64 ms 64 ms
clickbench #34 (1, URL) -15.3% 336 ms 292 ms 291 ms
sparse_column_filter (GROUP BY str) -15..-24% — -16..-20% -16..-20%
high-cardinality sanity, 50M groups / 1B rows, prefetch active: short keys — 0.90 s 0.91 s 0.90 s
same, ~19-byte keys — 2.78 s 2.55 s 2.53 s

The residual ~7-9% on the pathological 4-group case is the cost of the uniform 24-byte cell versus StringHashTable's specialized sub-tables; given the wins everywhere else I think that is an acceptable trade-off, but a fresh perf CI run will give the definitive picture.

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@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.
cc @rschu1ze

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 54.50% 85.90% +31.40%
Functions 61.30% 92.70% +31.40%
Branches 43.30% 78.10% +34.80%

Changed lines: Changed C/C++ lines covered: 232/238 (97.48%) · Uncovered code

Full report · Diff report

@amosbird

Copy link
Copy Markdown
Collaborator

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)

harikrishnan94 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Your finding is still valid. The fix (819b69423bb, detailed in my comment above) removed the artifactual overhead - the per-block hash pre-pass, a store-to-load-forwarding stall in build, and the branchy compare - which reduced the magnitude a lot, but a residual is still visible exactly in the band you measured. Cardinality-4 GROUP BY, 400M rows, vs pre-PR StringHashTable (ARM, 96 cores):

key length PR before fix PR after fix
≤11 B (inline) +56..60% +6..8%
12..24 B +63..93% +14..19%
25..48 B +65% +7%

The remaining 12..24 B residual is the representational half of your "decoding overhead": StringKey16/StringKey24 keep those keys inline in the cell, while PackedStringRef (11-byte inline cap) dereferences an arena pointer on every probe.

@alexey-milovidov

Copy link
Copy Markdown
Member

Why did we put it on hold? I think the changes are really good!

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All good, I like it.

@alexey-milovidov alexey-milovidov removed the hold Skip for auto-updating. label Jul 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

It shouldn't be on hold.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 26, 2026
Merged via the queue into ClickHouse:master with commit b59441b Jul 26, 2026
176 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 26, 2026
@harikrishnan94
harikrishnan94 deleted the packed-string-ref branch July 26, 2026 04:59
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jul 27, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
…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]>
pull Bot pushed a commit to infdahai/ClickHouse that referenced this pull request Aug 7, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…g-ref

Introduce PackedStringRef & PackedStringHashTable
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 pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants