Skip to content

Fix pipeline-stuck deadlock in BufferedShardByHashTransform - #106251

Merged
alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106237-buffered-shard-by-hash-pipeline-stuck
Aug 23, 2026
Merged

alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106237-buffered-shard-by-hash-pipeline-stuck

Conversation

@groeneai

@groeneai groeneai commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #106237
Related: #104233

BufferedShardByHashTransform::prepare() could deadlock when a downstream ConcatProcessor (from narrowPipe on a UNION ALL with max_streams_for_union_step below the pipeline width) activated its inputs sequentially. Three defects in prepare():

  1. Input-finished path. With the input exhausted and a shard's queue empty, that output port was never finished, so downstream waited forever for a finish signal while the other shards' queued chunks could not drain.
  2. At-capacity path. Once any shard queue hit the MAX_QUEUE_LENGTH soft cap, prepare() returned PortFull even if a sibling port was empty and had canPush(), so that sibling never received data and Concat never advanced.
  3. Cap bypass too broad (found in review). The bypass for (2) fired whenever an empty port was asking, without checking whether another shard's chunk was already pushable. Forward progress existed there, so the transform kept pulling past the cap in topologies that never had the deadlock.

The fix finishes empty-queue ports eagerly once input is exhausted, and narrows the cap bypass to the state that actually deadlocks: a demanded empty port with nothing drainable. Of the eight flag combinations only one changes behaviour, from pulling to Ready, which drains it. No state gains a PortFull.

Two follow-ups on top of that. A chassert(has_queued_chunks) added while reviewing the second loop was wrong and is removed: prepare holds only this node's status_mutex, so a downstream processor on another thread can close one of our output ports between the two loops, and the second loop then skips that now-finished output. The behaviour on that path is unchanged, and the port state change schedules another prepare that returns Status::Finished. Separately, MAX_QUEUE_LENGTH now documents why its escape cannot be bounded here: ConcatProcessor::prepare makes a single input needed at a time and advances only when it finishes, so buffering the not-yet-demanded shards is inherent to that topology; honouring the cap deadlocks instead, and overflow surfaces as a tracked-memory limit exception rather than Pipeline stuck.

Reproducer, deadlocking on the first run without the fix:

CREATE TABLE t (a UInt64, b UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT 0 AS a, number AS b FROM numbers(100000);
INSERT INTO t SELECT 1 AS a, number AS b FROM numbers(100000);
INSERT INTO t SELECT 2 AS a, number AS b FROM numbers(100000);

SELECT a, max(s)
FROM (
    SELECT a, sum(b) AS s FROM t GROUP BY a
    UNION ALL
    SELECT a, sum(b) AS s FROM t GROUP BY a
)
GROUP BY a
SETTINGS enable_sharding_aggregator = 1, max_threads = 5, max_streams_for_union_step = 1;

04342_sharded_aggregation_pipeline_stuck asserts both deadlock shapes and both cap paths. Reverting prepare() to its pre-PR form reproduces Pipeline stuck, so the test still covers the bug.

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 Logical error: 'Pipeline stuck' in queries that use enable_sharding_aggregator = 1 together with a UNION ALL and max_streams_for_union_step smaller than the pipeline width. BufferedShardByHashTransform now finishes empty-queue output ports as soon as its input is exhausted, and keeps pulling input when a demanded empty port has nothing drainable even if a sibling queue hit the back-pressure cap.


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

Version info

  • Merged into: 26.8.1.1955 (included in 26.8 and later)

`BufferedShardByHashTransform` had two prepare() bugs that deadlocked the
pipeline when a downstream consumer activated its inputs sequentially
(e.g. `ConcatProcessor` from `narrowPipe` on a `UNION ALL` with
`max_streams_for_union_step` < pipeline streams).

Scenario: data hashes to only a subset of shards (skewed keys, low
cardinality), so some output ports keep empty queues while sibling
ports fill up. A `Concat` downstream pulls from the empty-queue
branch first; the queued shards stay back-pressured because `Concat`
never advances to them.

Bug 1 (input-finished path): when input is exhausted and a shard's
queue is empty, `prepare()` never finished that output port. The
downstream waited forever for a finish signal, and the queued chunks
on other shards never drained because `Concat` never moved on.

Bug 2 (input-not-finished, queue-at-capacity path): the soft memory
cap (`MAX_QUEUE_LENGTH`) returned `PortFull` as soon as any queue hit
the limit, even when a sibling port had an empty queue and was
actively asking for data (`canPush() == true`). The active sibling
could never receive data, so `Concat` never advanced and the cap'd
queues never drained.

Fix:
  1. Finish empty-queue output ports eagerly in the first pass when
     `input.isFinished() && !has_pending_input_chunk`. Downstream of
     the empty shards then sees `Finished` and proceeds.
  2. Bypass the cap-induced `PortFull` when at least one empty port has
     `canPush() == true`. The deadlock priority outweighs the soft
     memory bound; a brief overshoot lets the asking path receive data
     while preserving forward progress.
  3. Track `has_pushable_empty_port` and require `has_pushable_queued`
     OR `has_pushable_empty` to make any forward-progress claim.

Closes: ClickHouse#106237
Related: ClickHouse#104233
@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker procedure):

a) Deterministic repro? Yes — the SQL reproducer in the PR description fires Logical error: 'Pipeline stuck' on the first try on master 501f0bf33a18; verified locally before and after the fix.
b) Root cause explained? Yes — see PR description: empty-queue outputs were never finished when input was exhausted, and the cap-induced PortFull ignored sibling empty ports that had canPush() == true. With ConcatProcessor activating inputs sequentially, the active path waited on shards that received no data while the queued shards were never advanced to.
c) Fix matches root cause? Yes — prepare now finishes empty-queue outputs when input.isFinished() && !has_pending_input_chunk, and bypasses the soft-cap PortFull when at least one empty port has canPush() == true. Both changes are at the exact branch the root-cause analysis identified.
d) Test intent preserved / new test added? New regression test 04305_sharded_aggregation_pipeline_stuck_106237. All 9 existing *_sharded_aggregation_* tests (03927, 03928, 04070, 04097-04100) still pass. No existing test was relaxed.
e) Both directions demonstrated? Yes — unfixed binary: Logical error: 'Pipeline stuck' (server died) on the first iteration. Fixed binary: 30/30 randomized runs of 04305 pass; broader aggregation suite passes.
f) Fix is general? The two prepare branches are the only places that decided to back-pressure without checking sibling empty ports. I checked ScatterByPartitionTransform (similar 1->N scatter shape) and it has a related but distinct state machine; its only caller is SortingStep, which does not introduce a ConcatProcessor downstream, so it does not exhibit this deadlock. Leaving that to a follow-up if a reproducer surfaces (per the no-speculative-defensive-code rule).

Session: cron:clickhouse-ci-task-worker:20260601-164500.

@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @nihalzp @KochetovNicolai — could you review this? It fixes the pipeline-stuck deadlock you flagged on #106237: BufferedShardByHashTransform.prepare now finishes empty-queue ports once the input is exhausted, and stops back-pressuring on the soft cap when an empty sibling port has canPush (the two states a sequential ConcatProcessor downstream stalled on).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [321cea8]

Summary: ✅


AI Review

Summary

This PR fixes the BufferedShardByHashTransform deadlock when a sequential ConcatProcessor consumes shard outputs one at a time, and the final stateless regression test now guards both the deadlock topology and the soft-cap coverage cases. I rechecked the current code, the full PR discussion, and all existing review threads, and I did not find any new blocker or major issue in the final diff.

Final Verdict

✅ No new findings. The earlier bot-raised issues are either fixed in the current code or were explicitly accepted in the resolved review threads as intended design tradeoffs for this PR.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 39/40 (97.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 1, 2026
Follow-up to the soft-cap bypass in the parent commit: the bypass was
unbounded under pathological hash-key skew. If all rows hash to a single
shard while a sibling output port is empty and downstream is asking on
it, `has_pushable_empty_port` stays true and the bypass never returns
`PortFull`, so each `prepare` keeps pulling another input chunk and
`generateOutputChunks` keeps appending to the one receiving shard until
upstream depletes. For a large skewed query that meant buffering the
whole input on one shard.

Add a hard per-shard limit `MAX_QUEUE_HARD_LIMIT = 2 * MAX_QUEUE_LENGTH`
that is unconditional - even an asking-empty port does not bypass it.
Worst-case per-shard buffering is now `MAX_QUEUE_HARD_LIMIT` chunks;
worst-case total `MAX_QUEUE_HARD_LIMIT * num_shards`. The soft cap and
its forward-progress bypass (which fixes the original `ConcatProcessor`
deadlock) are unchanged for the normal case; only pathological skew
trips the new hard limit. When it fires the pipeline waits and the
eager-finish on `input_finished` (also added in the parent commit)
unblocks it as soon as upstream depletes.

New regression test `04306_sharded_aggregation_pipeline_skew_memory_bound`
exercises the bot-described scenario: a single distinct key value forces
all rows to one shard, and `max_streams_for_union_step = 1` puts a
`ConcatProcessor` downstream. Bot review thread:
ClickHouse#106251 (comment)
@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 874c4f0 addressing the inline bot review:

  • Added MAX_QUEUE_HARD_LIMIT = 2 * MAX_QUEUE_LENGTH = 20 per-shard cap in the header, applied unconditionally in prepare() (an asking-empty port no longer bypasses it).
  • Worst-case per-shard buffering is now MAX_QUEUE_HARD_LIMIT chunks; total MAX_QUEUE_HARD_LIMIT * num_shards. Under pathological skew the pipeline waits at the cap and the eager-finish on input_finished unblocks it as soon as upstream depletes.
  • Soft cap and its forward-progress bypass for the normal ConcatProcessor deadlock case are unchanged.
  • New regression test 04306_sharded_aggregation_pipeline_skew_memory_bound covers the skew path (single distinct key + max_streams_for_union_step = 1).

Both tests pass 60/60 locally with randomized settings.

Session: cron:clickhouse-ci-task-worker:20260601-190000

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai tests failed, check

…rowth

Per bot review thread
ClickHouse#106251 (comment)
the hard cap added in 874c4f0 can reintroduce the same `Pipeline stuck`
deadlock it tried to prevent: when shard X is at the hard cap with its
downstream not asking, shard Y is empty and asking, and input is not
finished, `prepare` returns `PortFull` without `input.setNeeded`. Upstream
is back-pressured forever while the asking shard never gets data because
all rows hash to X.

The fundamental tradeoff: under sequential downstream consumption (e.g.
`ConcatProcessor`) plus pathological hash skew, bounded memory and
forward progress cannot both hold without a spill-to-disk fallback. Pick
forward progress here: revert to the soft cap with bypass-on-demand from
2067a25 and document the consequence. Under skew the receiving shard's
queue grows until upstream depletes, then the eager-finish on empty
ports unblocks the pipeline; memory is bounded by `max_memory_usage`.

A proper bound would require spilling overflow chunks; that is deferred
to a follow-up. The 04306 regression test was specific to the hard cap
and is removed.
@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Investigated.

CI failures:

Reverted the hard cap (commit 874c4f0) in 9645838 per the second bot CR (r3336600336). Bounded memory plus forward progress under sequential downstream consumption and hash skew is impossible without spill-to-disk. The hard cap reintroduced the original deadlock; reverting restores forward progress and accepts that a receiving shard's queue can grow until upstream depletes (bounded by max_memory_usage). Spill-to-disk is deferred.

PR is now the parent fix (commit 2067a25): eager-finish empty-queue outputs when input is exhausted, soft-cap bypass on demand. CI re-running.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 2, 2026
`decodeDataType` for `BinaryTypeIndex::Interval` cast a `UInt8` byte from
the input buffer directly to `IntervalKind::Kind` without validating that
the value belonged to the enum (valid range `0x00`..`0x0A`). Anything in
`0x0B`..`0xFF` produced a `DataTypeInterval` whose internal `kind` was
out of range, after which `IntervalKind::toString` returned
`magic_enum::enum_name` on an unknown value. On libcxx that returns
`std::string_view{nullptr, 0}`, and `SerializationInterval::getHash` then
fed that null pointer into `SipHash::update`, where the unrolled loop
computed `data + 8` on a null pointer (UB per `[expr.add]/4`). UBSan
flagged it via `-fsanitize=pointer-overflow` (STID 3285-3bba).

The primary fix is at the deserialization site: reject any byte above
`IntervalKind::Kind::Year` with `INCORRECT_DATA`. A regression test
`04307_03285_3bba_interval_binary_encoding_invalid_kind` feeds three
malformed bytes (`0x0b`, `0x7f`, `0xff`) through
`RowBinaryWithNamesAndTypes` with
`input_format_binary_decode_types_in_binary_format` and asserts each is
rejected.

The previous `SipHash::update(nullptr, 0)` short-circuit is kept as
defense-in-depth. The accompanying comment is shortened, and the
explanatory blocks in `gtest_sip_hash.cpp` plus the `ASSERT_EQ` on
`std::string_view` internals are removed per review feedback.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106251&sha=874c4f0fc6fa05c7726121221bd18e4185eda64e&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Related: ClickHouse#106251

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…l gtest

The functional test 04305_sharded_aggregation_pipeline_stuck_106237 depended
on scheduler timing to hit the empty-output/queued-sibling state, so it passed
on master HEAD and the Bugfix validation gate reported "Failed to reproduce the
bug". Remove it and add gtest_buffered_shard_by_hash_transform instead.

The gtest drives the deadlock directly: SourceFromChunks (all rows routed to the
last shard) -> BufferedShardByHashTransform -> ConcatProcessor -> sink. Concat
consumes its inputs sequentially and waits on the empty first input; the
transform must finish that empty output once the input is exhausted so Concat
advances to the last shard's queued data. Without the fix the empty output is
never finished and PipelineExecutor reports "Pipeline stuck"; with the fix the
pipeline drains. The test is deterministic: the key is chosen to route to the
last shard via the same WeakHash32 + Lemire mapping the transform uses.

Closes: ClickHouse#106237

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

Copy link
Copy Markdown
Member

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

Push more than MAX_QUEUE_LENGTH skewed chunks so the loaded shard's queue
overshoots the soft cap while the sibling port is empty and asking. This
covers the `any_queue_at_capacity && has_pushable_empty_port` bypass branch
in addition to the empty-output finish path. Replace the discarding sink
with a counting sink and assert every row reached it, proving the queued
chunks drained through `Concat` rather than being dropped.

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

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @alexey-milovidov. The branch already picked up the revert: the merge in c4152b5 includes #106365 (3930f8a, the revert of #104690), so the obfuscator TSan failures should be gone on the next CI run.

Also pushed f8c10c4 addressing the two review-bot notes on the gtest: it now drives 12 skewed chunks (> the soft cap) to exercise the cap-bypass path, and uses a counting sink asserting all 768 rows drain through Concat. Verified both directions locally (reverting the eager-finish reproduces the Pipeline stuck exception; with the fix it passes 10/10).

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: f8c10c4c4bc9c2e06c55dc2d6fb795f138c8a5fe

CI fully finished (Mergeable Check completed; 0 pending checks).

Check Test Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00175_obfuscator_schema_inference flaky chronic trunk — task 2026-06-02-ci-00175obfuscatorschemainference-ab
Unit tests (asan_ubsan) (check-level) infra/chronic UBSan UntrackedMemoryCounter — task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc

No PR-caused failures. Awaiting human review.

Session: cron:our-pr-ci-monitor:20260604-213000

@nihalzp nihalzp 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 do not like that it can lead to unbounded memory usage and MAX_QUEUE_LENGTH is not enforcing at all. Also, add the reproducing query as a stateless test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp Thanks.

Memory bound: agreed the soft cap is best-effort today. Under hash skew (all rows to one shard while the sibling port is asking) it is bypassed, so memory is bounded by max_memory_usage, not MAX_QUEUE_LENGTH. I did try enforcing a hard cap (commit 874c4f0), but the review bot showed it reintroduces the original #106237 deadlock with a sequential consumer (ConcatProcessor): if the capped shard is not the one Concat is currently asking, back-pressuring upstream stops the input from ever finishing, so the empty asking port is never finished and Concat hangs forever (r3336600336). For a sequential consumer, a hard memory cap and forward progress cannot both hold without spilling the overflow.

Which direction do you prefer?
(a) spill overflow chunks to disk in this PR so the cap is truly enforced (bounded memory + forward progress);
(b) land the deadlock fix now and track spill-to-disk as a follow-up (current state, memory bounded by max_memory_usage);
(c) a specific bound you have in mind.

I lean (a) if you want it enforced in-PR, since it is the only way to satisfy both for a sequential consumer.

Stateless test: will add the reproducing query back. One caveat: when it last ran under the Bug Fix Bugfix-validation gate it passed on master HEAD (the stuck state is scheduler-timing dependent; the reporter noted it is "difficult to reproduce"), which is why I had replaced it with the deterministic processor-level gtest. Plan: keep the gtest as the gating coverage and add the SQL reproducer as a plain stateless regression test. Works for you?

@nihalzp

nihalzp commented Jun 16, 2026

Copy link
Copy Markdown
Member

Remove gtest and only keep the stateless sql test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bdd044f

Every failure below has an owner: a fixing PR (mine 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 (arm_debug) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-36d8) pre-existing trunk state, not caused by this branch: 27 rows / 25 carriers / 1 true-master sha over 30 days, onset 2026-07-30, and the DistinctSortedStreamTransform abort frame appears on 126 unrelated PRs and 6 master rows in the same window fixing PR #113242 (mine, open)

Not PR-caused: the abort is DistinctSortedStreamTransform::transform reaching
ColumnVector<UInt32>::getEqualRangeEndAssumeSorted through SortCursor.h, a sorted-range
contiguity assertion that predates this branch and fires across unrelated PRs and master. This
branch touches the buffered shard-by-hash pipeline and cannot reach that assertion.

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

@alexey-milovidov alexey-milovidov self-assigned this Aug 22, 2026
alexey-milovidov and others added 2 commits August 22, 2026 22:06
The soft-cap escape in `BufferedShardByHashTransform::prepare` was documented
only as "bounded only by memory", which reads as an unforced tradeoff. Record
the structural reason instead.

The escape is reachable only under a consumer that activates our outputs one
at a time. `ConcatProcessor::prepare` calls `setNeeded` on a single input and
advances only once that input finishes, so every other shard port reports
`canPush() == false` until then. Buffering the not-yet-demanded shards in full
is therefore inherent to that topology, not something the escape introduces:
any producer feeding a `Concat` has to hold its later inputs rows somewhere.
Honouring the cap instead deadlocks, because the demanded empty queue can only
ever be filled from input. Queued chunks are tracked memory, so overflow
surfaces as a memory-limit exception rather than the `Pipeline stuck` logical
error the cap would cause.

Comment-only change, no behaviour difference.

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

Copy link
Copy Markdown
Member

🕵 Brought this up to date and closed out the two blockers.

Merged current master (c043a7b23de). The branch was 3 days behind and red; master had not touched either transform file, so the merge was clean and the PR diff is unchanged at 4 files.

Both unresolved threads are now decided and resolved.

  • Soft-cap memory tradeoff — accepted as-is, with the reasoning moved into the code at 321cea8464c (comment-only). The deciding fact is ConcatProcessor::prepare: it calls setNeeded on current_input alone and advances only when that input finishes, so the other shard ports are never pushable until then. Buffering the not-yet-demanded shards is therefore inherent to the Concat topology, not introduced by the escape; honouring the cap instead deadlocks, and overflow degrades to a tracked-memory MEMORY_LIMIT_EXCEEDED rather than an unconditional Pipeline stuck. A hard bound needs an overflow/spill path, which is a separate change.
  • Fail-on-base regression — 04342 ships alone, and the PR merges without a Bugfix Validation reproducer. Re-adding the gtest would reverse @nihalzp's 2026-06-16 request and cut against the guideline preferring functional tests. 04342 is not vacuous: its EXPLAIN PIPELINE precondition asserts both BufferedShardByHash and Concat are present. It cannot be made to fail on base, because Add ColumnsScatter::scatter: batched column split with type-index dispatch and bytes-budget input buffering #106120's CRC32C routing rewrite changed the skew distribution.

The one CI failure is a known master defect, not this branch. Stress test (arm_debug) aborted on Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-36d8). The query was SELECT count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_1 ORDER BY s ASC NULLS LAST LIMIT 100) SETTINGS optimize_distinct_in_order = 1, from 04870_distinct_merge_over_distributed.sql, and the stack goes through executeASTFuzzerQueries — the server-side AST fuzzer retyped that test's Merge parent and fed the clone to a SELECT. StorageMerge pushes the sort into a Distributed child and ReadFromMerge::convertAndFilterSourceStream then casts above that sort, so DistinctSortedStreamTransform gets a stream that is not sorted. Tracked as #115455 and #115831; the engine fix is #113242 and the CI amplifier is quieted by #115839. This branch only touches the buffered shard-by-hash pipeline and cannot reach that assertion.

CI is re-running on 321cea8464c.

@nihalzp

nihalzp commented Aug 23, 2026

Copy link
Copy Markdown
Member

@groeneai This is a complex problem to solve without allowing unbounded memory. Let's set MAX_QUEUE_LENGTH to 1 and disable buffering. This is okay since sharded aggregator will be removed soon in favor of adaptive aggregator. This should solve all the problems.

@nihalzp nihalzp self-assigned this Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp MAX_QUEUE_LENGTH = 1 and "disable buffering" turn out to be two different changes. I measured both on 321cea8464c before touching anything.

Setting the constant to 1 on its own is a no-op here, because the cap is soft: when the only demand is an empty output port with nothing drainable, prepare yields the cap and the queue grows past it. Instrumented peak queue depth on the 04342 topology is 3 with the cap at 1 (the escape fires) and 3 with it at 10 (the cap is never reached). Unbounded either way.

Disabling buffering for real means honouring the cap, so dropping that escape. I built that arm and it brings back #106237:

Logical error: 'Pipeline stuck. Current state:
  BufferedShardByHashTransform_10 ... (PortFull)
  Concat_38 ...

That is the same failure as the MAX_QUEUE_HARD_LIMIT attempt in 874c4f0, reverted in 9645838. ConcatProcessor::prepare calls setNeeded on one input and advances only once that input finishes, so the demanded shard's empty queue can only be filled from input while every sibling port refuses to accept. A hard bound needs an overflow/spill path for the over-cap shard.

@ alexey-milovidov resolved this thread the other way at 22:38Z and approved the PR (#106251 (comment)), so I would rather not push against that on my own judgement. If the sharded aggregator is going away soon, do you want the escape left as-is until it is removed, or the spill path added here?

@nihalzp

nihalzp commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

@groeneai I meant remove all the changes you have in this PR and set MAX_QUEUE_LENGTH to 1, making it similar to scatterByPartitions.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp I built that arm: this PR's source diff fully reverted, MAX_QUEUE_LENGTH = 1, nothing else changed. It reproduces #106237.

3 of 3 independent server starts on the 04342 topology abort with the state from the original report:

Logical error: 'Pipeline stuck. Current state:
  BufferedShardByHashTransform_10 ... (PortFull)
  Concat_38 ... (NeedData)

Control in the same session: the pure revert with the constant left at 10 gives the same stuck node states, and current head 321cea8464c passes and returns 0/1/2 = 4999950000. Build ids 1d9aa93b (revert + 1), 48b72e43 (revert + 10), 6706d62f (head). So the value of the constant is not what decides this.

On the scatterByPartitions comparison: ScatterByPartitionTransform has no queue, so it refuses new input until every partition chunk of the current one has been pushed. That is exactly the shape that wedges under a consumer which activates its inputs one at a time, and it is already documented as doing so in optimizeJoinByShards.cpp (ff63b592c39), where a pre-sorted merge-join side is deliberately not scattered because two such scatters "form a circular wait ... seen as Logical error: Pipeline stuck". It stays correct by not being placed under that topology rather than by tolerating it, so adopting its shape in a transform that does sit under a Concat is the arm I measured above.

That leaves the two of you asking for opposite things: this thread was resolved keep-as-is and the PR approved at 21:55Z (#106251 (comment)). I am not going to argue the tradeoff, and I would rather not revert an approved PR on one assignee's word. Pick one and I will do it: leave the escape as-is, add the spill path here, or close this PR if the sharded aggregator is going away soon enough that the deadlock does not need fixing first.

@alexey-milovidov

Copy link
Copy Markdown
Member

Let's merge this, and then do a follow-up.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@nihalzp Alexey ruled merge-now plus a follow-up (#106251 (comment)), so I am not reverting the diff or setting MAX_QUEUE_LENGTH to 1 here. Bounding the queue (an overflow or spill path for the over-cap shard) goes into that follow-up.

Branch left at 321cea8464c.

Merged via the queue into ClickHouse:master with commit 21d083e Aug 23, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated the follow-up (bounding the BufferedShardByHashTransform queue). I have a design
question before writing code, because every bounded design I costed ran into the same fact.

The amplification scales with shard count, not with the queue cap. num_shards = max_threads
(AggregatingStep.cpp:740) and there is one sharder per input stream (:752-763), limited only by
getNumStreams() * max_threads < 100'000 (:335) - so ~90k shard outputs is a legal configuration.
Under a Concat every not-yet-demanded shard accumulates, so any per-shard resource a fix allocates
scales the same way. I costed four shapes and each moved the cost rather than bounding it:

shape why it does not bound
one spill writer per overflowing shard 1 MiB write buffer each (TemporaryDataOnDisk.cpp:399, Defines.h:22) exceeds the queues being bounded
cap writers, others stay in memory "the others" is the original unbounded behaviour, just less frequent
LRU-finalize writers to reuse slots every input chunk touches every shard (:170-175), so segments rotate per chunk - one temp file per chunk
shrink buffers via a child scope reads bypass it: readRaw uses min(compressed_size, DBMS_DEFAULT_BUFFER_SIZE) (:475-477), and the reader count is still ~90k

Two other things I found worth flagging:

  • Spilling here is the write half of external sharded aggregation, whose read/merge half is
    explicitly absent: params.max_bytes_before_external_group_by = 0 with the comment "Sharded
    aggregation does not implement temporary-file spill/merge yet."
    (AggregatingStep.cpp:505).
    So this is a subsystem, not a patch.
  • Chunk byte sizes are not a usable reservation bound: ColumnConst::scatter keeps columns constant
    (O(1) byteSize) but NativeWriter materializes them before serializing (NativeWriter.cpp:73),
    so a constant-heavy chunk reports bytes and writes megabytes.

A cheaper option that nobody has priced yet: cap num_shards (or decline the sharded path above
some shard count). Since the queues scale with it, that bounds them by construction - a few lines, no
spill machinery, no serialization round-trip. It costs parallelism on very wide pipelines, which is
your call rather than mine.

@ alexey-milovidov @ nihalzp - which do you want: the shard-count cap, the full external sharded
aggregation (write + merge), or leave the documented soft-cap escape as-is? I will build whichever
you name.

One correction for the record, since it bears on whether this is worth doing at all: both
aggregators coexist on master today. enable_adaptive_aggregator landed 2026-07-22 in
43f9a8906005025 and defaults true; enable_sharding_aggregator is still declared
(Settings.cpp:4363, default false) and AggregatingStep.cpp:325/:1366 still build the path,
with no removal PR open. If the plan is still to remove the sharded aggregator, closing this is a
reasonable answer too.

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov @nihalzp — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up PR for the queue bound: #116055, closing #116038.

It does not answer the spill question I asked above; it removes a case that was never part of the
trade-off accepted here. The escape fires under a plain Resize + AggregatingTransform consumer as
well, with no ConcatProcessor in the pipeline, so it also applied while the loaded shards were
being drained every cycle. Minimum max_memory_usage for a 16M-row, 4-distinct-key aggregation,
bisected on builds one predicate apart: 389 MiB on master against 17 MiB once the cap holds in that
state. The header comment claiming Concat-only reachability was wrong and is corrected.

The escape stays for the state it was added for: reverting only that predicate reproduces
Pipeline stuck on 04342.

Still open, unchanged: under a Concat no shard can be pushed at all, so the cap genuinely cannot be
honoured there and a hard bound needs an overflow path for the over-cap shard. The cheaper option I
priced in the write-up above, capping num_shards or declining the sharded path above a shard count,
also still stands.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to my note above: the follow-up PR I pointed at (#116055) is closed. @ nihalzp is removing
the feature instead, in #116532, which deletes BufferedShardByHashTransform outright and retires
enable_sharding_aggregator as obsolete, so the queue bound asked for here has nothing left to bound.
04342, the regression test this PR added, goes with it.

That is also a fourth answer to the design question I posted above, so I am standing down rather than
authoring a competing bound: the shard-count cap and the five spill shapes I priced become irrelevant
if #116532 merges. I verified on #116055 that the surviving adaptive path already bounds its staged
rare keys through the ordinary external-aggregation spill, so nothing carries over.

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t_106251 (a UInt64, b UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_106251 SELECT 0 AS a, number AS b FROM numbers(100000);
INSERT INTO t_106251 SELECT 1 AS a, number AS b FROM numbers(100000);
INSERT INTO t_106251 SELECT 2 AS a, number AS b FROM numbers(100000);

SELECT a, max(s)
FROM (
    SELECT a, sum(b) AS s FROM t_106251 GROUP BY a
    UNION ALL
    SELECT a, sum(b) AS s FROM t_106251 GROUP BY a
)
GROUP BY a
ORDER BY a
SETTINGS enable_sharding_aggregator = 1, max_threads = 16, max_streams_for_union_step = 1;

-- 26.7.5.10 / 26.6.3.62: Code: 49. DB::Exception: Pipeline stuck.
-- master (with #106251): 0/1/2 -> 4999950000 each.

Results:

  • Culprit PR: Naive Sharded Aggregation for high cardinality data Naive Sharded Aggregation for high cardinality data #104233
  • Reproduces on: 26.7, 26.6
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 unknown
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

CC introducing PR reviewer: @nickitat

Analysis metadata

comp-aggregation · Severity P2 · Finding phase_d_pr106251

  • Verified against master build 654e39ec84ef (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 26.5, 26.3, 25.8
  • Could not test: master
  • Caused by: Naive Sharded Aggregation for high cardinality data #104233 (commit 4775f2d5cfb4, found by bisecting in several steps)

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

clickgapai's backport finding above holds. I measured it with the official per-branch binaries from
builds.clickhouse.com, running both its reproducer and 04342_sharded_aggregation_pipeline_stuck, the
regression test this PR added:

branch binary reproducer, enable_sharding_aggregator = 1 04342
26.8 26.8.3.12 (7b3fa8c81925) correct result passes, byte-identical to the .reference
26.7 26.7.7.7 (de4ec46b7337) Code: 49. DB::Exception: Pipeline stuck reproduces
26.6 26.6.5.23 (6645546f6487) Code: 49. DB::Exception: Pipeline stuck reproduces
26.3 26.3.29.7 (9d44dc7ea695) Code: 115. UNKNOWN_SETTING feature absent

The 26.7 and 26.6 stuck states are byte-identical to each other and are the ones from #106237:
BufferedShardByHashTransform_10 in PortFull with Concat_38 in NeedData. Controls on the same
binaries: with enable_sharding_aggregator = 0 every query returns the correct result, and 04342's
topology assertion prints 1 before the exception, so the pipeline shape the fix targets is the one
being built. The setting is Production tier and defaults to 0 on both branches, so one SETTINGS
clause reaches it.

26.8 inherited the fix at its branch cut, so 26.6 and 26.7 are the whole gap, and master is unaffected
either way since #116532 retired the setting there. On both branches the two source files this PR
changed are byte-identical to its first parent and the two test files are absent, so the pick has no
conflicting hunk.

@alexey-milovidov could you apply v26.6-must-backport here? It expands to 26.6, 26.7 and 26.8, and
ReleaseBranch.pre_check skips 26.8 because it already contains the commit, so it yields exactly the
two backport PRs.

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-bugfix Pull request with bugfix, not backported by default 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.

Logical error: Pipeline stuck still happens

7 participants