Skip to content

Fix wrong ORDER BY results and pushed bucket twice with offset based parallel replicas - #128865

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:offset-parallel-replicas-ordered-merges
Nov 3, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:offset-parallel-replicas-ordered-merges

Conversation

@groeneai

@groeneai groeneai commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115986

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results of ORDER BY (unsorted rows, wrong rows under LIMIT) and the GroupingAggregatedTransform pushed bucket ... twice error (duplicated groups in older versions) of queries with parallel_replicas_mode = 'sampling_key', or a custom key mode on a cluster with more than one shard. Such a query now reads a shard from one replica unless the initiator only aggregates or fully sorts the parts returned by the replicas.

Description

On 26.10.2.103, SELECT k FROM remote('127.0.0.{1|2|3}', db, t) ORDER BY k LIMIT 10 SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 3, parallel_replicas_mode = 'sampling_key' returns the ten smallest keys of one replica, not of the table (same on 26.8.34.13 and 26.3.60.2). With GROUP BY such reads fail with GroupingAggregatedTransform pushed bucket N twice (26.3: duplicated groups). Found by the AST fuzzer (report).

In these modes ReadFromRemote reads a shard with one executor in GET_MANY: every replica returns its own part of the shard's result, and all parts arrive interleaved on one port. The memory-efficient merge of aggregation and the sorted merge for ORDER BY need one ordered stream per port.

As decided in #115986 (fail closed, from the final plan), a new last pass of optimizeTreeSecondPass allows GET_MANY only when every consumer of the read ignores the order of its streams: a merge of aggregation states that has no keys or is neither memory-efficient nor in order, an aggregation not in order, a full sort (expressions, filters and unions are looked through). Otherwise, including the plan root, the shard is read from one replica. The price is the parallelism inside a shard for such reads; a GROUP BY keeps it with distributed_aggregation_memory_efficient = 0, unless its states are merged in order. The single-shard custom key case already reads every replica separately. A custom key read that now goes to one replica per shard no longer needs parallel_replicas_custom_key; a shard split among replicas still fails with BAD_ARGUMENTS without it.

Validation (debug build, local 2 shards x 3 replicas): the new test fails 20/20 on master, passes 50/50 plus 50 randomized runs; ORDER BY cases: 80/80 wrong on master, 80/80 correct with the fix; ~890 distributed and parallel replicas tests show no difference. test_parallel_replicas_custom_key pins distributed_aggregation_memory_efficient = 0 to keep using every replica.


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

Version info

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

groeneai and others added 7 commits November 2, 2026 16:59
…nless no consumer needs stream order

With `parallel_replicas_mode = 'sampling_key'` on any cluster, or a custom key mode on a cluster with
more than one shard, `ReadFromRemote::addPipe` reads a shard with one `RemoteQueryExecutor` in
`PoolMode::GET_MANY`. Every replica gets its own `parallel_replica_offset` and returns its own part of
the result of the shard, and all parts arrive interleaved through one `RemoteSource` port.

The initiator's order-dependent merges assume one ordered stream per port:
- `GroupingAggregatedTransform` treats a port as past bucket b once any replica sent b + 1, pushes b,
  and the slower replica's chunk of b recreates it: `pushed bucket b twice` (a `LOGICAL_ERROR`;
  duplicated groups before ClickHouse#114523);
- the sorted merge for `ORDER BY` merges ports that are not sorted, and with one shard there is no
  merge at all, so `ORDER BY ... LIMIT` returns rows of one replica.

As decided by the owner in ClickHouse#115986 (fail closed, decided from the final plan), a new last pass of
`optimizeTreeSecondPass`, `allowReadingShardsFromSeveralReplicas`, walks from every `ReadFromRemote` to
its first consumer that is not `Expression`/`Filter`/`Union`, and allows several replicas only for a
consumer that ignores the order of its input streams: a `MergingAggregated` that is not memory bound
and either not memory efficient or without keys, an `Aggregating` that is not in order, a `Full`
sort. Anything else, including the plan root (whose consumer is outside the plan: an upper initiator,
the parent of a `Merge` child plan, a set), and any plan that is never optimized, read every shard
from one replica (`GET_ONE` sends no `parallel_replicas_count`, so that replica reads the whole shard).
`addPipe` runs in `initializePipeline`, after the optimization, so the pool mode follows the final plan.

The single-shard custom key case already reads every replica through its own `GET_ONE` executor and is
unchanged. The price is the parallelism inside a shard for order-dependent offset-mode reads.

Related: ClickHouse#115986

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…replicas keeps the replicas

The `system.query_log` decision check covered only an aggregation without keys. Add a merge of
aggregation that is not memory efficient, a full sort and an aggregation that is not in order, each
expecting three secondary queries, so turning any of these consumers to one replica fails the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fset parallel replicas test

With aggregation in order, which the test runner can randomize on, the replicas send single-level
results, so the GROUP BY cases miss the bucket-by-bucket merge. Pin it off for them.

The replica decision check had no expression, filter or union between the read and the consumer.
Add one case for each, so treating any of these steps as order-dependent fails the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ard from one replica

Every case of the replica decision check reached a consumer that is classified explicitly, so
making the generic fallback or the default for the plan root allow several replicas kept the
test green. Add a read under LIMIT and a read at the plan root, both expected to use one replica.

Also drop the per-query optimize_aggregation_in_order = 0 of the plain merge case: the session
SET already pins it.

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

With LIMIT 3 the initiator stops reading before the secondary query sends EndOfStream and
cancels it. A secondary that sees the Cancel is logged as ExceptionWhileProcessing, which the
QueryFinish-only check does not count, so the case could read 0 instead of 1 with the fix and 1
instead of 3 without it. Use a limit above the row count, so the initiator reads to the end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A merge of aggregation states in order (memory bound merging over a local in-order aggregation)
needs one ordered stream per port, so the remote shard must be read from one replica. Add a
top-level GROUP BY that reaches FinishAggregatingInOrderTransform and check that its remote
shard is read by one secondary query (three without the fix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the pass and addPipe comments to one line each and drop the member comment that only pointed at the pass.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds; the last re-review found nothing)
  • ⚠️ The description over-generalised the custom key GROUP BY without parallel_replicas_custom_key: agreed, narrowed (a shard split among replicas still fails with BAD_ARGUMENTS, as 04669_pr_custom_key_without_custom_key requires).
  • ⚠️ Only the keyless count() proved that several replicas are kept: agreed, a case added for each listed consumer.
  • ⚠️ No case for the expressions, filters and unions the pass looks through: agreed, cases added.
  • ⚠️ Randomized optimize_aggregation_in_order skipped the bucket merge: agreed, pinned to 0.
  • ⚠️ No case for the fail-closed side (any other consumer, the plan root): agreed, cases added.
  • ⚠️ The LIMIT case could cancel its replica query: agreed, the limit is now above the row count.
  • ⚠️ No case for the memory bound merge: agreed, a top-level GROUP BY case added.
  • 💡 In-order aggregation directly over a remote read: reachable only with the internal force_aggregation_in_order, not added.
  • 💡 Defensive merge of repeated visits in the pass, and a test pin without a comment: noted, not changed.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai, could you review this and add the can be tested label so CI runs? In the offset parallel replicas modes ReadFromRemote multiplexes all replicas of a shard onto one port; a new last plan pass now keeps that only when every consumer of the read ignores stream order, otherwise the shard is read from one replica (the fail-closed option chosen in #115986).

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3774155]

Summary: ✅


AI Review

Summary

PR #128865 fixes incorrect ORDER BY results and repeated aggregation buckets with offset based parallel replicas. It uses the final query plan to restrict each shard to one replica when a consumer requires ordered streams, retaining parallel reads for aggregation and full sorting that can accept interleaved streams. No actionable findings at commit 377415576c91a50c1689cb4bdbf9142bd78b2d72.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 3, 2026
@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Nov 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 377415576 with master 53bfe5fc3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 31bebf957; 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.

Object file sizes

6 object files changed (+39.35 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/allowReadingShardsFromSeveralReplicas.cp… new 35.40 KiB +35.40 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

84 translation units recompiled, 700 s compile time in total, 83 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Optimizations/allowReadingShardsFromSeveralReplicas.cpp: 6.5 s

Job report

The distributed case checks that on a two shard cluster every replica
processed the query with the custom key filter. Its `GROUP BY` is merged
memory efficiently by default, so a shard is now read from one replica
and the check fails. Pin `distributed_aggregation_memory_efficient = 0`:
the plain merge ignores the order of the streams, so the replicas of a
shard are still used together and the check still covers that path.

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

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

Passable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit 22a323d Nov 3, 2026
185 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 5, 2026
Antalya 26.8 Backport of ClickHouse#128865 - Fix wrong `ORDER BY` results and `pushed bucket twice` with offset based parallel replicas
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 6, 2026
Antalya 26.6 Backport of ClickHouse#128865 - Fix wrong `ORDER BY` results and `pushed bucket twice` with offset based parallel replicas
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-bugfix Pull request with bugfix, not backported by default 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.

3 participants