Skip to content

Do not merge-sort the streams of an all-constant full sort fed by a fan-out - #126992

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-pipeline-stuck-constant-sort-parallel-distinct
Oct 21, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-pipeline-stuck-constant-sort-parallel-distinct

Conversation

@groeneai

@groeneai groeneai commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

On master, a sort by constant keys over the parallel final DISTINCT (#114550) fails with Logical error: 'Pipeline stuck', and debug and sanitizer servers abort:

SELECT * FROM (SELECT DISTINCT 'x' AS c, number FROM numbers_mt(100000)) ORDER BY c
SETTINGS max_threads = 4, max_block_size = 100;

A window OVER (ORDER BY <constant>) fails the same way, and so does the fuzzer's ORDER BY ALL over toTypeName(...) columns.

The parallel DISTINCT hands its ScatterByPartitionTransform lanes downstream as separate streams, and a scatter only moves on once every lane has accepted its piece. A sort by constant keys does not buffer (MergeSortingTransform passes chunks through when no key is left), but SortingStep::fullSort still merges the lanes with MergingSortedTransform. With all keys equal, that merge reads only its first input until it finishes, while the other lanes fill up and block the scatters the first input is waiting for.

An all-constant description orders nothing, so when the pipeline contains a fan-out that must push to all of its outputs (requiresAllOutputsPushable(), the test narrowPipe uses since #121227), fullSort now combines the streams with resize(1), the remedy #114626 applied to GatherSendStep. Without such a fan-out the merge stays, so ORDER BY <constant> over UNION ALL keeps returning the streams in order, which tests such as 03721_tuple_inside_nullable_array_element_function rely on. A description with at least one real column always keeps the merge. The helper sortDescriptionIsAllConstant moves from GatherSendStep.cpp to Core/SortDescription so both sites share it.

The new test fails with Pipeline stuck before this change and passes after it (50/50 with randomized settings).

Related: #114550 (introduced the parallel DISTINCT, not in any release yet)
Related: #125514 (where this failure was reported)

Found by AST fuzzer (amd_debug, targeted): CI report.


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

Version info

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

groeneai and others added 2 commits October 20, 2026 16:23
…s all-constant

The parallel final DISTINCT (ClickHouse#114550) hands its ScatterByPartitionTransform
lanes downstream as separate streams, and a scatter holds its input chunk
until every unfinished lane has accepted its piece, so the lanes are coupled.
A full sort normally decouples them, because MergeSortingTransform consumes
its whole input first. When every sort key is a constant, SortingTransform
strips them all and MergeSortingTransform::consume passes chunks through,
yet SortingStep::fullSort still merged the lanes with MergingSortedTransform.
With all keys equal the cursor tie-break is the source number, so the merge
asks for its first input only, until that input finishes. The first lane
finishes only after every scatter has finished, and a scatter cannot finish
while the lanes the merge does not read are full: Pipeline stuck (a logical
error, so debug and sanitizer servers abort).

Reachable without the fuzzer, e.g.
  SELECT * FROM (SELECT DISTINCT 'x' AS c, number FROM numbers_mt(100000))
  ORDER BY c SETTINGS max_threads = 4, max_block_size = 100
and with a window OVER (ORDER BY <constant>). DISTINCT and ORDER BY in the
same SELECT are not affected: preserveInputOrder() forbids the scatter there.

An all-constant description orders nothing, so any interleaving is a valid
result. fullSort now combines such streams with resize(1), whose
ResizeProcessor drains whichever input is ready. This is the remedy that
5e1ec58 (ClickHouse#114626) applied to GatherSendStep for the same wedge; its
helper sortDescriptionIsAllConstant moves to Core/SortDescription so both
sites share it (no behaviour change in GatherSendStep). The stage grouping
used by EXPLAIN PIPELINE is kept, virtual rows are still removed in the
shared non-merge branch, and the top-K threshold tracker is skipped because
it belongs to the merge. A limit on the sorting step is only a hint pushed
down from the LimitStep that stays above it, and the single-stream path
already relied on that, so LIMIT and WITH TIES stay correct.

Found by AST fuzzer (amd_debug, targeted) on
ClickHouse#125514

The new test fails with Pipeline stuck before this change and passes after
it, also 50/50 with randomized settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Restore the original merge comment line and fold the all-constant note into one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ The all-constant resize(1) branch drops the sort's limit_, so a bounded sort can emit more than L rows (SortingStep.cpp:590-594) DISAGREE A limit on a full sort is a hint: the LimitStep that set it stays above and re-applies the bound (limitPushDown.cpp:27-31; topKThroughJoin, vector search and Cascades TwoStageTopN all keep an outer Limit). The single-stream path never applied it for constant keys either (MergeSortingTransform.cpp:103-109). The test's ORDER BY c LIMIT 50000 returns 50000.

Also noticed, not changed: GatherReceiveStep merges per-sender exchange streams without this guard; that is separate distributed-plan code that does not take these streams.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261020-162700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM (SELECT DISTINCT 'x' AS c, number FROM numbers_mt(100000)) ORDER BY c SETTINGS max_threads = 4, max_block_size = 100 aborts a debug build with Pipeline stuck 10/10; the CI query verbatim also reproduces on a server with a two-shard cluster.
b Root cause explained? The parallel final DISTINCT scatters into coupled lanes. A sort by constant keys does not buffer, and SortingStep::fullSort merges the lanes with MergingSortedTransform, which reads only its first input when all keys tie. The other lanes fill and block the scatters that the first input needs.
c Fix matches root cause? Yes. An all-constant description orders nothing, so the merge is replaced by resize(1), which drains any ready input. Same remedy as #114626, shared helper.
d Test intent preserved / new tests added? New SQL test: an EXPLAIN guard that the scatter is present, an outer constant ORDER BY, and a window ordered by a constant. No existing test changed.
e Both directions demonstrated? Yes. Before: stuck 10/10 on each of four shapes, new test fails (server died). After: 10/10 OK, test 50/50 with randomized settings. Pre-#114550 master passes, so this is a regression of #114550.
f Fix is general across code paths? Yes. It covers outer ORDER BY, windows and the pre-join sort through the one fullSort merge; GatherSendStep already had the guard and now shares the helper; mergingSorted cannot follow the scattered lanes.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. LowCardinality, Nullable, LowCardinality(Nullable), NULL, several constants, COLLATE, WITH TIES, LIMIT BY, UNION ALL: all stuck before, all pass after with results equal to pre-#114550 master. A real or mixed key keeps the merge.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization change. Only the row interleaving of an all-constant sort over several streams changes, which no key defines.
i Invariants and contracts preserved? Yes. Output stays sorted by the (constant) description; LIMIT stays enforced by the LimitStep above (a limit on the step is only a pushed-down hint); virtual rows are still removed before leaving the step. 633 sort/window/distinct tests show no fix-only failure.

Session id: cron:clickhouse-impl-slot-7:20261020-153100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @davenger, could you review this and add the can be tested label so CI runs? A sort by constant keys over the parallel final DISTINCT (#114550) merged its coupled scatter lanes with MergingSortedTransform, which drains only the first input when all keys tie, so the pipeline got stuck; SortingStep::fullSort now resizes such streams instead, like #114626 did in GatherSendStep.

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [430c8f7]

Summary: ✅


AI Review

Summary

Prevents the Pipeline stuck exception when an all-constant full sort consumes coupled fan-out streams by combining them with resize(1). Other inputs retain merge sorting. No actionable findings; the focused regression test passed in the Fast test on commit 430c8f7cf6501c9fe09030c435ca1c3fffa5742f.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 20, 2026
@davenger davenger added the can be tested Allows running workflows for external contributors label Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 20, 2026
…feeds it

Resizing every all-constant full sort changed the output order of queries like
`SELECT ... FROM (... UNION ALL ...) ORDER BY tuple()`, which the merge has always
returned in stream order and which tests depend on: 03358_block_structure_match and
03721_tuple_inside_nullable_array_element_function failed in the Fast test, because
a resize interleaves the streams nondeterministically.

With all-constant keys the merge drains its inputs one after another. That only
stalls when a processor upstream must push to all of its outputs before it
consumes again (`requiresAllOutputsPushable`, e.g. the scatter of the parallel
final DISTINCT), so resize only in that case, the same test `narrowPipe` uses for
its `ConcatProcessor`. Everything else keeps the merge and its order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not merge-sort the streams of a full sort whose sort description is all-constant Do not merge-sort the streams of an all-constant full sort fed by a fan-out Oct 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 430c8f7cf with master ecb486e6e (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.

Compile time of recompiled translation units

839 translation units recompiled, 6589 s compile time in total, 816 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Parsers/LogsQL/LogsQLPipes.cpp: 5.2 s

Job report

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 21, 2026
@alexey-milovidov alexey-milovidov added pr-must-backport Pull request should be backported intentionally. Use this label with great care! v26.10-must-backport and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Oct 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit b29785d Oct 21, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 21, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 21, 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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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 v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants