Skip to content

Serialize the GROUP BY top-K parameters in the query plan - #116163

Merged
alexey-milovidov merged 7 commits into
masterfrom
topk-serialize-params
Oct 6, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
topk-serialize-params

Conversation

@thevar1able

@thevar1able thevar1able commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Related: #96630

Changelog category (leave one):

  • Improvement

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

Allow using fused GROUP BY top-K with serialized query plan.


Workflow [PR]
Sync PR [sync-upstream/pr/116163]

Version info

  • Merged into: 26.10.1.1645-master (included in 26.10 and later)

`AggregatingStep::serialize` did not carry `params.top_k`, so the
optimization was gated off entirely under `serialize_query_plan`: the
plan-level pass and the shard-side Planner hook both bailed, and the
followers aggregated without the heap.

Carry the parameters in the `Aggregating` step payload under a new flag
bit, gated on query plan serialization version 10
(`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_GROUP_BY_TOP_K`).
Towards an older peer the parameters are omitted rather than rejected:
the peer aggregates without the heap and returns partial states for all
its groups, which the initiator's merge, sort and limit handle
correctly - the safe direction. The deserializer validates the payload
(`k` within the cap, key coverage, directions).

Remove the `serialize_query_plan` gates from `tryOptimizeGroupByTopK`
and `applyTopKPushdownToPartialAggregation`. The shipped plan is a
fresh Planner product built at `WithMergeableState`
(`createRemotePlanForParallelReplicas`, `createLocalPlan` for
`Distributed`), so the hook annotates it and serialization delivers it
to the followers.

Followers re-optimize deserialized plans, so the plan-level pass now
also rejects non-final aggregation explicitly: synthesizing a sort over
partial states would truncate each follower's group set independently,
with no initiator-side sort to discard the resulting incomplete groups.

Integration coverage: new
`test_remote_partial_aggregation_serialized_heap_engaged` proves via
`AggregationTopKRowsSkipped` on the secondary queries that the heap
runs on the followers under `serialize_query_plan = 1`; the EXPLAIN
expectations now require the `Top-K` annotation whenever the
optimization is on, regardless of `serialize_query_plan`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [681c8f3]

Summary: ✅


AI Review

Summary

This PR serializes the GROUP BY top-K parameters in AggregatingStep so serialized distributed and parallel-replica plans can keep the follower-side heap, and it adds solid regression coverage for the new step payload. I found one remaining mixed-version distributed edge: the new kept-keys arbitration now prefers the heap even when an older shard will still deserialize Aggregating step version 0, so that shard loses both the old kept-keys cutoff and the new heap.

Findings
  • ⚠️ Majors
    • [src/Planner/Planner.cpp:951] preferGroupByTopKOverKeptKeysCutoff now assumes a serialized remote plan will always carry top_k. On the ordinary distributed path the QueryPlan packet is still serialized per connection, so a shard below plan version 20 receives Aggregating step version 0 without top_k and falls back to exact aggregation after this helper has already cleared trivial_group_by_limit. That is a rolling-upgrade performance regression for supported mixed-version distributed queries. Suggested fix: keep the cutoff until the target can read Aggregating step version 1, or restrict this preference to paths that are already hard-gated to the current plan version.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required: preserve the old kept-keys cutoff behavior for mixed-version distributed shards, or otherwise gate this preference on a path that guarantees the serialized Aggregating step will actually carry top_k.

LLVM Coverage Report

Measured on commit 681c8f3.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 72/77 (93.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 24, 2026
@thevar1able thevar1able added the hold Skip for auto-updating. label Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 681c8f32b9d9db4cd3c7f146d65b57e062e4cd31 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@thevar1able
thevar1able marked this pull request as ready for review August 27, 2026 00:09
Comment thread src/Core/ProtocolDefines.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@alexey-milovidov alexey-milovidov removed the hold Skip for auto-updating. label Oct 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

I want to review this PR.

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
thevar1able and others added 4 commits October 3, 2026 13:34
Master moved to per-step serialization versions
(#119535) and documented that a
change to a step's bytes must bump the step's own version rather than the
global `DBMS_QUERY_PLAN_SERIALIZATION_VERSION`
(#123241). Flag bit 128 of
`AggregatingStep` is now taken by `only_merge`.

Resolve accordingly: drop the global version bump and the bit-128 top-K
flag, and carry the top-K parameters as a trailing presence byte plus
payload in version 1 of the `Aggregating` step, introduced at plan version
20 (the 26.10 value). Towards a peer that reads step version 0 the
parameters are omitted, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ry_plan`

`preferGroupByTopKOverKeptKeysCutoff`, added on master, refused the heap
under `serialize_query_plan` because the heap used to be disabled for a
serialized plan. This PR lifts that restriction (`AggregatingStep`
carries the top-K parameters since `Aggregating` step version 1), so the
gate would now arm the kept-keys cutoff and take the heap away from a
query it applies to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…trip gtest

Cover `serialize -> deserialize -> serialize` of the `GROUP BY` top-K parameters
for a multi-key mixed-direction case and a prefix-of-keys case, the omission of
the parameters towards a peer below
`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_GROUP_BY_TOP_K`, and the
rejection of more ranked columns than `GROUP BY` keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: 05237_with_expression_alias_scope_descendant (DBReplicated, unrelated to GROUP BY top-K) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other failures on 9aaa67f are unrelated to this PR and already handled. The Build (amd_fuzzers) relocation overflow was fixed by #123738, 00945_bloom_filter_index by #123761, and 05237_time_series_old_metric_family_name_inner_column by #123763. All three fixes are now merged into this branch. 01660_join_or_any has an open fix in #123683, and 05257_sql_security_view_sealed has one in #123729.

Comment thread src/Planner/Planner.cpp Resolved
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (it includes the change from my #123774, closed in its favor). In its own run on 2a290a03b667, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated job.

The failing run on 9aaa67f6dc0 is from 2026-10-03, before #123789 removed the arm_binary DBReplicated jobs. The current head 681c8f32b9d includes #123789, so this job will not run on it until #123790 brings it back with the fix.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit 47a31cd Oct 6, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the topk-serialize-params branch October 6, 2026 10:25
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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