Skip to content

Do not merge-sort a distributed gather whose sort description is all-constant - #114626

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-gather-send-const-sort-description
Aug 17, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-gather-send-const-sort-description

Conversation

@groeneai

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

With make_distributed_plan = 1, a window PARTITION BY <constant> builds a GatherSend fragment
whose sort description is entirely constant. GatherSendStep::updatePipeline adds an order-preserving
MergingSortedTransform for any non-empty description, and that merge waits for every input stream
to have data (IMergingTransformBase::prepareInitializeInputs). Hashing a constant key sends all rows
to one bucket, so the other branches are never fed and stay NeedData while the loaded branch is
PortFull. Neither side can move: the query deadlocks at zero CPU until receive_timeout and then
raises Pipeline stuck (a logical error, so the server aborts in debug and sanitizer builds).

An all-constant description orders nothing, so this change takes the pipeline.resize(1) branch that
already exists in that function. A ResizeProcessor pairs any waiting output with any ready input and
has no all-inputs barrier, which is why the code before
4a1ab1e - which replaced an
unconditional resize(1) with this conditional merge - could not wedge this way. Every row compares
equal under an all-constant description, so any interleaving is validly sorted and the contract
GatherReceiveStep relies on still holds. A description with at least one real column keeps the merge.

Related: #113558 (where this failure was reported)
Related: #106237 (context only, different mechanism)

Found by AST fuzzer (amd_debug, targeted, old_compatibility):
CI report.
The BufferedShardByHashTransform deadlock tracked in #106237 is a different mechanism: that
transform does not appear in the failing pipeline at all.

The new test 04888 fails on master with Pipeline stuck for a constant key, a LowCardinality
constant and a Nullable constant, and passes with this change. Its controls - a real column key, a
mixed constant-plus-column key, and the non-distributed plan - pass both before and after, so the
change is narrow. 04837_distributed_plan_window_partition_shuffle, which pins the full distributed
plan for a column-keyed window, still passes.

groeneai and others added 2 commits August 13, 2026 09:50
…constant

With make_distributed_plan = 1, a window PARTITION BY <constant> builds a
GatherSend fragment whose sort description is entirely constant.
GatherSendStep::updatePipeline added an order-preserving MergingSortedTransform
for any non-empty description, and that merge waits for every input stream to
have data (IMergingTransformBase::prepareInitializeInputs). Hashing a constant
key sends all rows to one bucket, so the sibling branches are never fed and stay
NeedData while the loaded branch is PortFull: a const-only description is
stripped in SortingTransform's constructor, after which
MergeSortingTransform::consume passes chunks through instead of draining.
Neither side can proceed, and the query deadlocks at zero CPU until
receive_timeout, then raises the Pipeline stuck logical error.

An all-constant description orders nothing, so take the pipeline.resize(1)
branch that already exists in that function. A ResizeProcessor pairs any waiting
output with any ready input and has no all-inputs barrier, which is why the code
before 4a1ab1e (which replaced an unconditional resize(1) with this
conditional merge) could not wedge this way. Every row compares equal under an
all-constant description, so any interleaving is validly sorted and the contract
GatherReceiveStep relies on still holds. A description with at least one real
column keeps the merge.

GatherReceiveStep is deliberately left alone: it merges independent per-bucket
exchange sources with no shared upstream scatter, so its wait-for-all-inputs
cannot form a cycle, and changing it would alter delivered order for real
descriptions.

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

The new test fails before this change with Pipeline stuck for a plain constant,
a LowCardinality constant and a Nullable constant, and passes after it. Its
controls (a real column key, a mixed constant-plus-column key, and the
non-distributed plan) pass both before and after.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test only compared row counts, and pipeline.resize(1) loses no rows, so
every arm stayed green whichever branch GatherSendStep took. A widened
predicate that also matched a real column would not have reddened the file,
and the results-equivalence arm never reached the new branch at all:
PlannerWindowFunctions builds full_sort_description as partition_by ++
order_by, so PARTITION BY 'c' ORDER BY a, v yields ('c', a, v), which is not
all-constant.

Assert the gather's rendered sort description instead, once per branch. The
constant arm must render sorted by ('c'_String ASC) and the column arm
sorted by (a ASC), which also fails if no distributed plan was built at all,
since a local plan has no GatherExchange line to match. The mixed key
renders both components, so neither pattern matches it.

The subquery form is used rather than pinning the whole EXPLAIN output, and
make_distributed_plan is repeated inside the subquery because the outer
SETTINGS propagates into it while the outer query itself cannot be
distributed.

Verified by corrupting each pattern in turn: only the corresponding row
flips to 0, and each arm fails to match the other arm's pattern.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds by a separate model reading the resulting code cold, before any of the author's
evidence. Round 1 raised one major finding and bounced it; round 2 re-reviewed the fix and found
nothing blocking. Verdicts below are terminal.

# Finding Verdict
⚠️ The test could not detect a regression of the branch selection. Every arm asserted only count() = 20000, and pipeline.resize(1) loses no rows, so each arm was green whichever branch was taken. The results-equivalence arm did not even reach the new code: PlannerWindowFunctions.cpp:52-54 builds full_sort_description as partition_by ++ order_by, so PARTITION BY 'c' ORDER BY a, v gives ('c', a, v), which is not all-constant. Nothing asserted that a distributed plan had been built at all, so a settings interaction that declined it would have left the file green. AGREE, fixed. Two SELECT ... FROM (EXPLAIN ...) WHERE explain ILIKE rows now pin the sort description each arm gives the gather: sorted by ('c'_String ASC) for the constant key, sorted by (a ASC) for the column key. Corrupting either pattern flips only its own row to 0, neither arm matches the other's pattern, and the mixed key matches neither, so the rows discriminate three shapes rather than being always-true. A local plan has no GatherExchange line, which closes the distributed-plan gap.
💡 Those rows pin the arm's sort description, not the pipeline branch. EXPLAIN renders the plan without building a pipeline (InterpreterExplainQuery.cpp:954-1024 calls buildQueryPipeline zero times, against once in the adjacent EXPLAIN PIPELINE case), and the sorted by (...) text is set during plan.optimize() at makeDistributed.cpp:585 from the sort description alone. So widening the predicate would not change any arm's EXPLAIN output. AGREE, scoped. The rows still do what was asked of them: prove the constant arm reaches an all-constant description and that the plan really is distributed. The remaining half, order preservation for a real column key that a too-broad predicate would break, is covered by committed 04836_distributed_plan_window_partition_order, which byte-compares 600k distributed and local rows for PARTITION BY a.
💡 Would an over-broad predicate escape review entirely? DISAGREE. 04836's own header names this failure mode: "GatherSend collapsed them with ResizeProcessor, which does not preserve order". A widened predicate routes its column-keyed gather to resize(1) and breaks its comparison. It passes on this branch.
💡 sortDescriptionIsAllConstant returns true for an empty description. DISAGREE. Unreachable, and the correct answer if it were reached. The call is guarded by maintain_sort_description &&; the sole producer at makeDistributed.cpp:584 passes a non-empty description, and Planner.cpp:1422 builds the step only when !full_sort_description.empty().
💡 Could plan-fragment serialization strip the constant, making the predicate dead? DISAGREE. The predicate reads the live pipeline.getSharedHeader(), which the worker recomputes bottom-up (Serialization.cpp:230-232) from an ActionsDAG whose COLUMN constant survives serialization (ActionsDAG.cpp:4374-4397) and is reproduced as a ColumnConst; SortingStep::updateOutputHeader passes it through untouched.

Also checked independently and found correct: the invariant-carrier list (GatherReceiveStep left
alone deliberately, since it merges independent per-bucket sources with no shared upstream scatter and
cannot form the cycle); the Not for changelog category, since make_distributed_plan is experimental
and default false and the commit that introduced this merge is not an ancestor of any active release
branch; and that query_plan_max_step_description_length is not randomized by clickhouse-test, so
the new rows are stable under randomized settings (50 of 50 runs).

Session id: cron:clickhouse-review-slot-11:20260813-114000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04888 with distributed_plan_default_shuffle_join_bucket_count = 2, distributed_plan_default_reader_bucket_count = 2, max_threads = 4 and a 5-part fixture aborts on master with Pipeline stuck on 4 of 4 runs, and passes on 4 of 4 runs with this change. The default bucket counts (8/8) do not reach the state, which is why earlier attempts on this signature were negative.
b Root cause explained? Yes. A window PARTITION BY <constant> gives the GatherSend fragment an all-constant sort description. GatherSendStep::updatePipeline adds an order-preserving merge for any non-empty description, and IMergingTransformBase::prepareInitializeInputs returns NeedData until every input has data. Hashing a constant key sends all rows to one bucket, so the other branches are never fed. The loaded branch is PortFull because a const-only description is stripped in SortingTransform's constructor, after which MergeSortingTransform::consume passes chunks through instead of draining.
c Fix matches root cause? Yes. It removes the barrier exactly where the description cannot order rows, by taking the pipeline.resize(1) branch already present in that function. No widened bound, no no-random-* tag, no guard at the abort site.
d Test intent preserved / new tests added? Yes. No existing test was changed or weakened. New 04888_distributed_plan_window_const_partition carries the three failing shapes, three controls, a distributed-versus-local results-equivalence assertion, and two plan-shape assertions pinning the sort description each arm gives the gather: the constant arm must render sorted by ('c'_String ASC), the column arm sorted by (a ASC). Both are real oracles rather than always-true rows: corrupting either pattern flips only its own row to 0, neither arm matches the other's pattern, and the mixed key matches neither. Those rows pin the arm's description and confirm a distributed plan was built; they do not observe the pipeline branch itself, since EXPLAIN renders the plan without building a pipeline. Order preservation for a real column key, which a too-broad predicate would break, is covered by 04836_distributed_plan_window_partition_order, which byte-compares the distributed and local row sequences.
e Both directions demonstrated? Yes. Per arm, with a fresh server and the Build ID asserted on every run. On master the three all-constant arms raise Pipeline stuck; with the change all six arms return 20000. Whole test file: master rc=32, Pipeline stuck present; fixed rc=0, output byte-identical to the reference, 4 of 4 repeats.
f Fix is general across code paths? Yes. Every consumer of maintain_sort_description was enumerated. GatherReceiveStep merges independent per-bucket exchange sources with no shared upstream scatter, so its wait-for-all-inputs cannot form a cycle, and changing it would alter delivered order for real descriptions - left unchanged deliberately. ShuffleSendStep has no such merge (0 occurrences). The remaining readers in makeDistributed.cpp only match plan shapes.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured on both binaries: plain constant, toLowCardinality('c'), toNullable('c'), real column key, mixed constant-plus-column key, and make_distributed_plan = 0. The three constant forms fail on master and pass with the change; the three controls pass on both.
h Backward compatible? (maintainer-approved exception only) Yes. maintain_sort_description serialization is untouched, no setting default changes, so no SettingsChangesHistory.cpp entry and no version gate. make_distributed_plan is experimental and default false, and the commit that introduced this merge is not an ancestor of any active release branch.
i Invariants and contracts preserved? Yes. GatherReceiveStep merge-sorts assuming each bucket's stream arrives sorted; under an all-constant description every row compares equal, so an arbitrary interleaving is sorted and the contract holds. The predicate fails safe: a column name absent from the header, or one with a null column pointer, counts as non-constant and keeps the merge. No new allocation, lock, or error path.

Also validated: 04506_distributed_plan_window_function, 04837_distributed_plan_window_partition_shuffle, 04836_distributed_plan_window_partition_order and 04714_scatter_by_partition_finished_output all pass, and the new test passes 50 of 50 runs with randomized settings enabled.

Note on the plan-shape oracle: an EXPLAIN PIPELINE assertion was considered and dropped. For a distributed plan the initiator renders only ReadFromDistributedPlanSource, and a positive control with a column key rendered identically, so such an assertion would have matched nothing and proved nothing. Plain EXPLAIN is used instead, in the SELECT ... FROM (EXPLAIN ...) WHERE explain ILIKE form, which does render the gather and its sort description. 04837 additionally pins the full distributed plan for a column-keyed window.

Session id: cron:clickhouse-impl-slot-6:20260813-105200

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2f1c05]

Summary: ✅


AI Review

Summary

This PR fixes the GatherSendStep deadlock that appears when a distributed gather is asked to preserve an all-constant sort description: the sender now falls back to resize(1) instead of installing a MergingSortedTransform, and the new stateless test covers the plain constant, LowCardinality, Nullable, identity, and materialize boundary shapes. After tracing the planning and execution paths in the current code and reconciling the existing review thread against the latest patch, I did not find any remaining correctness, compatibility, or test-coverage issues that warrant a new review comment.

Final Verdict

✅ No blocking or major issues found in the current patch.

LLVM Coverage Report

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

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @VighneshPath @davenger, could you review this? A window PARTITION BY a constant gives the GatherSend fragment an all-constant sort description, and the order-preserving merge added in 4a1ab1e waits for every input to have data while hashing a constant key feeds only one, so the fragment deadlocks until receive_timeout and raises the Pipeline stuck logical error. An all-constant description orders nothing, so this takes the resize(1) branch already in that function.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@davenger davenger self-assigned this Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c2f1c05f9 with master 3662ba8a9 (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.73 MiB 688.72 MiB -3.01 MiB (-0.44%)

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, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

An automated review asked whether the deadlock survives for a semantically constant key
that has been materialized to a full column, e.g. PARTITION BY materialize('c'), and asked
for the guard to key off "all rows compare equal" rather than ColumnConst.

Measured on this branch's binary and on its merge-base, five runs each: materialize('c')
completes in ~190 ms on both, so it is not a carrier before the fix either. The reason is
that the deadlock needs the sort description to be EMPTY after SortingTransform's
constructor strips const columns (SortingTransform.cpp:207), which is what makes
MergeSortingTransform::consume take its non-draining pass-through
(MergeSortingTransform.cpp:192-196). That strip tests isColumnConst, the same predicate the
guard uses, so the guard is exactly co-extensive with the condition that creates the
deadlock: a full column is not stripped, the sort really sorts and drains, and the merge
never wedges.

Probing the wider class the review pointed at did find an uncovered firing shape:
identity('c') returns its argument column verbatim (identity.h executeImpl), so the key
stays a ColumnConst. It deadlocks on the merge-base 3/3 with the same processor cast as the
CI report (ScatterByPartition, MergeSorting, MergingSorted, no BufferedShardByHash) and
passes 3/3 with the guard. Both shapes are added: identity('c') pins the newly covered
firing case, materialize('c') pins the boundary. Controls over a real column, identity(a)
and materialize(a), pass on the merge-base, so the arms discriminate on constancy rather
than on the wrapper.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c2f1c05

CI is complete on this commit with no failures: 177 checks, 157 success, 20 skipped (each with a stated reason: not labeled pr-performance, not a bug-fix PR, reused from cache, not affected by the changed files, no Keeper/integration changes). Config Workflow and Finish Workflow both succeeded, no jobs were dropped, and CIDB reports zero FAIL/ERROR rows for this commit. Nothing to own.

Session id: cron:our-pr-ci-monitor:20260813-200000

clickgapai added a commit to clickgapai/ClickHouse that referenced this pull request Aug 17, 2026
04888 is claimed by two open PRs (ClickHouse#114626, ClickHouse#104437); 04913 is free and
unclaimed. The tag comment gave the Replicated reason for both tags.

Requested by @groeneai in ClickHouse#115059 (comment)

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

I found this good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit dcf65e6 Aug 17, 2026
181 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 21, 2026
…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]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants