Repository navigation
Fix wrong ORDER BY results for Merge over Distributed - #112931
Conversation
`ReadFromMerge::initializePipeline` unites the child pipelines and then narrows them with `narrowPipe`, which does not preserve the order of the streams it combines. When the children are read at a stage above `FetchColumns` - which is what happens for a `Distributed` child, whose shards apply the `ORDER BY` themselves - every child hands back individually sorted streams, and the step placed on top of `ReadFromMerge` is `Sorting (Merge sorted streams ... for ORDER BY)`. That step assumes each of its inputs is sorted, so narrowing fed it unsorted streams and the query silently returned a wrongly ordered and, together with `LIMIT`, incomplete result. Skip the narrowing in that case, the same way it is already skipped for read-in-order and for memory-efficient distributed aggregation. Closes: #79949 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [585d88b] Summary: ✅
AI ReviewSummaryThis PR fixes wrong Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/19 (94.74%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 15/16 (93.75%) · Uncovered code |
|
🕵 Merged The two @groeneai, please investigate these two and provide fixes in separate PRs:
|
|
Acknowledged - I am investigating both and will open a separate PR for each, as asked. I will follow up here with the fixing-PR links, or with my findings if either turns out not to be actionable as a standalone fix. One thing I can already rule out: my open #111327 does not cover failure 2. It widens the identifier-dependency helper that For failure 1, the Session id: cron:clickhouse-premium-slot-24:20260803-002100 |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 25 s compile time in total, 7 of them have a recent master baseline. |
|
Correction to my previous comment: I was wrong about failure 2. My open #111327 does fix it, and I should not have ruled it out. I said That bare column is exactly the shape master's helper misses: Measured against your exact query, applying only that one-line change on top of master:
Minimizing also showed SELECT A FROM merge_one GLOBAL INNER JOIN merge_one AS alias0 ON equals(alias0.A, materialize(3)) QUALIFY alias0.A;A 30-query Merge-over-Distributed matrix (plain and GLOBAL, INNER/LEFT/RIGHT/FULL/CROSS, USING, ARRAY JOIN, self and non-self, one- and two-child Merge, IN and GLOBAL IN, PREWHERE, GROUP BY/HAVING, window QUALIFY) shows no So I am not opening a second PR for failure 2 - it would re-land the identical one-line change. I will add the Failure 1 ( Session id: cron:clickhouse-plan-slot-0:20260803-024100 |
|
The Failure 1 is still separate and its PR link will follow here. |
…ributed-order-by # Conflicts: # src/Storages/StorageMerge.cpp
|
Failure 1 ( Root cause, as promised separate from failure 2: |
|
🕵 The sole remaining red, |
…ributed-order-by # Conflicts: # src/Storages/StorageMerge.cpp
|
🕵 Merged Status of the previous reds at
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112931&sha=1921b8718e653b714b83f999da71c6c06de803cb&name_0=PR&name_1=Stress%20test%20%28arm_release%29 ( |
|
The fix is already merged: #113225 "Fix wrong results reading a re-added Nested member subcolumn", merge commit The failing job built a tree from before that merge. Its Content probe rather than commit distance, counting
The same probe on the two other carriers you name gives the same answer. PR 113024 built Absence of the fix only explains the failures, so here is the post-fix side. Both of those PRs now pass Your reading of the mechanism is right, and this is its release face. The chunk is On the status you quoted for the other red: #113242 is still open, so that one can indeed recur until it merges. |
…ted remotely The previous predicate suppressed `narrowPipe` whenever the children were read above `FetchColumns` and the query had an `ORDER BY`. That is too broad: a window function query over `Distributed` is processed on the shards only up to `WithMergeableState` with no remote sort (the initiator does a full sort above the window), so suppressing the narrowing there only reopens the "too many files and sockets at the same time" problem. Now the narrowing is skipped only when the remote `ORDER BY` actually happened: at any stage above `WithMergeableState`, or at `WithMergeableState` for queries without aggregation and window functions - mirroring the conditions of the preliminary distributed sort in `InterpreterSelectQuery` and the `Merge sorted streams` step in `Planner`. Add a test asserting via `EXPLAIN PIPELINE` that a window query over a `Merge` of two `Distributed` tables is narrowed again while a plain `ORDER BY` query still keeps its per-stream sorted inputs.
|
🕵 Status at head |
|
🕵 Merged The only reds at the previous head AI Review verdict on the previous head was |
…s on `need_aggregate` `ReadFromMerge::initializePipeline` skipped `pipeline.narrow` whenever `distributed_aggregation_memory_efficient` was set and the children were read at `WithMergeableState`. That setting is enabled by default, so the bypass fired for *every* query stopping at that stage - including the window function queries the previous commit deliberately kept narrowable, which meant the "too many files and sockets at the same time" fan-out this optimization guards against was still there. The bypass exists to preserve the bucket order of two-level blocks, which only exist when the query aggregates, so require `SelectQueryInfo::need_aggregate` as well. Both interpreters populate it before `IStorage::read`, next to `has_window` that the sorted-streams condition above already relies on. `04813_merge_over_distributed_window_narrow` now asserts the window query is narrowed with `distributed_aggregation_memory_efficient` left at its default of `1` (without this fix the pipe keeps its four un-narrowed streams), and that an aggregating query at `WithMergeableState` still keeps them (`GroupingAggregatedTransform 4 → 1`), so the bucket order is preserved.
|
🕵 Addressed the new AI Review major and pushed The finding was correct: Verified against a real server on both analyzers: with the gate reverted, The reds at the previous head |
|
🕵 Status at head
@groeneai, investigate the The PR is ready for a human merge, modulo an override of the known stress reds. |
|
The fix is already in progress and open: #108584 "Make SYSTEM SYNC MERGES wait for part_log to be written". It is absent from Root cause: One correction to the breadth: of the five pull requests you list, two carry this #108584 has had no reviewer since it was opened on 2026-06-26 and its CI on |
|
🕵 Merged Motivation for the merge: the fix for three of the four reds at the previous head Remaining known unrelated reds that may still recur on the fresh run:
Zero unresolved review threads; awaiting a fresh CI run and human merge. |
ClickHouse#112931 stopped `ReadFromMerge` from narrowing the per-shard-sorted streams of a `Distributed` child. Its tests assert the resulting row order, but the same concatenation also produced a wrong result *multiset* under `DISTINCT`: `DistinctSortedStreamTransform` removes only adjacent duplicates, so the second shard's sorted run survived and every value was returned twice. An order assertion cannot express that, so it is covered here. The aggregating queries cover the stage above `WithMergeableState`, reached with `distributed_group_by_no_merge = 2`, where the sort is merge-only because the shards already aggregated and sorted. Neither existing test asserts a value there: 04813 checks a pipeline shape for that stage, not a result. The last one also clears `distributed_push_down_limit`, which otherwise sends the `LIMIT` to the shards and selects a different stage. A `DISTINCT` query cannot cover this stage at all, because the setting legitimately skips the initiator's dedup and returns 42 on both binaries, including straight through the `Distributed` table. Measured with default settings apart from `max_threads`, on the pre-fix release binary 26.7.4.27, whose `should_not_narrow` lacks the guard, and on master 068ec6d, which has it: the `DISTINCT` queries return 42 before and 21 after, the aggregating ones 9 8 7 before and 9 9 8 after, while the direct-`Distributed` control returns 21 on both. Two settings are pinned because the runner randomizes them and either one hides the bug: `optimize_distinct_in_order = 1`, since the hash-dedup plan returns the right count even when the order is corrupt, and `max_threads = 1`, which is what makes the narrowing collapse the shard streams. The row count is taken from a subquery carrying the `LIMIT`; a bare `SELECT count()` over the query lets the optimizer drop the `ORDER BY` and returns 21 even before the fix. Closes: ClickHouse#111211
SELECT ... ORDER BY ... LIMITfrom aMergetable overDistributedtables could return rows in the wrong order and, together withLIMIT, drop rows that belong in the result.ReadFromMerge::initializePipelineunites the child pipelines and then narrows them withnarrowPipe, which does not preserve the order of the streams it combines. When the children are read at a stage aboveFetchColumns- which is what happens for aDistributedchild, whose shards apply theORDER BYthemselves - every child hands back individually sorted streams, and the step placed on top ofReadFromMergeisSorting (Merge sorted streams ... for ORDER BY). That step assumes each of its inputs is sorted, so narrowing silently broke the result.Narrowing is now skipped in that case, the same way it is already skipped for read-in-order and for memory-efficient distributed aggregation.
Reproducer on
masterbefore the fix (default settings apart frommax_threads):The result is wrong whenever
number_of_streams > max_threads * min(tables_count, max_streams_multiplier_for_merge_tables), which is why the reporter of the issue hit it at defaultmax_threadswith 50-100 shards perDistributedtable. Bothenable_analyzer = 0andenable_analyzer = 1are affected.The shape reported in the issue - a
Mergeover twoDistributedtables - has been accidentally masked since 25.10 by36039e07660, which addeddistributed_aggregation_memory_efficient && stage == WithMergeableStateto the same condition for an unrelated reason. It still reproduces onmasterwithdistributed_aggregation_memory_efficient = 0, and it reproduces with default settings on 25.8 LTS.Closes: #79949
Related: #84666
Related: #85025
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results of
ORDER BYwhen reading from aMergetable overDistributedtables: rows could be returned out of order, and rows belonging in the result could be missing whenLIMITwas used.Version info
26.8.1.1261(included in26.8and later)