Skip to content

Drop the GROUP BY ... LIMIT kept-keys cutoff from the per-replica aggregation of plan-based parallel replicas - #126139

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:pr-plan-based-kept-keys-cutoff-122607
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:pr-plan-based-kept-keys-cutoff-122607

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122607

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

With parallel_replicas_plan_based = 1, SELECT k, count() FROM t GROUP BY k LIMIT n no longer returns undercounted aggregates when the trivial GROUP BY ... LIMIT optimization uses its kept-keys cutoff.

Description

With parallel_replicas_plan_based = 1, SELECT k, count() FROM t GROUP BY k LIMIT n could return too-small aggregates when the kept-keys cutoff of the trivial GROUP BY ... LIMIT optimization applies (LIMIT above query_plan_max_limit_for_top_k_optimization, or the top-K heap disabled). The cutoff with aggregate functions came in with #114690 (26.10); the setting is experimental, so no changelog entry.

Root cause: the planner arms the cutoff because, at planning time, the aggregation sees every row. ApplyParallelReplicasVisitor then splits it into a per-replica partial aggregation plus MergingAggregated, cloning the step with the cutoff. The local replica runs the unserialized clone and keeps at most n keys of its share. The remote replicas get the serialized plan, where AggregatingStep::serializeSettings already drops the cutoff. A key the local replica dropped comes out of the merge with only the remote replicas' rows.

Change: the visitor drops the cutoff from the partial step it creates (AggregatingStep::dropSharedKeptKeysCutoff), so every replica runs the same exact partial aggregation that the remote ones already run: the local replica now keeps every key of its share, as the remote ones do. The merge step is unchanged. The serialized plan is byte-identical to before.

Validation: on master the new test fails 20/20 under random settings (local disk and s3). With the fix it passes 50/50, plus 40/40 with DBReplicated, 40/40 in the ParallelReplicas lane and 20/20 on s3. A 10M-row table is needed: below one 128-mark coordinator segment the local replica reads the whole table and the result is exact. The slowdown_parallel_replicas_local_plan_read fail point (hence no-parallel) makes sure the remote replicas also get marks.


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

groeneai and others added 2 commits October 15, 2026 20:45
…sed parallel replicas

The trivial `GROUP BY ... LIMIT` optimization arms a kept-keys cutoff
(`max_rows_to_group_by = LIMIT`, `ANY`, `shared_kept_keys_for_overflow_any`)
when the aggregation does both stages, which a plan-based parallel-replicas
query does at planning time. `ApplyParallelReplicasVisitor` later splits the
`AggregatingStep` into a per-replica partial aggregation plus
`MergingAggregated`, cloning the step with the cutoff. The local replica runs
the unserialized clone and keeps at most `LIMIT` keys of its share, while the
remote replicas get the serialized plan, where `serializeSettings` already
writes `max_rows_to_group_by = 0`. The initiator then merges a truncated local
state with full remote states, and a key the local replica dropped comes out
with only the remote replicas' rows.

Drop the cutoff from the partial step in the visitor, so every replica runs
the exact partial aggregation the remote ones already run. The merge step keeps
its params; its own cap is applied to keys it receives, so every key it outputs
is exact. The serialized partial step is unchanged.

The test needs a table of several coordinator segments (~10M rows): with one
128-mark segment the local replica reads everything and the result is exact.
The `slowdown_parallel_replicas_local_plan_read` fail point makes the remote
replicas take part, hence `no-parallel`.

Closes ClickHouse#122607

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MergingAggregated` is created when `ApplyParallelReplicasVisitor` splits the
aggregation, before `ConvertToDistributedVisitor` decides whether to build the
parallel-replicas plan. If that conversion declines, the split stays a
single-node pass-through and the test would return exact counts on any binary
while the old shape check still printed 1. Also require `ReadFromParallelReplicas`
in the plan, as `04409_pr_plan_based` and `04837_pr_plan_based_aggregation_in_order`
do.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 1 finding) plus my own cold reviews (nits only).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test's plan check (MergingAggregated) passes even if the plan is not sent to the remote replicas AGREE, fixed in 7f93060 The check now also requires ReadFromParallelReplicas. It prints 1 1 on the fixed binary and 0 1 with a one-replica cluster. Not adopted: ParallelReplicasUsedCount > 1 (timing-dependent) and OverflowAny > 0 (0 on the fixed binary by design). Re-review: 0 findings
2 💡 When the split plan falls back to one node, the partial aggregation also runs without the cutoff AGREE, not blocking Results stay exact; only the saving is lost there. No released version has the cutoff
3 💡 makeDistributed splits an aggregation the same way without dropping the cutoff DISAGREE The planner does not arm the cutoff for a query with make_distributed_plan (Planner.cpp:3150); not reproduced, and outside this PR's setting
4 💡 Test cost: about 10M rows DROPPED 50 local runs: average 1.14 s, max 3.29 s (debug build)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261015-213700

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa609a4]

Summary: ✅


AI Review

Summary

The PR fixes undercounted aggregates with parallel_replicas_plan_based by removing the planner-generated GROUP BY ... LIMIT cutoff from per-replica partial aggregation. The regression test covers both merge modes and a disabled top-K heap. No actionable findings remain after reviewing the current code and prior discussion.

Missing context / blind spots
  • ⚠️ No local ClickHouse build was available, so tests were not rerun during this review. Execution evidence comes from the author's recorded before/after validation; functional CI for the current head was still pending when inspected.
Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 9,998,000 rows (number % 4999), 3 plan-based replicas, GROUP BY k LIMIT 2000: master returns 1207 undercounted groups in 10/10 runs. Controls (optimize_trivial_group_by_limit_query = 0, parallel_replicas_plan_based = 0, parallel_replicas_local_plan = 0) are exact 10/10.
b Root cause explained? The planner arms the kept-keys cutoff for a complete aggregation. ApplyParallelReplicasVisitor clones that step into the per-replica partial. The local replica runs the unserialized clone and truncates its keys, while the remote replicas get the serialized plan, where serializeSettings drops the cutoff. The merge combines a truncated local state with full remote states.
c Fix matches root cause? Yes. The cutoff is dropped where the step stops seeing every row (the split), matching what the serializer already does for the remote half. No guard at the merge, no test-side pin.
d Test intent preserved / new tests added? New SQL test 05401_...: three exact-count arms (LIMIT above the top-K heap threshold, heap disabled, ordinary merge) plus a plan check that the split reaches the remote replicas (ReadFromParallelReplicas) and has MergingAggregated.
e Both directions demonstrated? Master: 20/20 FAIL (local disk), 20/20 FAIL (s3). Fix: 50/50 OK, plus DBReplicated 40/40, ParallelReplicas lane 40/40, s3 20/20, random settings on.
f Fix is general across code paths? The visitor's aggregation split is the only place an armed step is cloned into a partial. The planner does not arm the cutoff for a query with make_distributed_plan, Cascades refuses max_rows_to_group_by != 0, and query-tree parallel replicas / Distributed never arm a partial stage. Unions, lifted joins and Merge tables all pass through the same line.
g Fix generalizes across inputs (params/datatypes/wrappers)? Step-level, independent of key and aggregate types. Tested with LIMIT above and below the heap threshold, both merge kinds, random settings and 4 lanes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting and no format change: the serialized partial step is byte-identical to before.
i Invariants and contracts preserved? The cutoff's contract (exact only when the step sees every row) now holds. Every replica runs the same partial aggregation, and the merge step is unchanged. The cutoff's runtime control is created later in transformPipeline, so nothing is left half-initialized.

Session id: cron:clickhouse-impl-slot-7:20261015-212300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @nickitat, could you review this? With parallel_replicas_plan_based = 1, ApplyParallelReplicasVisitor clones the aggregation into the per-replica partial step together with the GROUP BY ... LIMIT kept-keys cutoff; the local replica runs that clone unserialized and drops keys, while the remote replicas already run without the cutoff, so the merge undercounts. The fix drops the cutoff from the partial step. CI did not start because the PR has no can be tested label, and I cannot add it myself: could one of you add it?

@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7f93060

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) job timeout, not from this PR (it changes the parallel replicas aggregation split): the job hit the 7200 s limit after the CI Logs cluster check in setup_log_cluster.sh blocked for about 1 hour (03:38Z to 04:39Z, ATTEMPT_TO_READ_AFTER_EOF); the same timeout hit many unrelated PRs and master on 2026-10-16 #126217 (mine, open)
Performance Comparison (arm_release, master_head, 2/6) same job timeout: both CI Logs cluster checks blocked (03:38Z to 04:39Z, then again until the 7200 s limit), so the tests never started #126217 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) same job timeout: the CI Logs cluster check blocked 03:38Z to 04:39Z, the tests started at 04:52Z and were cut at the 7200 s limit #126217 (mine, open)
Performance Comparison (arm_release, master_head, 6/6) same job timeout: both CI Logs cluster checks blocked (03:38Z to 04:39Z, then again until the 7200 s limit), so the tests never started #126217 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126217 (the owner of the rows above)

Session id: cron:our-pr-ci-monitor:20261016-060012

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fa609a457 with master d011c6b84 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

57 translation units recompiled, 663 s compile time in total, 57 of them have a recent master baseline.

Job report

This branch has not been deployed

No deployments
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 comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Plan-based parallel replicas undercount aggregates with GROUP BY LIMIT

2 participants