Repository navigation
Add setting enable_packed_string_keys_in_aggregation - #112089
Conversation
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]>
- Tag the stateless test 04649 with `shard` (it queries `127.0.0.{1,2}`),
so it is skipped instead of failing on servers not listening there.
- Correct the key-length range in its comment (the maximum is 62 bytes,
not 63) and stop overclaiming `convertBlockToTwoLevel` coverage: with
`group_by_two_level_threshold = 1` both shards emit only bucketed
chunks, so the initiator's single-level split path is exercised by the
integration test, not by this query.
- Name the legacy method `StringHashTable`-based consistently and
backtick the type names in the settings-history entry.
- Deduplicate the method-remap comment; the rationale lives in the
setting description.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [9cea7b7] Summary: ✅
AI ReviewSummaryThis PR adds Findings
Final VerdictNeeds changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 309/313 (98.72%) · Uncovered code |
…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]>
…ostfix # Conflicts: # src/Interpreters/Aggregator.cpp # src/Interpreters/Aggregator.h # src/Interpreters/InterpreterSelectQuery.cpp # src/Planner/Planner.cpp # src/Processors/QueryPlan/AggregatingStep.cpp # src/Processors/QueryPlan/QueryPlanSerializationSettings.cpp # src/Processors/Sources/LazyReadReplacingFinalSource.cpp # src/Processors/TTL/TTLAggregationAlgorithm.cpp
…ostfix # Conflicts: # src/Interpreters/Aggregator.cpp # src/Interpreters/Aggregator.h # src/Interpreters/InterpreterSelectQuery.cpp # src/Planner/Planner.cpp # src/Processors/QueryPlan/AggregatingStep.cpp # src/Processors/QueryPlan/QueryPlanSerializationSettings.cpp # src/Processors/Sources/LazyReadReplacingFinalSource.cpp # src/Processors/TTL/TTLAggregationAlgorithm.cpp
…od is used `QueryPlanSerializationSettings` is a strict named schema: `writeChangedBinary` writes every touched entry by name and `readBinary` throws on a name it does not know. Because `AggregatingStep::serializeSettings` and `MergingAggregatedStep::serializeSettings` assigned `enable_packed_string_keys_in_aggregation` unconditionally, and an assignment marks the entry changed regardless of the value, every serialized aggregation plan carried the new name - so a peer that predates the setting (any revision in `54477..54488`, which can already receive a serialized plan) would reject the plan outright, even for a query that does not group by `String`. Write the entry only when the legacy method is requested. A default plan then carries nothing new and stays readable by such a peer, while an explicit `false` fails closed on a peer too old to know the name instead of silently aggregating with the other method. Also pass the new `Aggregator::Params` argument in `gtest_aggregator_parallel_partition_merge`, which arrived on `master` after this branch.
…tfix' into packed-string-ref-postfix # Conflicts: # src/Processors/QueryPlan/AggregatingStep.cpp
… affect `QueryPlanSerializationSettings` is a strict named schema: `writeChangedBinary` writes every touched entry by name and `readBinary` throws on a name it does not know, so a peer that predates a setting rejects any plan carrying it. Gating the write on the session setting alone still put the name on the wire for every serialized aggregation step whenever the legacy method was requested - including `count()`, `GROUP BY UInt64`, `Nullable(String)` and `LowCardinality(String)` plans, where the single-`String` method is unreachable and the setting cannot change anything. A `54477..54488` peer rejected those otherwise-safe plans. `aggregationCanUsePackedStringKeys` now asks `AggregatedDataVariants::chooseMethod` whether the step - or, with grouping sets, any of its per-set aggregators - would pick `key_packed_string` at all, and only then is the entry written, in both `AggregatingStep::serializeSettings` and `MergingAggregatedStep::serializeSettings`. When a key cannot be resolved from the step's input header the predicate errs towards writing the entry, so a receiver is never left guessing the method. Added `gtest_packed_string_keys_plan_setting` covering both steps: the entry appears on the wire only for a single non-nullable, non-`LowCardinality` `String` key with the legacy method requested, and for a grouping-set step only when some set groups by exactly one such key. Address review: ClickHouse#112089
|
@groeneai Why are tests failing? |
|
One check of 174 is red, and it is a known trunk bug rather than anything from this PR.
That is the It reproduces on master independently of any PR: over the last 45 days that source line accounts for 127 failures, 118 of them on 107 distinct pull requests and 9 on MasterCI across 9 distinct master commits (most recent 2026-07-28). Your 27 changed files are aggregation method selection, plan serialization and tests, so none of them reaches a datetime function. The |
|
🕵 The trunk Verified after the merge: all touched translation units still compile against current |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 246/246 (100.00%) · Uncovered code |
|
@groeneai Make this PR mergeable. |
|
I checked what is actually blocking merge, and it is neither a conflict nor a review thread.
I confirmed that rather than assuming it. Across the 50 most recently updated open PRs, combined commit-status state and
On the remaining bot change request, its citations are accurate, but I would not treat it as a merge blocker:
Its closing line, that the same issue exists in So there is nothing in the diff I would change to unblock this. If you want the general peer-version gating for plan settings, that deserves its own PR against the serialization interface, and I am happy to open it and reference this one. |
|
@harikrishnan94, it was a conflict in the private repository around a new setting for Distributed Cache. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR makes PackedStringRef the default aggregation method for single non-nullable String key GROUP BY, and all three flagged clickbench queries (Q32 +18.4%, Q33 +7.4%, Q34 +7.8%) exercise exactly that path. The regressions are small but consistent, and CPU time rose alongside the medians, matching the PR's own documented case where the packed table can be slower than the legacy method for longer string keys. The two envelope-suppressed rows (Q32, Q34) fall inside master's current variance band, but because they are on-path and work-backed we've surfaced them for confirmation rather than leaving them hidden; Q33 is borderline with mixed signals from the two tests. Worth a targeted re-run on these string GROUP BY queries before merge to confirm the trend is stable. clickbenchFlagged queries (3 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
|
`AggregatingStep::serializeSettings` writes `enable_packed_string_keys_in_aggregation` only when the legacy method is requested and the step can actually choose the single-`String` method, so a peer in `54477..54488` rejects exactly those plans whose method choice it cannot follow. Automated review keeps proposing to drop that write, on the grounds that `MultiplexedConnections::sendQuery` / `HedgedConnections::sendQuery` already zero the two-level thresholds for such a peer, which would make the method choice inconsequential. That fence does not reach a serialized plan: a deserialized `AggregatingStep` takes `group_by_two_level_threshold` and `group_by_two_level_threshold_bytes` from the plan's own `QueryPlanSerializationSettings`, written from the initiator's unmodified `params`, not from the `Settings` sent with the query. Under `serialize_query_plan = 1` the peer can therefore still go two-level, and two-level bucket numbering differs between the two methods, which corrupts memory-efficient distributed merging. Record that reasoning next to the gate.
|
🕵 Pushed On the remaining bot blocker (replied in detail on the thread): its premise does not hold for the path it is about. The two-level fence in I prototyped the alternative the verdict asks for (carry the choice in the step's On Verified after the merge: |
…` into plans that cannot go two-level When both serialized two-level thresholds are 0, the receiving peer can never produce a two-level aggregation state: `worthConvertToTwoLevel` is false for any size (including the size-hint path), the external group-by spill additionally requires it, and `Aggregator::mergeVariants` converts only when some variant is two-level already. The step then only produces single-level blocks, whose rows and serialized aggregate states do not depend on the hash-table method, so a method mismatch is unobservable and an old plan-serialization peer may safely run the plan with its default method. Skip writing the setting in `AggregatingStep::serializeSettings` in that case. `MergingAggregatedStep` keeps the unnarrowed gate even for non-memory-efficient merging: `Aggregator::mergeBlocks` inserts bucketed input chunks under the producer's bucket number but re-buckets single-level chunks by the local method's hash, so with legitimately mixed inputs a merging peer on the other method splits one key across two sub-tables and returns it twice. Whether the input can be bucketed is a property of the producing steps' thresholds, which this step's merge params do not carry. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Pushed two commits:
On the two red checks of
All review threads are resolved; the PR remains blocked only on a human merge. |
|
Investigated. A fix is already in progress and it is yours: #113011, open since 2026-08-02, test-only (+26/-8 on this one file). Nothing to add from me beyond confirming it. The failure has one signature, not several. Of the 6 CIDB records for this test in 30 days (3 distinct PRs, 0 on master with
Two things this rules out. It is not a timing window and not TSan-specific: the failing runs took 1.8s and 2.1s, so nothing was near a deadline, and the first occurrence was on an ASAN build with the 1M-row version of the test. It is also not a threshold straddle. Confirming the mechanism from source rather than restating the test's comment: a QCC entry is buffered only where #113011 fixes exactly that by putting On its CI: 57 success, 116 skipped, 1 failure of 174 at head Two smaller confirmations. Your "unrelated to this PR" call on #112089 holds from the file list: 29 files, none under the QCC, I am not opening a separate PR - that would duplicate #113011. Say the word if you would rather I take it over instead. |
…on-aware Bump `DBMS_QUERY_PLAN_SERIALIZATION_VERSION` to 5 and pass the negotiated stream version into `serializeSettings`. A peer at version 5 knows the setting name, so `AggregatingStep` and `MergingAggregatedStep` write the value to it whenever the legacy method is requested - the setting can no longer silently stop taking effect on remote aggregation under `serialize_query_plan = 1` (e.g. when both two-level thresholds are 0). Towards an older peer, which rejects the unknown name, the previous correctness-only fail-closed gates are kept. ClickHouse#112089 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Pushed two commits:
On the two red stress checks at the previous head (both unrelated to this PR, and a fresh CI run starts with this push):
|
|
@groeneai Why is this PR still unmergable? |
|
Two red CI jobs on the current head Measured on Why neither is yours:
Neither subsystem is reachable from this diff: no file under What clears it, and it does not need a new commit. Of the last 60 merged pull requests, 0 merged with a red Given a 37-PR chronic bug and a twice-in-90-days fuzzer finding, re-running those two jobs is worth trying first, with the override as the documented fallback. Both need a ClickHouse maintainer: I have |
|
🕵 Merged current The two red checks on the previous head
All review threads remain resolved and the AI review reports no new findings; the PR is blocked only on the new CI run and a human merge. |
|
🕵 Follow-up on the @groeneai, investigate the failure https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112089&sha=d94ecfbddffdb09ef5163efd9f2d5c9d0d1b916c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 and provide a fix in a separate PR — the tracking issue with the reproducer is #113664. If the fix is already in progress, link it here. |
|
Investigated. A fix is already in progress and it is yours: #112723, open since 2026-07-31. I built it and it closes the reproducer in #113664 completely, so I am not opening a separate PR. Two things you will want to know: your shape matrix has one arm wrong, and #110770 does not cover this. I reproduced #113664 verbatim on the pristine master debug snapshot ( Then I ported the source hunk of #112723 onto that same master HEAD (the ported hunk is byte-identical to yours,
The two diagonals are what matter. Each PR fixes its own route and neither touches the other's, which is expected from the diff sites: yours guards fragment capture in That also settles the coverage question I flagged in my earlier comment here. I said then that I did not claim #110770 covers this shape because its route needs the text-indexed column to be the partition key. That was right, and it is now measured rather than inferred: #110770 alone still aborts on your reproducer, and Your matrix's last row is optimistic. It records "any of the above ... with And it is broader than the bug you filed: with I also confirmed the CI failure you pointed me at is this bug and not a third route. The fuzzer's table is One practical note. #112723 is 1980 commits behind master and its For the ledger on this PR: Happy to open the Session id: cron:clickhouse-premium-slot-25:20260806-131502 |
…ing_keys_in_aggregation` The committed test arms only exercised query-level overrides via `extra_settings`, which are already in the changed set and reach the shard through the ordinary settings path - deleting the new `modified_settings.set(...)` calls in `MultiplexedConnections` and `HedgedConnections` would have left them green. The new arm discriminates the forced propagation: the initiator sits on the compiled-in default (unchanged, so the ordinary changed-settings serialization sends nothing), while the shard's own `default` profile disables the setting. The shard must execute the secondary query with the initiator's effective value, asserted via the shard-side `system.query_log`. The recorded value (not the key presence) is the oracle, because the shard's own profile default marks the setting changed locally either way.
|
🕵 Pushed two commits:
The 10 red jobs on the previous head |
| /// and the conversion in `Aggregator::mergeVariants` fires only when some variant is two-level already. The step | ||
| /// then only ever produces single-level blocks (`bucket_num = -1`), whose rows and serialized aggregate states do | ||
| /// not depend on the hash-table method, and every consumer merges them as a plain set-union by key. | ||
| if (!params.enable_packed_string_keys |
There was a problem hiding this comment.
serializeSettings is still treating "this plan can go two-level" as equivalent to "group_by_two_level_threshold or _bytes was non-zero in the session", but transformPipeline later zeros both thresholds whenever the remote step is guaranteed single-level. A concrete trace is serialize_query_plan = 1, enable_packed_string_keys_in_aggregation = 0, max_threads = 1 against a peer below DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PACKED_STRING_KEYS_SETTING: this branch emits the new setting because the stored thresholds are still the session defaults, the old peer rejects the unknown name, and yet the deserialized step would hit the single-level path at src/Processors/QueryPlan/AggregatingStep.cpp:401-421, where a packed-vs-legacy mismatch is unobservable. So the old-peer narrowing is still too broad and keeps throwing on a safe mixed-version path. Suggested fix: include the plan-time single-stream/single-level proofs in this gate as well (at least the max_threads = 1, no-external-spill case) and add a focused test for that pre-v5 serialized-plan path.
…tring_keys_` Master (#112089) added a trailing constructor parameter; pass `false` in `makeMergeParams` so the unit test compiles again. Co-Authored-By: Claude Fable 5 <[email protected]>
Follow-up to #110573. The packed method is a clear win on average, but it is structurally slower for very low cardinality
GROUP BYwith keys longer than the 11-byte inline capacity:StringHashTablekeeps keys of up to 24 bytes inline in the cell, whilePackedStringRefdereferences an arena pointer on every probe. Cardinality-4GROUP BY, 400M rows, ARM 96 cores: +6..8% for keys <= 11 bytes, +14..19% for 12..24 bytes, +7% for 25..48 bytes (#110573 (comment)).This adds
enable_packed_string_keys_in_aggregation(defaulttrue). When disabled, single-String-keyGROUP BYfalls back to the legacyStringHashTable-based method: the legacy variants are restored askey_string/key_string_two_level, the packed ones are renamed tokey_packed_string/key_packed_string_two_level, and theAggregatorconstructor remaps the method chosen by the settings-blindchooseMethod. The flag goes through bothAggregator::Paramsconstructors, the merge-only one included:GroupingAggregatedTransformcallsconvertBlockToTwoLevelon the initiator, and two-level bucket numbers depend on the key hash, which differs between the methods. It is also mirrored in the serialized query plan.compatibilitywith versions before 26.8 selects the legacy method (previous_value = falsein the settings-changes history), restoring pre-26.8 two-level bucketing as well.All servers of a distributed query must agree on the setting value for memory-efficient two-level merges; the setting description documents this. The value propagates with the query, and a 25.6 server receiving the unknown setting skips it with a warning (covered by the integration test). A peer that has the packed method but not the setting (a master snapshot between #110573 and this PR) cannot follow a query that disables it, so
DBMS_TCP_PROTOCOL_VERSIONandDBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHODare bumped to 54489: peers below it are fenced to single-level aggregation, which stays correct under the method mismatch.LIMIT BYalso usesAggregatedDataVariants::chooseMethod, but only for transform-local hash tables, so it stays on the packed method regardless of the setting. A new performance test covers the regression shape (4 distinct keys of 8/16/24/32 bytes); #110573 had no dedicated perf test for it.Related: #110573
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added setting
enable_packed_string_keys_in_aggregation(enabled by default). Disabling it restores the pre-26.8StringHashTable-based method forGROUP BYwith a singleStringkey, which can be faster for very low cardinality aggregation with keys longer than 11 bytes. Settingcompatibilityto a version before 26.8 also selects the legacy method.Version info
26.8.1.946(included in26.8and later)