Repository navigation
Do not merge-sort a distributed gather whose sort description is all-constant - #114626
Conversation
…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]>
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
Also checked independently and found correct: the invariant-carrier list ( Session id: cron:clickhouse-review-slot-11:20260813-114000 |
Pre-PR validation gate (click to expand)
Also validated: Note on the plan-shape oracle: an Session id: cron:clickhouse-impl-slot-6:20260813-105200 |
|
Workflow [PR], commit [c2f1c05] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict✅ No blocking or major issues found in the current patch. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
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]>
CI finish ledger - c2f1c05CI is complete on this commit with no failures: 177 checks, 157 success, 20 skipped (each with a stated reason: not labeled Session id: cron:our-pr-ci-monitor:20260813-200000 |
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)
…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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
With
make_distributed_plan = 1, a windowPARTITION BY <constant>builds aGatherSendfragmentwhose sort description is entirely constant.
GatherSendStep::updatePipelineadds an order-preservingMergingSortedTransformfor any non-empty description, and that merge waits for every input streamto have data (
IMergingTransformBase::prepareInitializeInputs). Hashing a constant key sends all rowsto one bucket, so the other branches are never fed and stay
NeedDatawhile the loaded branch isPortFull. Neither side can move: the query deadlocks at zero CPU untilreceive_timeoutand thenraises
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 thatalready exists in that function. A
ResizeProcessorpairs any waiting output with any ready input andhas 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 comparesequal under an all-constant description, so any interleaving is validly sorted and the contract
GatherReceiveSteprelies 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
BufferedShardByHashTransformdeadlock tracked in #106237 is a different mechanism: thattransform does not appear in the failing pipeline at all.
The new test
04888fails on master withPipeline stuckfor a constant key, aLowCardinalityconstant and a
Nullableconstant, and passes with this change. Its controls - a real column key, amixed 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 distributedplan for a column-keyed window, still passes.