Skip to content

Ship the preliminary DISTINCT to replicas in plan-based parallel replicas - #130355

Merged
devcrafter merged 13 commits into
masterfrom
pr-plan-based-distinct
Nov 13, 2026
Merged

devcrafter merged 13 commits into
masterfrom
pr-plan-based-distinct

Conversation

@devcrafter

@devcrafter devcrafter commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Closes: #128560
Related: #129811
Related: #128413

Plan-based parallel replicas (parallel_replicas_plan_based) did not ship a DISTINCT to the replicas. The split marker was lifted through expressions, filters, aggregation and sorting, but stopped at the preliminary DistinctStep, so the fragment was only the read: every replica sent all the rows it read to the initiator, and its read was not in order (optimize_distinct_in_order could not apply on either side).

The split is now lifted above the preliminary DISTINCT, the same way as above an expression. The preliminary DISTINCT deduplicates each stream on its own and is always followed by the final DISTINCT, so it runs on a replica as it does on a shard of a Distributed table, and the final DISTINCT stays on the initiator. This matches classic parallel replicas.

With a LIMIT, the preliminary DISTINCT has a limit hint (limit + offset) that makes each of its streams stop reading once it has that many distinct rows. DistinctStep did not serialize the hint, and the LIMIT it comes from stays on the initiator, so a replica read its whole share. The hint is now serialized, as version 2 of the Distinct and PreDistinct steps, from query plan serialization version 21. A peer at an older version, such as 26.10, gets version 1 without the hint and only reads more. The hint does not bound what a replica sends, because the chunk that reaches it passes through whole, so the fragment also gets a final DISTINCT and a LIMIT of the hint, as on shards. The final DISTINCT on replicas is needed because the preliminary one deduplicates each stream separately.

For SELECT DISTINCT a ... LIMIT 3 over 2M rows with 50000 distinct values, a replica sent 200000 rows and read about 1000000 before, and now sends 3 and reads 261636, the same as classic parallel replicas.

#129811, now merged, ships a LIMIT without ORDER BY; with this PR, #128560 is fully addressed. Once this is merged, 02862_sorted_distinct_sparse_fix, 04330_distinct_sorted_const_key_after_filter, 04549_virtual_row_distinct_in_order_boundary, 05217_aggregation_in_order_fixed_keys and 05401_aggregation_nullable_fixed_keys_batch_pack can be removed from tests/parallel_replicas_plan_based_blacklist.txt in #128413. They pass locally with plan-based parallel replicas.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2229-master (included in 26.11 and later)

…gments

Replicas now deduplicate their share and can read in order for it, instead of sending every row they read.

Related: #128560

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [410a020]

Summary: ✅


AI Review

Summary

Ships preliminary DISTINCT to plan-based parallel replicas, serializes its limit hint with a versioned step encoding, and adds replica-local final DISTINCT and LIMIT steps when needed. No actionable findings remain after reviewing the current diff, callers, serialization, optimizer interactions, tests, and all prior discussion.

Missing context / blind spots
  • ⚠️ The full CI suite was skipped by the review-thread gate. The new stateless regression passes at 410a020d (Fast test); all 15 ExternalDistinctPlanSetting tests passed at 4717cb4a (unit tests). A full CI run at the current head would close the remaining validation gap. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No new inline findings or thread updates are needed.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 410a020db with master c65bdd819 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.65, programs/clickhouse-keeper ×0.64 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.4 s +5.1 s (+232%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +47.0 s (+5%) in total before that adjustment.

Job report

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me. I built d40f83a7 and the same tree without the applyParallelReplicas.cpp hunk, and compared them on a three-replica localhost cluster.

  • Every preliminary DistinctStep the planner creates (SELECT, UNION DISTINCT, the liftUpUnion copies) has a final DISTINCT above it, with no LIMIT in between (DISTINCT gets neither a partial-sort limit nor a preliminary LIMIT), so the split may continue into the sort branch. The final DISTINCT gets no sort order through the split, so it reads in order only from the merged stream of a shipped ORDER BY.
  • Results match the query without parallel replicas for parallel_replicas_local_plan 0/1, optimize_distinct_in_order 0/1, max_threads = 1 and max_block_size = 97, on Wide, Compact and sparse parts: ORDER BY (also DESC and a column outside the DISTINCT), LIMIT/OFFSET, WITH TIES, LIMIT BY, DISTINCT ON, UNION DISTINCT, WITH TOTALS, ROLLUP, a window function, JOIN, IN (SELECT DISTINCT ...), LowCardinality/Nullable keys, force_distinct_partitions_independently = 1, and a subquery whose optimize_distinct_in_order differs from the outer one. max_rows_in_distinct still throws with 'throw' and returns with 'break'.
  • No new version gate is needed: PreDistinct is a registered step, and the existing plan version check for parallel replicas admits only replicas that know it.
  • The five tests from the description pass 3/3 on the head and fail 3/3 on the old code with plan-based parallel replicas. With parallel_replicas_local_plan = 0, the replicas now send 200000 rows instead of 2000000 for SELECT DISTINCT a over 2M rows with 50000 values.

Not from this PR: with exact_rows_before_limit = 1, rows_before_limit_at_least of SELECT DISTINCT a FROM t LIMIT 3 is wrong with parallel replicas before and after it (expected 50000; 0 with the local plan, also in classic parallel replicas; 2000000 before and 200000 after without it).

One test suggestion inline.

@nickitat nickitat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Might make sense to test how much we send when there is also a limit.

devcrafter and others added 3 commits November 11, 2026 19:54
…NCT` in plan-based parallel replicas

`limitPushDown` also gives the limit hint to the preliminary `DISTINCT` below the final one, so replicas
both stop reading and send at most `limit + offset` rows, as with query-based parallel replicas.

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

Also keep the `Limit -> Sorting` comment on its function and shorten a comment.

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

A shipped plan fragment may not contain the `LIMIT` the hint comes from, so a replica cannot derive it again.

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

Copy link
Copy Markdown
Member Author

@nickitat Thanks, with a LIMIT the replicas still sent and read everything. DistinctStep did not serialize its limit hint, and the LIMIT stays on the initiator, so neither the preliminary DISTINCT on a replica could stop early nor did anything cap what it sent. Now:

  • DistinctStep serializes the limit hint (step version 2 of Distinct/PreDistinct, from plan version 21).
  • When the preliminary DISTINCT has a hint, the fragment also gets a final DISTINCT and a LIMIT of limit + offset, as on shards of a Distributed table, so duplicates from different streams cannot fill it.

Rows sent and read per replica, 2M rows with 50000 distinct values, max_threads = 4, parallel_replicas_local_plan = 0:

Query Mode Sent Read
SELECT DISTINCT a ... LIMIT 3 plan-based, before 200000, 200000 ~1000000 each
plan-based, now 3, 3 261636, 261636
query-based 3, 3 261636, 261636
... LIMIT 3 OFFSET 2 plan-based, now 5, 5 261636, 261636
query-based 5, 5 261636, 261636

05569_pr_plan_based_preliminary_distinct checks that the DISTINCT and LIMIT are shipped, and a unit test checks that the hint survives serialization.

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed at 4717cb4, approving. What I checked in the code:

  • The shipped LIMIT only exists when the preliminary DISTINCT has a hint, and only addDistinctStep in Planner.cpp sets that hint (liftUpUnion copies it, limitPushDown stops at the final DISTINCT). It is 0 with ORDER BY before the step, LIMIT BY, WITH TIES, a negative or fractional LIMIT, exact_rows_before_limit and WITH TOTALS, so the fragment's LIMIT never has to read till the end. LIMIT n OFFSET -m gets the hint n + m, which is still enough for NegativeOffset + LIMIT on the initiator.
  • The local final DISTINCT is needed for correctness, not only for size: without it, duplicates from different streams could fill the limit + offset rows and the initiator could end up with fewer distinct values than the LIMIT asks for.
  • On the explicit LIMIT: I agree it is needed. DistinctTransform::transform checks the hint after filtering a chunk and returns that chunk whole, and DistinctSortedStreamTransform does the same with its output row count. The hint stops reading, it does not cap what is sent.
  • Version gate: 21 is in no release yet (26.10 writes 20), so step version 2 at 21 follows the rule in ProtocolDefines.h.

@devcrafter
devcrafter enabled auto-merge November 13, 2026 14:14
@devcrafter
devcrafter added this pull request to the merge queue Nov 13, 2026
Merged via the queue into master with commit d1ced87 Nov 13, 2026
403 of 404 checks passed
@devcrafter
devcrafter deleted the pr-plan-based-distinct branch November 13, 2026 19:09
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
devcrafter added a commit that referenced this pull request Nov 13, 2026
Remove the `DISTINCT` tests, fixed by #130355, and `05292`, which passes now.
Add `04627`, and read the projection in `05339` with `parallel_replicas_local_plan = 0`, so both fail deterministically
with #128537.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 14, 2026
The test counts the `DISTINCT` steps in EXPLAIN. With parallel replicas, EXPLAIN also prints the preliminary
`DISTINCT` that runs on the replicas: in the query sent to them (query-based), or in the plan fragment
(plan-based, since ClickHouse#130355 ships the preliminary `DISTINCT`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Plan-based parallel replicas: DISTINCT and LIMIT are not shipped with the plan fragment, so replicas return every row they read

4 participants