Skip to content

Fix a hang in the always_read_till_end drain of sorted merges - #116051

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-merge-always-read-till-end-drain-hang
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-merge-always-read-till-end-drain-hang

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 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):

Fix a hang in a sorted merge when exact_rows_before_limit is enabled. A query with LIMIT over sorted remote streams could stop making progress after the merge reached its limit, because the merge waited for an input that had already finished. In debug and sanitizer builds this surfaced as a Pipeline stuck logical error instead.

Description

Closes: #114723

IMergingTransformBase::prepare reads every source to the end when always_read_till_end is set
(from exact_rows_before_limit), so rows_before_limit_at_least stays exact. That drain returned
NeedData unconditionally after touching the first unfinished input.

InputPort::isFinished() is masked by a buffered chunk: a producer may push its last chunk and
finish within one prepare, and until that chunk is consumed the input reports not-finished. The
drain therefore picked such an input, pulled the chunk (after which the input really is finished)
and then waited on it. Its producer was already Finished and emitted no further event, so nothing
rescheduled the merge. It stayed parked in NeedData while a later input remained back-pressured:
in a release build the query hangs; in debug and sanitizer builds finalizeExecution throws
Pipeline stuck.

The fix re-checks the input after the pull and continues to the next one, returning NeedData only
while some producer can still deliver. LimitTransform, the only other always_read_till_end
drain, already does this. When every input turns out finished, control falls through into the
existing completion path.

Reachable on unpatched master via a Distributed table read through remote(): 17 Pipeline stuck
rows across 15 distinct pull requests since 2026-07-22, on AST fuzzer and BuzzHouse in the
debug, ASan+UBSan, MSan and TSan builds.

Validation: the added case in 03408_limit_by_rows_before_limit_dist fails on master and passes
with the fix (50/50 randomized runs clean). The drain's purpose is preserved: reported
rows_before_limit_at_least is byte-identical before and after across 25 query/max_threads
combinations. All 13 IMergingTransformBase subclasses share this prepare, but 12 hardcode
always_read_till_end = false, so only MergingSortedTransform reaches the changed loop.

Not addressed here: the exact rows_before_limit_at_least count for plan-based parallel replicas,
which #114723 also asks for. That needs the per-replica sort to become unbounded
(applyParallelReplicas.cpp carries a FIXME for it) and was not re-tested against this change.


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


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


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

IMergingTransformBase::prepare reads every source to the end when
always_read_till_end is set (from exact_rows_before_limit), so that
rows_before_limit_at_least stays exact. That drain returned NeedData
unconditionally after touching the first unfinished input.

InputPort::isFinished() is masked while a pushed chunk is unconsumed: a
producer may push its last chunk and finish within one prepare, and until
that chunk is pulled the input reports not-finished. The drain therefore
picked such an input, pulled the chunk - after which the input really is
finished - and then waited on it. Its producer was already Finished and
emitted no further event, so no edge was queued for the merge and nothing
rescheduled it. The merge stayed parked in NeedData while a later input
remained back-pressured. In a release build the query hangs; in debug and
sanitizer builds PipelineExecutor::finalizeExecution throws
"Pipeline stuck".

Re-check the input after the pull and continue to the next one, returning
NeedData only while some producer can still deliver. LimitTransform, the
only other always_read_till_end drain, already does this. When every
input turns out finished, control falls through into the existing
completion path rather than duplicating it.

Reachable on master without any patch through a Distributed table read
via remote(): 17 "Pipeline stuck" rows across 15 distinct pull requests
since 2026-07-22, on AST fuzzer and BuzzHouse in six build flavours.

The added case in 03408_limit_by_rows_before_limit_dist aborts on master
and passes with this change, 50/50 randomized runs clean. Reported
rows_before_limit_at_least is byte-identical before and after across 25
query and max_threads combinations, so the drain's purpose is preserved.
All ten IMergingTransformBase subclasses share this prepare, but nine
hardcode always_read_till_end = false, so only MergingSortedTransform
reaches the changed loop.

Closes: ClickHouse#114723
The case added for the always_read_till_end drain hang asserted
rows_before_limit_at_least without pinning prefer_localhost_replica, which
tests/clickhouse-test randomizes 0/1 per run. The setting selects the
local-vs-remote branch for a local shard in SelectStreamFactory, which changes
how many legs the rows_before_limit counter observes: 33 with a local shard, 44
without. The case was therefore nondeterministic under CI settings
randomization.

Pin prefer_localhost_replica = 1 in the query's own SETTINGS clause and set the
reference to that topology's value. A query-level SETTINGS beats runner
injection, so this pins one setting rather than disabling randomization for the
whole file, and the four pre-existing cases keep their current topology and
values.

The value 1 is pinned rather than 0 because 0 does not reproduce the hang: on
the pre-fix build the pinned query passes 20/20 with prefer_localhost_replica =
0 and dies with 2 Pipeline stuck lines with = 1. Pinning 0 would have shipped a
regression test that cannot fail.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, all findings adjudicated)

An independent model reviewed this change cold in two rounds, plus my own review of the
resulting code. Findings and verdicts:

Round 1: one real defect, fixed

❌ The regression test was nondeterministic (fixed in 6293056). The new case asserted
rows_before_limit_at_least without pinning prefer_localhost_replica, which
tests/clickhouse-test:1519 randomizes per run. That setting selects the local-vs-remote
branch for a local shard (SelectStreamFactory.cpp:226), which changes how many legs the
counter observes: 33 with a local shard, 44 without. Fixed by pinning the setting in the
query's own SETTINGS clause and setting the reference to that topology's value.

= 1 is pinned rather than = 0 because = 0 does not reproduce the hang: on the pre-fix
build the pinned query passes 20/20 with = 0 and dies with Pipeline stuck with = 1.
Pinning 0 would have shipped a regression test that cannot fail.

The pin is verified live in both directions: with the runner injecting prefer_localhost_replica 0
the query-level pin wins and the test passes; with the pin deleted and nothing else changed the
same injection flips the value 33 -> 44 and the test fails. So the runner does reach this query
and the pin genuinely overrides it.

Round 2: clean

⚠️ One style nit, not applied: that the comment should write isFinished rather than
isFinished(). The premise does not hold for this subsystem. In src/Processors, comments
referring to a method with application parentheses outnumber the bare form 49 to 17
(ExecutorTasks.cpp:110, :251, Parquet/Decoding.cpp:1329). The committed form follows the
dominant local convention.

Also verified against the code

  • InputPort::isFinished() is masked while a pushed chunk is unconsumed (Port.h:347), so
    re-checking after the pull is the correct predicate.
  • LimitTransform, the only other always_read_till_end drain, already re-checks after its
    drain pull, so this restores a convention rather than inventing one.
  • All 13 concrete IMergingTransformBase subclasses were enumerated independently; 12 pass
    always_read_till_end_ = false literally, so only MergingSortedTransform reaches the
    changed loop.
  • The drain's purpose is preserved: reported rows_before_limit_at_least is byte-identical
    before and after across 25 query/max_threads combinations.
  • The added case fails on unpatched master (server abort, Pipeline stuck) and passes 50/50
    under settings randomization with the fix.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6293056]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR fixes IMergingTransformBase::prepare so the always_read_till_end drain re-checks an input after pulling its buffered last chunk instead of waiting on a producer that has already finished, and it adds a deterministic stateless regression case for the nested remote-stream shape that previously wedged the pipeline. I did not find any remaining correctness, compatibility, or test-contract issues in the current diff.

Final Verdict

✅ No blocking issues found in the current patch.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · 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 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
Check Result
a Deterministic repro 20/20 aborts on unpatched master at max_threads = 16 (also 10/10 at 32); one concrete query, no patch needed. Oracle is the Pipeline stuck signature in the server log, never an exit code or wall-clock.
b Root cause explained InputPort::isFinished() is masked while a pushed chunk is unconsumed (Port.h:347), so the always_read_till_end drain (IMergingTransform.cpp:216-229) picks an input, pulls its last chunk, and then waits on it. Its producer is already Finished and emits no further event, so no edge is queued for the merge and nothing reschedules it.
c Fix matches root cause Corrects the return condition at the defect site. No widened bound, no no-random-* tag, no watchdog, no change to the finalizeExecution assertion that detects it, no change to the port protocol.
d Test intent preserved / test added Existing assertions untouched; one case appended to 03408_limit_by_rows_before_limit_dist, which exists to pin rows_before_limit_at_least.
e Both directions demonstrated Query level: base 19-20/20 stuck vs fix 0/20 (0/10 at max_threads = 32). Test level: base FAILs on run 1 with two Pipeline stuck lines; fix 50/50 randomized runs clean. Discriminating control: same binary and query with exact_rows_before_limit = 0 gives 0/6, with = 1 gives 6/6 - the control lands on exactly the branch being changed.
f General across code paths Fixed in the shared base prepare(), not guarded at the wedge site. All 13 IMergingTransformBase subclasses share it and none overrides it; 12 hardcode always_read_till_end = false, so only MergingSortedTransform reaches the loop. LimitTransform, the only other always_read_till_end drain, already re-checks after its pull (LimitTransform.cpp:206-210).
g Generalizes across inputs max_threads in {1, 2, 3, 16, 32}; exact_rows_before_limit 0 and 1; single- vs two-level nesting; nine single-element reductions of the query, each of which stops reproducing, so the trigger is fully determined.
h Backward compatible No setting default, no format, no serialization change, so no SettingsChangesHistory.cpp entry. Pure control-flow correction inside one existing branch.
i Invariants preserved The drain exists so rows_before_limit_at_least is exact, so this was the headline risk: reported values are byte-identical between the two builds across 25 query/max_threads combinations. The completion path is reached by fall-through rather than duplicated; the always_read_till_end = false and have_all_inputs = false paths are untouched. Regression sweep over 123 merge-subsystem tests found zero failures that do not reproduce identically on unpatched master.

Validated on a Debug build. A TSan arm was not run locally; CI covers the sanitizer flavours.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @novikd, could you review this? The always_read_till_end drain in IMergingTransformBase::prepare returned NeedData after pulling an input whose isFinished() was masked by its own buffered chunk, so the merge waited on a producer that had already finished and nothing rescheduled it. LimitTransform, the only other such drain, already re-checks after the pull.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6293056ae with master 4faa0468e (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 706.02 MiB 702.99 MiB -3.03 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, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6293056

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
Stress test (amd_debug) / Hung check failed, possible deadlock found uninterruptible CPU work in h3 polygon size estimation, not a deadlock a fix task is created (investigating at full effort - fixing-PR link to follow here)

Not caused by this PR. The hung query is a fuzzer-widened
h3PolygonToCellsWithContainment([... , (0.0001, 3.4028234663852886e38), ...], 9, 0) over
numbers(200), cancelled at 551.6 s. The hung thread's stack ends in
contrib/h3/src/h3lib/lib/polyfill.c:775 maxPolygonToCellsSizeExperimental via
src/Functions/h3PolygonToCellsWithContainment.cpp:277, with zero futex or condition-wait frames,
so it is unbounded C work inside h3 rather than a lock cycle. This PR's diff is
src/Processors/Merges/IMergingTransform.cpp plus one stateless test pair, and the dump holds
0 IMergingTransform, 0 MergingSorted and 0 always_read_till_end frames, so the code this PR
changes is not on the hung path. Breadth over 14 days for this check and test name: 880 hits across
378 distinct pull requests, including 96 on master.

Session id: cron:our-pr-ci-monitor:20260824-113000

This branch has not been deployed

No deployments
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. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MergingSortedTransform deadlocks in its always_read_till_end drain: NeedData with all inputs finished ("Pipeline stuck")

1 participant