Skip to content

Fix ORDER BY not applied globally when reading Distributed through Merge - #111464

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111211-order-by-merge-over-distributed
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111211-order-by-merge-over-distributed

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

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 for a global ORDER BY (and DISTINCT) when reading a Distributed table through a Merge engine: the per-shard sorted streams were concatenated instead of merge-sorted, so LIMIT could return rows local to one shard instead of the global top rows, and DISTINCT could return a doubled result multiset.

Description

Closes: #111211

ReadFromMerge::initializePipeline narrows the united child pipeline with narrowPipe, which concatenates streams via ConcatProcessor and does not preserve per-stream order. When a child is read at a partial stage that emits already-sorted streams (e.g. a Distributed child produces one sorted stream per shard), the outer plan adds a merge-only sorting step that assumes each input stream is individually sorted. With max_threads = 1 the two sorted shard streams were concatenated into one, the merge-only sort then had a single unsorted input and became a no-op, and LIMIT returned one shard's local top rows.

The should_not_narrow guard already suppresses narrowing for the two other order-sensitive cases (read-in-order and memory-efficient distributed aggregation). This adds the third: a global ORDER BY (no aggregation, or any after-aggregation stage) over a child read above FetchColumns. The condition mirrors when the planner/interpreter choose a merge-only sort (Planner.cpp isFromAggregationState / InterpreterSelectQuery.cpp from_aggregation_stage).

Reproducer (before: 297, 294, 291; after: 1297, 1294, 1291), see #111211.

The same narrowPipe concatenation also corrupts the result multiset under DISTINCT (with optimize_distinct_in_order, the second shard's sorted run survives adjacent-only dedup, doubling the rows). That query shape is already covered by the guard added here, so no extra code change was needed; the regression test now also asserts the DISTINCT / DISTINCT ON row counts (reported by @ zlareb1 on #111211).

ReadFromMerge::initializePipeline narrows the united child pipeline with
narrowPipe, which concatenates streams via ConcatProcessor and does not
preserve per-stream order. When a child is read at a partial stage that emits
already-sorted streams (e.g. a Distributed child produces one sorted stream per
shard), the outer plan adds a merge-only sorting step that assumes each input
stream is individually sorted. With max_threads = 1 the sorted shard streams
were concatenated into one, the merge-only sort had a single unsorted input and
became a no-op, and LIMIT returned one shard's local top rows instead of the
global top rows.

Extend the existing should_not_narrow guard (which already covers read-in-order
and memory-efficient distributed aggregation) with the global-ORDER-BY case: a
child read above FetchColumns for an ORDER BY without aggregation, or any
after-aggregation stage. This mirrors when the planner/interpreter choose a
merge-only sort.

Closes ClickHouse#111211.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT w FROM merge_t ORDER BY w DESC LIMIT 3 SETTINGS enable_analyzer=1, max_threads=1 returns 297,294,291 every time on master (max_threads=1 makes narrow(1) collapse the two shard streams).
b Root cause explained? Yes. A Distributed child of the Merge table is read at an after-aggregation stage and emits one sorted stream per shard. The outer plan adds a merge-only sorting step that assumes each input stream is individually sorted. ReadFromMerge::initializePipeline then calls narrowPipe, whose ConcatProcessor concatenates the streams; concatenating separately-sorted inputs is not globally sorted, so the merge-only step sees a single input, adds no MergingSortedTransform, and LIMIT returns one shard's local top rows.
c Fix matches root cause? Yes. Extends the existing should_not_narrow guard (which already covers read-in-order and memory-efficient distributed aggregation) with the global-ORDER-BY case, so the sorted per-shard streams are preserved and the outer step merges them. No widened bound / no-random tag / re-sort bolt-on.
d Test intent preserved / new tests added? Yes. New regression test 04545_order_by_merge_over_distributed.sh. No existing test weakened.
e Demonstrated both directions? Yes. Test FAILS on master (297,294,291) and PASSES with the fix (1297,1294,1291); EXPLAIN PIPELINE gains MergingSortedTransform 2 -> 1 over ReadFromMerge.
f Fix general, not a narrow patch? Yes. Condition covers both merge-only-sort triggers: any after-aggregation stage (distributed_group_by_no_merge=2, distributed_push_down_limit), and WithMergeableState without aggregation/window. Verified for analyzer and old interpreter.
g Generalizes across inputs? Yes. DESC/ASC, enable_analyzer=0/1, GROUP BY present/absent, distributed_group_by_no_merge=2 with and without distributed_push_down_limit, and plain-MergeTree Merge (unaffected, FetchColumns child) all correct; 50/50 randomized-settings runs pass.
h Backward compatible? Yes. Pure query-execution correctness fix; no setting default, on-disk, or wire format change. No SettingsChangesHistory needed.
i Invariants preserved? Yes. The change only avoids destroying the per-stream sortedness the merge-only sort relies on; it emits (still correct) un-narrowed streams that the merge step combines exactly as the direct-Distributed path does. GROUP-BY-without-ORDER-BY still narrows (order irrelevant).

Session id: cron:clickhouse-author-slot-6:20260722-160600

@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 — full pass + delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Type conversion (Int8 child, UInt8 Merge column) changes sort order, still wrong DISAGREE Reproduced, but PRE-EXISTING and independent: on unfixed master at max_threads=4 (no narrowing) the same query already returns 0,2,255,1. Root cause is a different path — child→Merge conversion appended after child-side sort — unrelated to narrowing. Out of scope (one-concern); noted for a separate follow-up.
2 ⚠️ Test never exercises the WithMergeableState guard arm (DISTINCT suggestion) DISAGREE The suggested DISTINCT ... ORDER BY returns the correct 1297,1294,1291 on unfixed master, because DISTINCT sets input_order_info which already triggers the pre-existing should_not_narrow clause — so it does not discriminate the arm. Adding it would be a non-discriminating test line. Kept the arm (mirrors the planner).
3 💡 min/max/count full-order check is order-insensitive AGREE — fixed Replaced with order-sensitive head (top-2 DESC = 1297,1294) and tail (bottom-2 ASC = 0,3); both fail on unfixed, pass on fixed.
4 ⚠️ Stage matrix: stage-3 (WithMergeableStateAfterAggregation) boundary untested AGREE — fixed Added group by + DESC, no_merge=2, push_down_limit=0 (reaches the after-aggregation stage; fails on unfixed 297,294,291, passes on fixed). The stage-1 sub-suggestion is the same non-discriminating DISTINCT case as #2 → not added.
5 💡 no-parallel avoidable AGREE — fixed Converted .sql → parallel-safe .sh: shard tables named t_${CLICKHOUSE_DATABASE} in the shared shard_0/shard_1 (created-not-dropped), Distributed/Merge in the per-test DB. Removed no-parallel. 50/50 randomized runs pass.
6 💡 Comment: ConcatProcessor preserves per-input order; only global sortedness is lost AGREE — fixed Reworded to "narrowPipe's concatenation does not preserve [per-stream sortedness]"; also trimmed to the local invariant (detailed mechanism lives in the commit message).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-6:20260722-160600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @davenger — could you review this? It fixes wrong results for a global ORDER BY ... LIMIT reading a Distributed table through a Merge engine: ReadFromMerge narrowed (concatenated) the per-shard-sorted streams, so the outer merge-only sort had a single unsorted input and LIMIT returned one shard's local top rows. The fix extends the existing should_not_narrow guard to keep the sorted per-shard streams so the global merge runs (issue #111211).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d58cf12]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_llvm_coverage, 6/8) FAIL
test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies FAIL cidb
Stress test (arm_debug) FAIL
Cannot start clickhouse-server FAIL cidb
Logical error: Sort order of blocks violated for column number A, left: B, right: C. Chunk D, rows read E.F (STID: 3413-350b) FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR makes ReadFromMerge::initializePipeline preserve per-stream ordering when a Merge table reads partial-stage Distributed children whose results are later combined by a merge-only ORDER BY. The follow-up test updates now cover the previously missing unbounded ORDER BY path, the multi-child WithMergeableState arm, and the DISTINCT regression case discussed on the PR. I did not find a remaining correctness, compatibility, or coverage issue in the current diff.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
The existing assertions all read through a LIMIT, so the merge-only
SortingStep always carried a sort limit. An ORDER BY without LIMIT keeps
that step unbounded, which is a distinct code path (SortingStep treats a
zero sort limit differently). Verified locally that this unbounded case
returns per-shard-local order before the fix and global order after it,
so add two no-LIMIT monotonicity assertions (new and old analyzer) on the
existing tables.

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

Copy link
Copy Markdown
Collaborator Author

Good catch, addressed in 70afc67. Confirmed locally that the no-LIMIT path is genuinely a separate case and was broken before the fix:

  • The merge-only sort is chosen from the processing stage + aggregation state, not from LIMIT (Planner.cpp addMergeSortingStep), so an unbounded ORDER BY takes the same narrowPipe path. EXPLAIN PLAN description=1 shows the inner Sorting step carries no Limit in this case, whereas an outer LIMIT gets pushed down into it (so an outer-limit wrapper would not exercise the unbounded path).
  • Pre-fix: SELECT w FROM merge_t ORDER BY w DESC (no LIMIT) returned shard 0's local values (297, 294, 291, ...) instead of the global top (1297, 1294, ...); the monotonicity check returned 0. Post-fix it returns 1 for both analyzers.

Added two no-LIMIT assertions on the existing tables:

SELECT arraySort(x -> -x, groupArray(w)) = groupArray(w) FROM (SELECT w FROM merge_t ORDER BY w DESC)

DESC is used deliberately: shard 0 (max 297) concatenates before shard 1 (min 1000), so a broken global sort is non-monotonic and the check fails. 50/50 runs pass with randomized settings.

…R BY

The regression test only matched a single child (^dist$), so getQueryProcessingStage
returned the child's after-aggregation stage and every assertion exercised the
should_not_narrow after-aggregation arm. When a Merge matches two or more partial-stage
children the stage is capped to WithMergeableState, where the guard instead relies on the
WithMergeableState && !need_aggregate && !has_window arm. With the default
distributed_aggregation_memory_efficient = 1 the pre-existing memory-efficient clause
already covers that shape, so the arm is only load-bearing when the setting is 0.

Add a second Distributed table (disjoint higher range) and a Merge matching both children,
asserting a globally monotonic no-LIMIT ORDER BY under distributed_aggregation_memory_efficient = 0
(new and old analyzer). Verified the assertion fails when the WithMergeableState arm is removed.

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

Copy link
Copy Markdown
Collaborator Author

Added in ab68ff2. Confirmed the second arm (common_processed_stage == WithMergeableState && !need_aggregate && !has_window) is reachable and was previously untested:

  • When Merge matches two children the common stage is capped at WithMergeableState (StorageMerge.cpp, std::min(stage_in_source_tables, WithMergeableState) for selected_table_size > 1), so a no-LIMIT global ORDER BY over such a Merge takes this arm rather than the after-aggregation arm.
  • Added merge_multi over two disjoint-range Distributed tables and a no-LIMIT monotonic ORDER BY w DESC assertion on it (both analyzers, distributed_aggregation_memory_efficient = 0 so the older memory-efficient guard cannot mask this arm).
  • On a build with only this arm removed, the two new assertions return 0 (shard-local order) while every prior assertion still passes; with the arm present all pass. So dropping the branch now fails the test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ab68ff2

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Logical error '!part.empty()' (STID 2735-47bf) crash (chronic trunk, ~34 unrelated PRs/30d, 0 master; real abort is a multiply type-mismatch in the header dry-run path via 03915_exchange_tables_race.sh TOCTOU under the old analyzer; the !part.empty() label is a coverage-log scraper misattribution to a comment in a co-located test) #109747 (ours, open)

Not PR-caused: this PR's diff is Fix ORDER BY not applied globally when reading Distributed through Merge (Planner sort step + a stateless regression test), unrelated to the coverage old-analyzer partial-result-evaluation abort. Only 1 of the 12 coverage shards is affected; all others green. Tracking issue #110133.

Session id: cron:our-pr-ci-monitor:20260723-063000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ab68ff2

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / Logical error '!part.empty()' (STID 2735-47bf) + Server died chronic trunk crash (0 master, ~25 unrelated PRs/30d; scraper mislabels it !part.empty(), real abort is the multiply Int256 vs Float64 header dry-run on the old-analyzer 03915 TOCTOU path) #109747 (ours, open)
Mergeable Check / PR rollup of the above owned via #109747
CH Inc sync - CH Inc sync (private, not actionable by us)

Not PR-caused: this PR's diff is a 10-line StorageMerge.cpp should_not_narrow guard + one stateless test; it cannot produce an old-analyzer AST partial-result abort. The failing STID is pre-existing trunk flakiness across many unrelated PRs.

Session id: cron:our-pr-ci-monitor:20260723-073000

Same root cause as the ORDER BY case (issue ClickHouse#111211): narrowPipe concatenates the
per-shard-sorted streams, so DISTINCT + optimize_distinct_in_order dedups only adjacent
rows and the second shard's run survives, doubling the result multiset. The existing
should_not_narrow guard already covers this query shape (WithMergeableState without
aggregation/window), so this adds a regression case only.

Count the bare query's output rows rather than SELECT count() over it: count() lets the
optimizer drop the inner ORDER BY, which makes narrowing harmless and hides the bug.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (DISTINCT regression case, click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds; bounded: 1 full pass + 1 fix round + 1 delta recheck). Scope: the added DISTINCT regression case (no source change; the existing should_not_narrow guard already covers this shape).

# Sev Finding Verdict Evidence / action
1 ⚠️ DISTINCT assertions do not pin optimize_distinct_in_order, so a randomized run with it 0 would pass even with the fix reverted (hash dedup returns 21 regardless of order) AGREE — fixed Pinned optimize_distinct_in_order = 1 in all 3 DISTINCT queries. Re-verified both directions with the pin: pristine build 42/42/42 (test FAILS), fixed build 21/21/21 (test PASSES). Harness randomizes it at tests/clickhouse-test:1423.
2 💡 Draft description used abbreviated Closes #111211. rather than the full-URL Closes: line AGREE — fixed PR body rebuilt from the upstream template with a visible Closes: <full-url> line.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. This delta re-review had no DISAGREE/DEFERRED.

Session id: cron:clickhouse-premium-slot-26:20260724-082500

@groeneai

Copy link
Copy Markdown
Collaborator Author

Added a DISTINCT regression case in 3bcaddf (reported by @ zlareb1 on #111211): the same narrowPipe concatenation doubles the result multiset under DISTINCT, and that shape is already covered by the guard in this PR, so no code change was needed. The test counts the bare query's output rows (a SELECT count() wrapper lets the optimizer drop the inner ORDER BY and hides the bug) and pins optimize_distinct_in_order = 1 (with it 0, hash dedup masks the bug). Verified both directions: 42 rows unfixed, 21 fixed; 50/50 randomized runs pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3bcaddf

Every failure below has an owner (an open fixing PR). Neither is caused by this PR's diff (src/Storages/StorageMerge.cpp ORDER-BY-over-Merge-over-Distributed sort step + test 04545_order_by_merge_over_distributed.sh): neither the named-collection startup path nor the metric_log rotation path is touched here.

Check Reason Owner / fixing PR
Stress test (amd_asan_ubsan): Cannot start clickhouse-server Re-attaching a URL(...) table (04320_url_engine..._nc) on stress restart hits NAMED_COLLECTION_DOESNT_EXIST (chronic named-collection-not-restored startup family, not this PR) #110529 (ours, open)
Upgrade check (amd_release): Error message in clickhouse-server.log system.metric_log rotation metadata (273438 bytes) exceeds max_query_size (262144), QUERY_IS_TOO_LARGE (trunk regression, not this PR) #111703 (external, open)

Reports:

Session id: cron:our-pr-ci-monitor:20260724-160000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3bcaddf

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in server.log: system.metric_log rotation metadata (273438 bytes) exceeds max_query_size (QUERY_IS_TOO_LARGE, Code 229) trunk regression fixing PR #111703 (merged 2026-07-24 17:24Z), NOT yet on this branch (head predates the merge) -> merging master to pick it up
Stress test (amd_asan_ubsan) / Cannot start clickhouse-server: There is no named collection 04320_url_engine_..._nc (Code 669 -> load job 695 -> startup 722) flaky (restart load-order: URL table references a named collection missing at startup) fixing PR #110529 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

No PR-caused failure: #111464's diff is a 10-line StorageMerge should_not_narrow guard + the 04545 stateless test; it touches neither system-log rotation nor named-collection startup loading.

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d58cf12

Every failure below has an owner: a fixing PR (ours 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
Integration tests (amd_llvm_coverage, 6/8) / test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies flaky (RabbitMQ SYSTEM REFRESH backlog on a stopped table; 28 hits / 14 unrelated PRs / 3 master, 30d) #111480 (mine, open)
Stress test (arm_debug) / Logical error: Sort order of blocks violated ... (STID 3413-350b) trunk bug (Float64 fuzzer sort-order violation; 14 hits / 13 unrelated PRs / 1 master, since 2026-06-26) #108550 (mine, open)
Stress test (arm_debug) / Check failed + Cannot start clickhouse-server collateral from the STID 3413-350b server abort above (same job, same run) #108550 (mine, open)
Mergeable Check / PR rollup of the above resolved via the owners above

This PR's diff is a 10-line StorageMerge.cpp should_not_narrow guard plus the 04545_order_by_merge_over_distributed test. None of the failures above is in a code path it touches; none is PR-caused.

Session id: cron:our-pr-ci-monitor:20260725-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #112931 (merged 2026-08-12), which fixes the same defect in the same lines of ReadFromMerge::initializePipeline. Closing this.

Its predicate is a strict superset of mine. With FetchColumns=0, WithMergeableState=1, Complete=2, WithMergeableStateAfterAggregation=3:

Over every (stage, need_aggregate, has_window, has_order_by) combination there is no case where mine suppresses narrowPipe and #112931 does not. #112931 also covers the Complete stage and adds the inverse guard mine lacked: a window-function query is processed only to WithMergeableState with no remote sort, so its pipe must still be narrowed.

Verified on master 068ec6d2ae62 (build id 594b0c0ef23ed1fa), two shards, max_threads = 1: #111211's repro SELECT w FROM merge_t ORDER BY w DESC LIMIT 3 returns 1297 1294 1291 on both analyzers (the bug returned 297 294 291), the no-LIMIT monotonicity check is 1, and my test 04545_order_by_merge_over_distributed.sh matches its reference exactly. As a control, the same fixture still shows per-shard concatenation (297 294 291 1297 1294 1291) under distributed_group_by_no_merge = 1, so the pass is not vacuous.

#112931 carries tests for both arms (04666_merge_over_distributed_order_by, 04813_merge_over_distributed_window_narrow), so nothing here needs re-landing. Mine additionally has a GROUP BY with distributed_group_by_no_merge = 2 arm and a DISTINCT arm; the overlap with 04666 is large, so I am not sending those separately unless wanted.

Note that #111211 is still open. It reproduced independently of #79949, which #112931 closed, but the verification above shows the same commit fixes it.

@groeneai groeneai closed this Aug 13, 2026
@groeneai groeneai added question Question? and removed question Question? labels Aug 14, 2026
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants