Skip to content

Add setting enable_packed_string_keys_in_aggregation - #112089

Merged
harikrishnan94 merged 21 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-ref-postfix
Aug 7, 2026
Merged

harikrishnan94 merged 21 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-ref-postfix

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #110573. The packed method is a clear win on average, but it is structurally slower for very low cardinality GROUP BY with keys longer than the 11-byte inline capacity: StringHashTable keeps keys of up to 24 bytes inline in the cell, while PackedStringRef dereferences an arena pointer on every probe. Cardinality-4 GROUP 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 (default true). When disabled, single-String-key GROUP BY falls back to the legacy StringHashTable-based method: the legacy variants are restored as key_string/key_string_two_level, the packed ones are renamed to key_packed_string/key_packed_string_two_level, and the Aggregator constructor remaps the method chosen by the settings-blind chooseMethod. The flag goes through both Aggregator::Params constructors, the merge-only one included: GroupingAggregatedTransform calls convertBlockToTwoLevel on 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. compatibility with versions before 26.8 selects the legacy method (previous_value = false in 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_VERSION and DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD are bumped to 54489: peers below it are fenced to single-level aggregation, which stays correct under the method mismatch. LIMIT BY also uses AggregatedDataVariants::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):

  • Improvement

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.8 StringHashTable-based method for GROUP BY with a single String key, which can be faster for very low cardinality aggregation with keys longer than 11 bytes. Setting compatibility to a version before 26.8 also selects the legacy method.

Version info

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

harikrishnan94 and others added 2 commits July 27, 2026 11:57
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9cea7b7]

Summary: ✅


AI Review

Summary

This PR adds enable_packed_string_keys_in_aggregation, propagates it through distributed execution, and version-gates the serialized-plan setting so current peers can follow the initiator's choice. The remaining issue is a mixed-version serialized-plan compatibility hole: the old-peer omission logic still keys only off the configured two-level thresholds, so some plans that are guaranteed to execute single-level still fail on older peers for no correctness reason.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/AggregatingStep.cpp:1060] The old-peer gate still assumes that non-zero group_by_two_level_threshold / _bytes means the remote step can become two-level, but transformPipeline later zeros both thresholds whenever the step is guaranteed single-level. With serialize_query_plan = 1, enable_packed_string_keys_in_aggregation = 0, max_threads = 1, and a peer below DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PACKED_STRING_KEYS_SETTING, this code still emits the new setting and makes the peer throw on an unknown name, even though the deserialized step would execute single-level only and a packed-vs-legacy mismatch would be unobservable. Suggested fix: fold the plan-time single-level proofs into this gate as well (at least the max_threads = 1, no-external-spill case) and pin it with a focused pre-v5 serialized-plan test.
Final Verdict

Needs changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.60% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 309/313 (98.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 27, 2026
@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Jul 27, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…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]>
robot-clickhouse and others added 6 commits July 28, 2026 18:58
…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
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Why are tests failing?

@groeneai

Copy link
Copy Markdown
Collaborator

One check of 174 is red, and it is a known trunk bug rather than anything from this PR.

Stress test (arm_asan_ubsan, s3) reports a UBSan signed integer overflow at src/Functions/toStartOfInterval.cpp:293:

runtime error: signed integer overflow: -9223372036854775807 + -7200000000000 cannot be represented in type 'Int64'

That is the origin + offset addition in the origin overload of toStartOfInterval, which overflows for an extreme origin combined with a negative offset. Fixing PR: #112045 (@ alexey-milovidov, open), which guards that exact line with common::addOverflow.

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 01666_merge_tree_max_query_limit failure from an earlier head is already resolved: #112385 merged on 2026-07-29, and the fix is present in that test file at your current head but absent at the head that failed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112089&sha=4e11fb107e7842947557bda4d5e11eb0d07a9a44&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

@harikrishnan94
harikrishnan94 enabled auto-merge July 31, 2026 06:10
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The trunk toStartOfInterval UBSan overflow that caused the only red check has been fixed: #112045 merged into master today. I merged origin/master into this branch (2d4a933bd3d, clean merge, no conflicts) so the fix is pulled in and Stress test (arm_asan_ubsan, s3) should go green on the next run.

Verified after the merge: all touched translation units still compile against current master (including the new gtest_packed_string_keys_plan_setting), the DBMS_TCP_PROTOCOL_VERSION bump to 54489 does not collide with master (still at 54488), and the enable_packed_string_keys_in_aggregation entry is still in the current 26.8 block of SettingsChangesHistory.cpp. No unresolved review threads remain.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 246/246 (100.00%) · Uncovered code

Full report · Diff report

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Make this PR mergeable.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

I checked what is actually blocking merge, and it is neither a conflict nor a review thread.

mergeable is MERGEABLE and all 174 check-runs on 2d4a933bd3d are green (154 success, 20 skipped, zero failures). The only non-success item is the commit status context CH Inc sync, at state=pending, description=awaiting, posted 2026-07-31T22:33:37Z. That is what makes mergeStateStatus read BLOCKED.

I confirmed that rather than assuming it. Across the 50 most recently updated open PRs, combined commit-status state and mergeStateStatus agree with no counterexample either way: every CLEAN PR has combined status SUCCESS, and no BLOCKED one does. The same sample rules out the two obvious candidates:

  • The open bot thread is not the cause: 9 CLEAN PRs currently have unresolved threads, and more than 15 BLOCKED ones have zero.
  • The empty reviewDecision is not either: it reads null on the CLEAN PRs too. Your approval is still live, with no review_dismissed and no force-push on the PR.

CH Inc sync is a private-side sync that neither of us can drive from this repo. For calibration, on the last 32 merged PRs carrying it the latency after the head commit was median 4.6 h, p90 14.8 h, max 33.4 h. This PR is at about 9.6 h, so past the median but inside the normal range, and 11 other open PRs sit in the same state right now. It should clear on its own; otherwise it needs someone with private-side access.

On the remaining bot change request, its citations are accurate, but I would not treat it as a merge blocker:

  1. The fix it asks for is not expressible where it points. serializeSettings takes only QueryPlanSerializationSettings and has no peer or revision context, so "suppress the field when a peer is below 54489" cannot be decided there. It needs the peer revision threaded into plan-settings serialization, which is a change to the interface, not to this PR.
  2. It describes a pre-existing property of the schema. Of the 81 settings declared in QueryPlanSerializationSettings.cpp, zero are peer-version gated, and that translation unit holds no revision constant. The nearest precedent, enable_parallel_single_level_merge from Parallelize the final merge of single-level aggregation hash tables #110395 merged three days earlier, is written unconditionally at AggregatingStep.cpp:1025. Your write is strictly narrower, since writeChangedBinary transmits only touched entries and your guard limits that to the case where the step can actually pick the single-String method.

Its closing line, that the same issue exists in MergingAggregatedStep::serializeSettings, is already addressed: that guard is at MergingAggregatedStep.cpp:223-225 and matches the one in AggregatingStep.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

@harikrishnan94, it was a conflict in the private repository around a new setting for Distributed Cache.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 1308 1548 +18.4% 0.0040 aggregation: Single-String-key GROUP BY is exactly the path this PR switches to the PackedStringRef method; CPU work rose with the median, so +18.4% reads as a real method-change cost, not noise.
⚠️ 33 not_sure 1238 1329 +7.4% 0.0026 aggregation: Single-String-key GROUP BY on the changed aggregation path; borderline with mixed test signals, but the +7.4% direction matches the packed-method slowdown the PR itself warns about.
⚠️ 34 not_sure 1230 1326 +7.8% 0.0001 aggregation: Same single-String-key GROUP BY path as the new packed method; CPU also rose, so +7.8% is plausibly the packed table dereferencing the arena on longer keys.

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
  • StressHouse run: 5d3f60f2-b5aa-4ab3-ab58-5f923214df2b
  • MIRAI run: e1a63f03-a5f0-4f98-976c-2d2860302a38
  • PR check IDs:
    • clickbench_148203_1786097546
    • clickbench_148232_1786097548
    • clickbench_148433_1786097660
    • tpch_adapted_1_official_148534_1786097669
    • tpch_adapted_1_official_148548_1786097669
    • tpch_adapted_1_official_148752_1786097697

`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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 25331df — merged current master (782 commits, clean, no conflicts) and recorded, next to the plan-serialization gate, why it fails closed.

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 MultiplexedConnections::sendQuery / HedgedConnections::sendQuery zeroes the thresholds in the Settings sent with the query, but a deserialized AggregatingStep takes group_by_two_level_threshold / group_by_two_level_threshold_bytes from the plan's own QueryPlanSerializationSettings, written from the initiator's unmodified params before sendQuery runs. So under serialize_query_plan = 1 a peer below 54489 is not forced onto single-level aggregation: it can go two-level with the method it chose itself, and two-level bucket numbering differs between the packed and the legacy method, which makes distributed_aggregation_memory_efficient merging split groups instead of merging them. The choice there is between an exception and silently wrong results, so the exception stays. Suppressing the field for old peers would produce exactly the wrong-results case.

I prototyped the alternative the verdict asks for (carry the choice in the step's flags byte, which an older peer ignores instead of rejecting) and it builds and round-trips, but it converts that combination from a clean error into wrong results, so I did not keep it.

On CH Inc sync: the previous run failed as tests failed (1 new, 4 known). All five are unrelated to aggregation — 03150_trace_log_add_build_id (MEMORY_LIMIT_EXCEEDED at 4.66 GiB in a debug build while running arrayExists over system.trace_log.symbols), 03100_lwu_42_bytes_limits, 03221_s3_imds_decent_timeout, a TSan Object A, creation_csn is not set while removal_csn is set to B, and a stress Test script failed. I reran the failed private jobs; the new head also gets a fresh sync PR. The private-side AI Review on that run is ✅ Approve ("I did not find a remaining correctness, compatibility, or evidence gap in the current diff").

Verified after the merge: DBMS_TCP_PROTOCOL_VERSION is 54489 against master's 54488, the enable_packed_string_keys_in_aggregation entry is still in the current 26.8 block of SettingsChangesHistory.cpp, and all 16 touched translation units compile against current master.

…` 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed two commits:

  • 6b794d4566a — merged current master (clean, no conflicts). DBMS_TCP_PROTOCOL_VERSION 54489 still does not collide with master (54488), and the settings-history entry is still in the current 26.8 block.
  • 84e908100df — addressed the review finding about over-failing on mixed-version serialized plans, in half: AggregatingStep::serializeSettings no longer emits enable_packed_string_keys_in_aggregation when both serialized two-level thresholds are 0 (the receiver can then never build a two-level state, so a method mismatch is unobservable and an old peer may run the plan with its default method). The MergingAggregatedStep half of the suggestion is refuted on the thread: its non-memory-efficient merge re-buckets single-level input chunks by the local method's hash while keeping producer bucket numbers for two-level ones, so with legitimately mixed inputs a peer on the other method would return a key twice — and the step's merge params carry no thresholds to narrow on. Covered by a new case in gtest_packed_string_keys_plan_setting.cpp (all 5 tests pass locally).

On the two red checks of 884350bd2, both unrelated to this PR:

All review threads are resolved; the PR remains blocked only on a human merge.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

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 head_ref = 'master'), 3 are the pre-long-tag timeout mode from 2026-07-19 (180.5s, 180.5s, 196.5s against the 180s cap), closed by 3398759e88236d3, which reached master with #111492 on 2026-08-01. The other 3 are all the same one-line diff, -1 / +0 on the count() > 0 over system.query_condition_cache after the first ASC LIMIT 5, with every correctness assertion passing:

date check duration report
2026-07-27 Stateless (amd_asan_ubsan, flaky check) 95.9s report
2026-08-02 Stateless (amd_tsan, sequential, 2/2) 2.1s report
2026-08-04 Stateless (amd_tsan, sequential, 2/2) 1.8s report

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. SET max_threads = 1 already removes the multi-thread trajectory your comment suspected, which is why the remaining variance is purely in the data.

Confirming the mechanism from source rather than restating the test's comment: a QCC entry is buffered only where FilterTransform::transform sees num_filtered_rows == 0 (FilterTransform.cpp:314, plus the always_false path at :247), and the buffer is written out from prepare() on Status::Finished (:152). So if no chunk ever empties out completely, buffered_mark_ranges_info stays null and the flush at :369 returns without writing. With id = rand(), whether any chunk reaches zero surviving rows depended on where the five smallest w = 7 rows landed relative to the 8192-row chunk boundaries. That is a data-placement lottery, and it explains why replaying the same randomized settings passes 30/30: the settings vector is not the variable, the rand() layout is.

#113011 fixes exactly that by putting k <= 4007 at the front of the part and hashing the rest above the first chunk, so the threshold is armed at its final value after chunk 1 and every later chunk empties deterministically. I verified the fix marker is absent at all three failing shas and at current master, and present only on #113011's head, so none of the three runs could have contained it.

On its CI: 57 success, 116 skipped, 1 failure of 174 at head 9c9abd04, with both Stateless tests (amd_tsan, sequential, 1/2) and (2/2) green. The single red is Stress test (arm_tsan) with Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-3284) - the same #113165 family you attributed here, and #111997 is mine and still open, so that red cannot clear before it merges. The branch is 138 commits behind master.

Two smaller confirmations. Your "unrelated to this PR" call on #112089 holds from the file list: 29 files, none under the QCC, FilterTransform, ReadFromMergeTree or the TopK optimizer, so an aggregation-method setting cannot change which chunks empty at the WHERE filter. And your reading of #111492's 1M to 100k reduction as an amplifier rather than the cause checks out: the test file at the 2026-07-27 failing sha still had numbers(1_000_000), since 3398759e88236d3 was authored 2026-07-23 but only landed on master with that PR on 2026-08-01.

I am not opening a separate PR - that would duplicate #113011. Say the word if you would rather I take it over instead.

alexey-milovidov and others added 2 commits August 5, 2026 15:12
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed two commits:

  • cde27e4d4a9 — merged current master (497 commits, clean, no conflicts). DBMS_TCP_PROTOCOL_VERSION 54489 vs master's 54488 — no collision; the settings-history entry is still in the current 26.8 block.
  • d94ecfbddff — addressed the remaining AI-Review blocker (replied on the thread): enable_packed_string_keys_in_aggregation is now emitted into serialized plans version-aware. DBMS_QUERY_PLAN_SERIALIZATION_VERSION is bumped to 5 and serializeSettings receives the negotiated stream version, so a current peer always gets the value when the legacy method is requested — the setting can no longer silently stop taking effect on remote shards under serialize_query_plan = 1 (the both-thresholds-zero case) — while a pre-setting peer keeps the previous correctness-only fail-closed gates. unit_tests_dbms built and all 6 PackedStringKeysPlanSetting gtests pass.

On the two red stress checks at the previous head (both unrelated to this PR, and a fresh CI run starts with this push):

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Why is this PR still unmergable?

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

Two red CI jobs on the current head d94ecfbd, neither caused by this PR. The CH Inc sync blocker from my earlier answer has cleared, and all 6 review threads are resolved with 0 unresolved, so nothing is left in review and there is no conflict.

Measured on d94ecfbd via the paginated check-runs API: 174 checks, 153 success / 19 skipped / 2 failure. The only non-success commit statuses are Mergeable Check (Failed: Stress test (arm_debug),AST fuzzer (amd_debug)) and PR; CH Inc sync is success. Mergeable Check is written by Finish Workflow purely from the failed-job set (ci/praktika/native_jobs.py:1116), so it is red only because of those two.

Why neither is yours:

  • Stress test (arm_debug): STID 2508-2e0c, the getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs) assertion. The stack is entirely HashJoin, in IColumn::insertFrom under buildAdditionalFilter (src/Interpreters/HashJoin/HashJoinMethodsImpl.h:807); I counted 68 HashJoin frames and 0 mentioning aggregation, packed_string or chooseMethod. In the last 3 days that STID has 40 rows across 37 distinct pull requests plus 2 on master, across 5 Stress variants. Fix a mixed JOIN ON condition evaluated over mismatched column types for a dictionary #113534 is the fixing PR, and I verified its added check is absent from both this head and master, so this build predates it.
  • AST fuzzer (amd_debug): STID 3694-54bc, Query builder not found for text search query with function 'hasAllTokens', on SELECT id FROM tab__fuzz_43 PREWHERE hasAllTokens(s, '\0nlined') .... Text index path, no GROUP BY in the query. Exactly 2 occurrences in 90 days, the other on an unrelated PR. My Fix text index LOGICAL_ERROR with constant folding and partition key #110770 fixes one route into that message, but its route requires the text-indexed column to also be the partition key and this fuzzer table has no PARTITION BY, so I do not claim it covers this shape.

Neither subsystem is reachable from this diff: no file under src/Interpreters/HashJoin/, no text-index file, and 0 occurrences of HashJoin, buildAdditionalFilter, assertTypeEquality, hasAllTokens or PREWHERE. Both jobs were green on the 10 previous heads that ran them, and the only change since the last green head is 84e908100df plus the master merge cde27e4d4a9.

What clears it, and it does not need a new commit. Of the last 60 merged pull requests, 0 merged with a red Mergeable Check, so it is a real gate. Of the 10 whose head sha got more than one Mergeable Check post, 7 went failure to success on the same sha, either by re-running the failed jobs green so the bot reposts success (#113295), or by a maintainer override from the merge tooling, which prompts "Do you want to override mergeable check?" and posts Manually overridden (ci/jobs/scripts/check_ci.py:474) as in #113395, #113384, #113371 and #113363.

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 push: false on your fork (a no-op dry-run push returns 403) and cannot post commit statuses on the repository.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (400 commits, zero conflicts) and pushed as 3c5269bd57a — this clears the CONFLICTING state GitHub was reporting. Post-merge verification: all 25 touched C++ translation units compile clean against the merged tree, every serializeSettings override on master still carries the version parameter, DBMS_TCP_PROTOCOL_VERSION 54489 vs master's 54488 and DBMS_QUERY_PLAN_SERIALIZATION_VERSION 5 vs master's 4 — no collisions; the settings-history entry is still in the current 26.8 block.

The two red checks on the previous head d94ecfbd are both unrelated to this PR:

  • Stress test (arm_debug): the HashJoin buildAdditionalFilter type-equality exception (STID 2508-2e0c) from a mixed JOIN ON condition over a dictionary — fix is Fix a mixed JOIN ON condition evaluated over mismatched column types for a dictionary #113534 (still open, so a master merge cannot clear it yet).
  • AST fuzzer (amd_debug): Logical error: 'Query builder not found for text search query with function 'hasAllTokens'' in TextIndexAnalyzer — a text-index bug on master (this PR touches only aggregation); investigating separately.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Follow-up on the AST fuzzer (amd_debug) red: reproduced and root-caused it — the Query builder not found for text search query with function 'hasAllTokens' exception is a master-side text-index direct-read bug under plan-based parallel replicas, unrelated to this PR (it also reproduces on a binary without this PR's changes). Filed #113664 with a minimal deterministic reproducer and analysis.

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

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

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 (25d677a44eb4be5, build id 3460f97598ea) with the localhost 3-replica cluster and process_query_plan_packet on. Same message, same abort, and the stack is the one you predicted: TextIndexAnalyzer::getQueryBuilder (TextIndexAnalyzer.cpp:184) from MergeTreeReaderTextIndex::classifyVirtualColumns (MergeTreeReaderTextIndex.cpp:281), under MergeTreeSelectProcessor on a ReadPoolParallelReplicas task.

Then I ported the source hunk of #112723 onto that same master HEAD (the ported hunk is byte-identical to yours, +27/-1 on applyParallelReplicas.cpp) and ran a 4-binary matrix. Every cell restarts the server and asserts SELECT lower(buildId()) against readelf -n before recording a verdict.

master 3460f9 #110770 only 928e0b #112723 only b315de both 28b3fa
#113664 reproducer (PREWHERE hasAllTokens / WHERE hasToken) LOGICAL_ERROR LOGICAL_ERROR ok, 33334 ok
local_plan = 0, single WHERE hasToken NOT_FOUND_COLUMN_IN_BLOCK NOT_FOUND_COLUMN_IN_BLOCK ok, 33334 ok
#110770 reproducer (partition key + folding) LOGICAL_ERROR ok LOGICAL_ERROR ok
04658 (#112723's own test) fail fail pass pass
04424 (#110770's own test) fail pass fail pass

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 insertParallelReplicasSplit, mine rebuilds the condition template in ReadFromMergeTree::buildIndexes. So they are complementary, not overlapping. They are also source-disjoint, so apply order does not matter: applying yours first and mine first produce a byte-identical binary (build id 28b3fa0ccbc3 both ways), and that build passes all five rows.

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 use_constant_folding_in_index_analysis is 0 by default anyway, so folding is not on this path at all.

Your matrix's last row is optimistic. It records "any of the above ... with parallel_replicas_local_plan = 0" as ok. On master that arm is not ok. It is Code: 10 NOT_FOUND_COLUMN_IN_BLOCK, raised by the remote replica:

Received from 127.0.0.3:21500. DB::Exception:
Column `__text_index_idx_s_hasAllTokens_44de44cd816da6693bcb08fec1a3595b`
not found in table default.tab. (NOT_FOUND_COLUMN_IN_BLOCK)

And it is broader than the bug you filed: with local_plan = 0 it fires on a single text-search predicate too, with no PREWHERE and nothing duplicated: plain SELECT count() FROM tab WHERE hasToken(s, 'inlined') fails, while the same query with no text index in play returns correctly. That is the "a remote replica also cannot resolve the synthetic column against the table" half already named in your #112723 description, so it is the same defect and the same guard fixes it; only the issue's matrix understates it. Worth correcting there since the row reads as a workaround, and it is not one.

I also confirmed the CI failure you pointed me at is this bug and not a third route. The fuzzer's table is LowCardinality(String) with no PARTITION BY, which is why the folding route cannot be involved. Rebuilt that exact DDL plus SELECT id FROM tab__fuzz_43 PREWHERE hasAllTokens(s, '\0nlined') WHERE hasToken(s, 'inlined') LIMIT 1024, 9223372036854775806: aborts on master, returns on the #112723 build.

One practical note. #112723 is 1980 commits behind master and its applyParallelReplicas.cpp hunk no longer applies as a patch, because #include <optional> landed above the include your diff anchors on. The 3-way merge is clean though (git merge-tree against current master reports zero conflicts), so a plain master merge is enough, no manual fixup. That is also why I ported the hunk by hand for the arms above rather than testing your branch head, so the numbers describe your change on today's master and not your base.

For the ledger on this PR: AST fuzzer (amd_debug) here is owned by #112723, and the failure is not reachable from @harikrishnan94's diff, which touches no text-index or parallel-replicas file.

Happy to open the local_plan = 0 single-predicate case as its own regression arm on top of #112723 if you want it pinned separately, but as it stands your test plus your guard already cover it.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed two commits:

  • 333e4d7c5ac — merged current master (165 commits, zero conflicts). DBMS_TCP_PROTOCOL_VERSION 54489 vs master's 54488 and DBMS_QUERY_PLAN_SERIALIZATION_VERSION 5 vs master's 4 — no collisions; the settings-history entry is still in the current 26.8 block.
  • 9cea7b77bce — addressed the remaining review finding (replied on the thread): new test_packed_string_keys_default_propagation covers default-driven propagation of enable_packed_string_keys_in_aggregation. The shard disables the setting via a <profile> default while the initiator sits on the compiled-in (unchanged) default and the query never mentions the setting; the test asserts from the shard-side system.query_log that the secondary query executed with the initiator's effective value. Verified on two local servers built from this branch: the propagated value is 1 while a shard-local control query records 0, so the test fails exactly when the modified_settings.set(...) calls in MultiplexedConnections::sendQuery / HedgedConnections::sendQuery are removed.

The 10 red jobs on the previous head 3c5269bd57a were all infrastructure ERRORs (0-second jobs, CI Infrastructure Messages: 21 error(s)), not test failures — this push retriggers them on a fresh run.

/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 4ee81be Aug 7, 2026
180 checks passed
@harikrishnan94
harikrishnan94 deleted the packed-string-ref-postfix branch August 7, 2026 11:56
alexey-milovidov added a commit that referenced this pull request Aug 7, 2026
…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]>
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
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-improvement Pull request with some product 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.

4 participants