Repository navigation
Fix pipeline-stuck deadlock in BufferedShardByHashTransform - #106251
alexey-milovidov merged 31 commits into
Conversation
`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
|
Pre-PR validation gate (per worker procedure): a) Deterministic repro? Yes — the SQL reproducer in the PR description fires Session: |
|
cc @PedroTadim @nihalzp @KochetovNicolai — could you review this? It fixes the pipeline-stuck deadlock you flagged on #106237: |
|
Workflow [PR], commit [321cea8] Summary: ✅
AI ReviewSummaryThis PR fixes the 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
Changed lines: Changed C/C++ lines covered: 39/40 (97.50%) · Uncovered code |
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)
|
Pushed 874c4f0 addressing the inline bot review:
Both tests pass 60/60 locally with randomized settings. Session: cron:clickhouse-ci-task-worker:20260601-190000 |
|
@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.
|
@PedroTadim Investigated. CI failures:
Reverted the hard cap (commit 874c4f0) in 9645838 per the second bot CR ( 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. |
`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]>
|
The failures of They were introduced by #104690 ("Add #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]>
|
Thanks @alexey-milovidov. The branch already picked up the revert: the merge in c4152b5 includes #106365 (3930f8a, the revert of #104690), so the 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 |
CI ledger — covered SHA:
|
| 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
left a comment
There was a problem hiding this comment.
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.
|
@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 Which direction do you prefer? 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 |
|
Remove gtest and only keep the stateless sql test. |
CI finish ledger - bdd044fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not PR-caused: the abort is Session id: cron:our-pr-ci-monitor:20260822-160000 |
…-buffered-shard-by-hash-pipeline-stuck
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]>
|
🕵 Brought this up to date and closed out the two blockers. Merged current Both unresolved threads are now decided and resolved.
The one CI failure is a known CI is re-running on |
|
@groeneai This is a complex problem to solve without allowing unbounded memory. Let's set |
|
@nihalzp 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, Disabling buffering for real means honouring the cap, so dropping that escape. I built that arm and it brings back #106237: That is the same failure as the @ 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? |
|
@groeneai I meant remove all the changes you have in this PR and set |
|
@nihalzp I built that arm: this PR's source diff fully reverted, 3 of 3 independent server starts on the 04342 topology abort with the state from the original report: Control in the same session: the pure revert with the constant left at 10 gives the same stuck node states, and current head On the 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. |
|
Let's merge this, and then do a follow-up. |
|
@nihalzp Alexey ruled merge-now plus a follow-up (#106251 (comment)), so I am not reverting the diff or setting Branch left at |
|
Investigated the follow-up (bounding the The amplification scales with shard count, not with the queue cap.
Two other things I found worth flagging:
A cheaper option that nobody has priced yet: cap @ alexey-milovidov @ nihalzp - which do you want: the shard-count cap, the full external sharded One correction for the record, since it bears on whether this is worth doing at all: both |
|
@groeneai @alexey-milovidov @nihalzp — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
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 The escape stays for the state it was added for: reverting only that predicate reproduces Still open, unchanged: under a |
|
Correction to my note above: the follow-up PR I pointed at (#116055) is closed. @ nihalzp is removing That is also a fourth answer to the design question I posted above, so I am standing down rather than |
ReproducerCREATE 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:
CC introducing PR reviewer: @nickitat Analysis metadata
|
|
The 26.7 and 26.6 stuck states are byte-identical to each other and are the ones from #106237: 26.8 inherited the fix at its branch cut, so 26.6 and 26.7 are the whole gap, and master is unaffected @alexey-milovidov could you apply |
Closes: #106237
Related: #104233
BufferedShardByHashTransform::prepare()could deadlock when a downstreamConcatProcessor(fromnarrowPipeon aUNION ALLwithmax_streams_for_union_stepbelow the pipeline width) activated its inputs sequentially. Three defects inprepare():MAX_QUEUE_LENGTHsoft cap,prepare()returnedPortFulleven if a sibling port was empty and hadcanPush(), so that sibling never received data andConcatnever advanced.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 aPortFull.Two follow-ups on top of that. A
chassert(has_queued_chunks)added while reviewing the second loop was wrong and is removed:prepareholds only this node'sstatus_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 anotherpreparethat returnsStatus::Finished. Separately,MAX_QUEUE_LENGTHnow documents why its escape cannot be bounded here:ConcatProcessor::preparemakes 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 thanPipeline stuck.Reproducer, deadlocking on the first run without the fix:
04342_sharded_aggregation_pipeline_stuckasserts both deadlock shapes and both cap paths. Revertingprepare()to its pre-PR form reproducesPipeline stuck, so the test still covers the bug.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
Logical error: 'Pipeline stuck'in queries that useenable_sharding_aggregator = 1together with aUNION ALLandmax_streams_for_union_stepsmaller than the pipeline width.BufferedShardByHashTransformnow 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
26.8.1.1955(included in26.8and later)