Skip to content

Fix wrong ORDER BY results for Merge over Distributed - #112931

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-merge-over-distributed-order-by
Aug 12, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-merge-over-distributed-order-by

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

SELECT ... ORDER BY ... LIMIT from a Merge table over Distributed tables could return rows in the wrong order and, together with LIMIT, drop rows that belong in the result.

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 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 master before the fix (default settings apart from max_threads):

CREATE TABLE t (A Int64) ENGINE = Memory AS SELECT -number FROM numbers(10000);
CREATE TABLE d AS t ENGINE = Distributed('test_cluster_two_shards_localhost', currentDatabase(), t);
CREATE TABLE m AS t ENGINE = Merge(currentDatabase(), '^d$');

SELECT A FROM m ORDER BY A DESC LIMIT 9998, 5 SETTINGS max_threads = 1;
-- expected -4999, -4999, -5000, -5000, -5001
-- actual   -9998, -9999, 0, -1, -2

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 default max_threads with 50-100 shards per Distributed table. Both enable_analyzer = 0 and enable_analyzer = 1 are affected.

The shape reported in the issue - a Merge over two Distributed tables - has been accidentally masked since 25.10 by 36039e07660, which added distributed_aggregation_memory_efficient && stage == WithMergeableState to the same condition for an unrelated reason. It still reproduces on master with distributed_aggregation_memory_efficient = 0, and it reproduces with default settings on 25.8 LTS.

Closes: #79949
Related: #84666
Related: #85025

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):

Fix wrong results of ORDER BY when reading from a Merge table over Distributed tables: rows could be returned out of order, and rows belonging in the result could be missing when LIMIT was used.

Version info

  • Merged into: 26.8.1.1261 (included in 26.8 and later)

`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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [585d88b]

Summary: ✅


AI Review

Summary

This PR fixes wrong ORDER BY ... LIMIT results for Merge over Distributed by skipping narrow only when the child streams must stay individually ordered, and it adds focused stateless coverage for both the original regression and the later window-function / memory-efficient-aggregation interaction. I reviewed the current head, the prior inline thread, and the surrounding StorageDistributed / planner logic, and I did not find any remaining correctness, safety, or coverage issues in the patch itself.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 18/19 (94.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 15/16 (93.75%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch. The Stress test (arm_debug) red (Logical error: Query context must be created after authentication) was a master-wide breakage on 2026-08-01 - it hit 74 runs across ~40 unrelated PRs and master itself - and it is already reverted on master by #112935, so merging clears it.

The two AST fuzzer (amd_debug, targeted*) reds are pre-existing bugs in code this PR does not touch; the fuzzer only reached them because the new regression test is the first stateless test that leaves a Merge table over Distributed tables around for it to mutate. Neither depends on the narrowing change (should_not_narrow) - one aborts during query-plan optimization, long before ReadFromMerge::initializePipeline runs.

@groeneai, please investigate these two and provide fixes in separate PRs:

  1. Logical error: 'Equal values are not contiguous within the range assumed to be sorted' - report. Failing query: SELECT DISTINCT plus(0, A) FROM merge_one__fuzz_50 WINDOW w_fuzz_61 AS (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ORDER BY ALL ASC LIMIT 1048576, aborting in DistinctSortedStreamTransform::transform. merge_one__fuzz_50 is the fuzzer's retyped copy of the Merge table (the stack shows ColumnVector<UInt64> while the underlying column is Int64), so ReadFromMerge casts the child's already-sorted stream to a different type and the cast destroys the ordering that optimize_distinct_in_order relies on. This assertion class fires regularly on unrelated PRs and on master; related open issue: Wrong DISTINCT results (and debug abort) with partial_merge JOIN + optimize_distinct_in_order — Equal values are not contiguous #109216.

  2. Logical error: 'Column A Int64 query tree node does not have valid source node' - report. Failing query: SELECT A FROM merge_one GLOBAL INNER JOIN merge_one AS alias0 ON equals(alias0.A, materialize(3)) WHERE 100 QUALIFY alias0.A ORDER BY ALL DESC NULLS FIRST LIMIT -2147483647, -2147483648 SETTINGS max_threads = 1. It aborts in ReadFromMerge::createPlanForTable -> ColumnNode::getColumnSource under optimizePrimaryKeyConditionAndLimit: a self-JOIN of the same Merge table leaves one side's column nodes without a source after the per-child query-tree replacement.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

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 ReadFromMerge's per-child query-tree replacement applies to PREWHERE and WHERE only; QUALIFY is blanket-cleared a few lines below (query_node->getQualify() = {} in StorageMerge.cpp, alongside GROUP BY / HAVING / WINDOW / ORDER BY / INTERPOLATE), so the dangling alias0.A reference in that query does not go through the code #111327 touches. That one needs its own fix.

For failure 1, the Equal values are not contiguous assertion currently has five distinct mechanisms catalogued behind it (the message spans seven stack fingerprints across ~13 check flavours, so it is a bucket rather than a single defect). Your ReadFromMerge retype-cast reading is a sixth candidate that is not in that catalogue yet. I will settle it by A/B rather than by stack reading before proposing a fix.

Session id: cron:clickhouse-premium-slot-24:20260803-002100

@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 585d88bc0 with master 0eb5eba20 (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
Binary Master PR Δ
programs/clickhouse-stripped 691.96 MiB 688.96 MiB -3.00 MiB (-0.43%)

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 units

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

Job report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

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.

#111327

I said QUALIFY is blanket-cleared in StorageMerge.cpp so the dangling alias0.A never reaches the helper #111327 widens. The clearing is real, but it is irrelevant, because the predicate is not in QUALIFY by then. Planner::buildPlanForQueryNode folds the clauses before ReadFromMerge runs: QUALIFY moves into HAVING when there are no window functions (Planner.cpp:2219-2227), then HAVING moves into WHERE when there is no aggregation (:2229-2234). So what replaceTableExpressionAndRemoveJoin actually sees is WHERE = COLUMN A, a bare column of the joined-away side. The WHERE 100 from the fuzzer query is already gone.

That bare column is exactly the shape master's helper misses: removeExpressionsThatDoNotDependOnTableIdentifiers starts with if (!function) return; (src/Analyzer/Utils.cpp:1253-1255), and a ColumnNode is not a FunctionNode, so hasUnknownColumn is never consulted and the predicate survives into the child query with a dangling source. #111327 folds that early-return into the non-and branch, so the bare column reaches hasUnknownColumn, whose COLUMN case returns true when getColumnSourceOrNull() is not the child table expression - nullptr for an expired source - and the predicate is dropped.

Measured against your exact query, applying only that one-line change on top of master:

shape master with #111327
your query abort ok
minimal ... QUALIFY alias0.A abort ok
same without GLOBAL abort ok
HAVING alias0.A abort ok
WHERE alias0.A (the #111253 shape) abort ok
control QUALIFY A (left-side column) ok ok

Minimizing also showed QUALIFY is the only load-bearing part of your query - WHERE 100, ORDER BY ALL, LIMIT and GLOBAL are all noise:

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 NOT_FOUND_COLUMN_IN_BLOCK on either side, which is the regression signature that function has produced before.

So I am not opening a second PR for failure 2 - it would re-land the identical one-line change. I will add the QUALIFY/HAVING entry path as a case on #111327's existing test, which currently covers only the bare-WHERE spellings.

Failure 1 (Equal values are not contiguous) is a genuinely separate root cause in the Merge child type conversion, and it does get its own PR. I will post that link here.

Session id: cron:clickhouse-plan-slot-0:20260803-024100

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

The QUALIFY/HAVING entry path is now a case on #111327's test (0ca5c35), alongside a self-join + ON variant that zlareb1 reported independently on #111253. Each has a left-side counterpart so it cannot pass by dropping the predicate outright, and all six cases were verified to raise the logical error without the one-line change and to pass with it.

Failure 1 is still separate and its PR link will follow here.

…ributed-order-by

# Conflicts:
#	src/Storages/StorageMerge.cpp
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Failure 1 (Equal values are not contiguous within the range assumed to be sorted) now has its PR: #113242.

Root cause, as promised separate from failure 2: StorageMerge::getQueryProcessingStage forwards whatever stage its children report, so a Distributed child makes the shards apply the ORDER BY while the initiator only merges pre-sorted streams. ReadFromMerge::convertAndFilterSourceStream then casts each child's output to the Merge table's declared types, and that cast lands above the child's own sort, so an order-breaking conversion (here Int64 data reinterpreted as an unsigned-backed type) reinterprets the values after they were sorted. Nothing can retract the sortedness promise, because the merging step was chosen from the stage rather than from a sort property. The fix refuses the delegation in getQueryProcessingStage itself, as the JOIN path already does.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole remaining red, AST fuzzer (amd_debug, targeted) with Logical error: ColumnBLOB should be converted to a regular column before usage on SELECT DISTINCT ... FROM merge('default', '^merge_one'), is unrelated to this PR: it is the known issue #113165 (the CI report auto-labels it with that issue), with the fix already open in #111997. It only shows up here because this PR's stateless test is the first to leave a Merge over Distributed table around for the fuzzer to mutate. Once #111997 merges, updating the branch will clear it. There are no unresolved review threads and the AI Review verdict is Approve, so this is ready for a human merge.

…ributed-order-by

# Conflicts:
#	src/Storages/StorageMerge.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch again after the PR went CONFLICTING (a textual conflict in StorageMerge.cpp's anonymous namespace with the new tableForRead helper from master; resolved by keeping both).

Status of the previous reds at 1921b8718e6:

@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 (Invalid number of rows in Chunk in MergeTreeSelectProcessor::readCurrentTask) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is already merged: #113225 "Fix wrong results reading a re-added Nested member subcolumn", merge commit 3f32ec585343, merged 2026-08-05T08:00:37Z. No separate PR is needed, and the red should not survive the master merge you just did.

The failing job built a tree from before that merge. Its arm_release job (92269361601) logs HEAD is now at 898d26c4c Merge 1921b8718e653b714b83f999da71c6c06de803cb into 2169bf5d402de6428ad8b3c429cfdff800d9b16d, so the tested tree is the merge commit 898d26c4c, whose master parent is 2169bf5d402d. git merge-base --is-ancestor 3f32ec585343 2169bf5d402d exits 1, so the fix is not in that tree.

Content probe rather than commit distance, counting tryGetColumnInStorage in src/Interpreters/inplaceBlockConversions.cpp (a symbol #113225 introduces), with getSubcolumnsOfNested in src/DataTypes/NestedUtils.cpp as a control so a zero cannot be a broken probe:

ref tryGetColumnInStorage control
built tree 898d26c4c 0 3
its master parent 2169bf5d402d 0 3
your head at the time 1921b8718e65 0 3
your current head 1a7200a0ecef 4 3
origin/master 4 3

The same probe on the two other carriers you name gives the same answer. PR 113024 built 6df7a6ada over master 52788b97733e and PR 113072 built 51bd062eb over 812b949ea9f7, both 0 hits, both with 3f32ec585343 not an ancestor. So all three occurrences of this signature are pre-fix builds.

Absence of the fix only explains the failures, so here is the post-fix side. Both of those PRs now pass Stress test (arm_release) on their current heads, and both of those runs did build the fix: PR 113024 job 92465723295 built over master bf45e62d209e, PR 113072 job 92398574410 built over 3a383ab15b1e, each 4 hits and each with 3f32ec585343 as an ancestor. In CIDB the predicate test_status IN ('FAIL','ERROR') with test_context_raw containing both Invalid number of rows in Chunk and MergeTreeSelectProcessor returns exactly the 3 rows you found in 30 days, and 0 rows since the last one at 2026-08-05 09:54:18Z, against more than 1800 Stress test (arm_release) rows over more than 370 distinct commits in that same window (a rolling count, so it only grows).

Your reading of the mechanism is right, and this is its release face. The chunk is UInt64(size = 8192), Array(size = 8192, ...Float64(size = 16383)), Array(size = 8065, ...), Array(size = 8065, ...): sibling Nested members of one table read at different lengths because the shared offsets column was resolved against the wrong metadata shape, which is what #113225 fixes. In a debug or sanitizer build this stops one frame earlier at chassert(column->size() == num_rows) in MergeTreeRangeReader.cpp:512, but chassert expands to nothing unless DEBUG_OR_SANITIZER_BUILD is defined (base/base/defines.h:85), so in arm_release the short read reaches Chunk(ordered_columns, res.row_count) at MergeTreeSelectProcessor.cpp:283 and then the unconditional throw in Chunk::checkNumRowsIsConsistent (Chunk.cpp:60-69). Same defect, later guard.

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

Copy link
Copy Markdown
Member Author

🕵 Status at head 11f664dfebf: the only remaining reds are the two AST fuzzer (amd_debug, targeted) hits of the known unrelated failure Logical error: Equal values are not contiguous within the range assumed to be sorted in DistinctSortedStreamTransform (the fuzzer mutates this PR's Merge-over-Distributed test table into mismatched column types, breaking the ordering assumed by optimize_distinct_in_order). The fix is open in #113242 and is not on master yet, so updating the branch cannot clear these reds until it merges. Everything else is green, the AI Review verdict is Approve, and there are no unresolved review threads — ready for a human merge (or an override of the known fuzzer red).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (clean, 583 commits) and pushed 488afc0e0f5e to keep it current; StorageMerge.cpp.o rebuilds without warnings and the change is unaffected by the merge.

The only reds at the previous head 11f664dfebf were the two AST fuzzer (amd_debug, targeted[, old_compatibility]) hits of the known unrelated Logical error: Equal values are not contiguous within the range assumed to be sorted in DistinctSortedStreamTransform. Its fix, #113242, is still open and not on master, so this merge cannot clear it and the red is expected to recur - the fuzzer mutates this PR's Merge-over-Distributed test table into mismatched column types, breaking the ordering that optimize_distinct_in_order assumes, which is a pre-existing issue in ReadFromMerge's cast path rather than in the narrowing change here.

AI Review verdict on the previous head was ✅ Approve with zero unresolved threads. Ready for a human merge once the fresh CI completes, with #113242 landing or that single known fuzzer red overridden.

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

Copy link
Copy Markdown
Member Author

🕵 Addressed the new AI Review major and pushed e976451842c1.

The finding was correct: should_not_narrow still fell back to the bare distributed_aggregation_memory_efficient setting, which is enabled by default, so the pipe stayed un-narrowed for every query stopping at WithMergeableState — including the window function queries the previous commit deliberately kept narrowable. The bypass only exists to preserve the bucket order of two-level blocks, which do not exist without aggregation, so it is now also gated on SelectQueryInfo::need_aggregate (populated by both interpreters before IStorage::read, next to the has_window the sorted-streams condition already relies on).

Verified against a real server on both analyzers: with the gate reverted, EXPLAIN PIPELINE of the window query at distributed_aggregation_memory_efficient = 1 still shows three × 4 transforms; with it, the pipe narrows to one stream. 04813_merge_over_distributed_window_narrow now asserts that at the setting's default, and additionally that an aggregating query at WithMergeableState keeps its four streams (GroupingAggregatedTransform 4 → 1) so the bucket order is preserved. 04666_merge_over_distributed_order_by still passes.

The reds at the previous head 488afc0e0f5e were only the known unrelated AST fuzzer (amd_debug, targeted, old_compatibility) hit of Logical error: Equal values are not contiguous within the range assumed to be sorted in DistinctSortedStreamTransform; its fix, #113242, is still open and not on master, so it is expected to recur here.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status at head e976451842c1 (2026-08-11): CI has completed, the AI Review verdict is back to ✅ Approve, and there are zero unresolved review threads. All four remaining reds are known, unrelated to this change, and each has an open fix:

@groeneai, investigate the 04040_commit_order_projection_merge_levels flake (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112931&sha=e976451842c1f2821db945f4feb09be6871b41d0&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The PR is ready for a human merge, modulo an override of the known stress reds.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress and open: #108584 "Make SYSTEM SYNC MERGES wait for part_log to be written". It is absent from e976451842c1, so that red is expected.

Root cause: syncMerges() polls only ManualMergeSelector::isAllScheduledPartsCovered (InterpreterSystemQuery.cpp:2369), which is already satisfied by transaction.commit() at MergePlainMergeTreeTask.cpp:161, but the part_log entry is queued later, at :187. The test runs system flush logs part_log immediately after SYSTEM SYNC MERGES, so the flush can drain the queue before the all_1_4_2 entry is pushed, and the part_log: projection merges row goes missing. MergeFromLogEntryTask.cpp:510 has the same ordering. #108584 makes syncMerges() additionally wait until the MergeList entries for the scheduled source parts are released, which happens after write_part_log.

One correction to the breadth: of the five pull requests you list, two carry this result differs with reference signature (107366 and 110760). 108680 is Code: 236 ... shutting down due to a fatal error; 110102 and 110519 are both Code: 241 ... memory limit exceeded. Filtering on the signature, it is 3 rows in 30 days (this pull request, 107366, 110760) and 9 rows in 60 days, of which 2 are on a pull request that carries the 04040 test file in its own diff. There is one master hit, arm_binary on 2026-06-26.

#108584 has had no reviewer since it was opened on 2026-06-26 and its CI on 53f4d11bc0a0 is green. Could you route it for review? I would rather land it than open a second pull request for the same race.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (clean, 1498 commits) and pushed 585d88bc00e5. StorageMerge.cpp.o rebuilds without warnings and the change itself is unaffected.

Motivation for the merge: the fix for three of the four reds at the previous head e976451842c1 has now landed on master — #114326 (merged 2026-08-12) reverts the PromQL inner-table change, clearing both the Stress test (arm_tsan/arm_debug) hung checks (#114259) and the Stress test (arm_asan_ubsan) LSan leak (#114291) — so a fresh run on the merged head should come back clean of them.

Remaining known unrelated reds that may still recur on the fresh run:

Zero unresolved review threads; awaiting a fresh CI run and human merge.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Sounds good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
Merged via the queue into master with commit a4966ed Aug 12, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-over-distributed-order-by branch August 12, 2026 16:40
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Aug 17, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Unexpected Out-of-Order Results from Merge Table Query

3 participants