Skip to content

Honour the shard-queue cap while a consumer is draining - #116055

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-116038-shard-queue-cap-push-evidence
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-116038-shard-queue-cap-push-evidence

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116038
Related: #106251

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

BufferedShardByHashTransform may let a queue exceed MAX_QUEUE_LENGTH when the only demand is an empty output port with nothing drainable. That escape is needed: such a port can only be fed from input, so refusing to pull there deadlocks the pipeline, which is #106237.

The state was detected with canPush(), which cannot tell a consumer blocked until another branch finishes from one that is merely busy this cycle. A shard receiving no rows keeps its queue empty and its consumer keeps the port needed, so the escape also fired on a plain GROUP BY under a Resize + AggregatingTransform consumer, where the loaded shards were in fact draining every cycle. Peak memory then scaled with the scanned data rather than with the cap.

This change requires evidence of draining: an output port that is needed and still holds an undelivered chunk belongs to a consumer draining right now, and that chunk guarantees a further port-state change when taken, so the cap can be honoured there without stalling. Where nothing is in flight, input is the only way forward and the escape still applies, so the deadlock fix is preserved. It does not make the cap a hard bound under a ConcatProcessor -- that still needs an overflow path for the over-cap shard, which is the open question on #106251.

The header comment claimed the escape was only reachable under a consumer that activates outputs one at a time. EXPLAIN PIPELINE shows no ConcatProcessor in the plain sharded GROUP BY that reaches it, so that claim is corrected.

26.6 and 26.7 do not carry the escape predicate, so they are unaffected. 26.8 was cut after this PR opened and does carry it, so it needs the same fix; I have not hand-authored a release-branch PR for it, since backports go through the vX.Y-must-backport label.

Validation

Three binaries one predicate apart, each Build ID asserted via SELECT lower(buildId()) on the binary that ran the query. Minimum max_memory_usage at which the issue's query succeeds, bisected on a 16M-row, 4-distinct-key aggregation:

build min budget
cap unconditionally honoured 15 MiB
master 389 MiB
this change 17 MiB
  • 04342_sharded_aggregation_pipeline_stuck (the Logical error: Pipeline stuck still happens #106237 regression test): passes, 6/6 fresh servers. Reverting only the escape on top of this branch aborts with Pipeline stuck, so the escape is still load-bearing and this change keeps it.
  • New 04656_sharded_aggregation_queue_cap_memory fails on master with Code: 241 ... While executing BufferedShardByHashTransform and passes here, 5/5.
  • Single key with 15 of 16 shards never fed, under a sequential ConcatProcessor: completes, no stall.
  • The other 15 enable_sharding_aggregator stateless tests are byte-identical to master.

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

BufferedShardByHashTransform lets a queue exceed MAX_QUEUE_LENGTH when the only
demand is an empty output port with nothing drainable, because that port can only
be fed from input and refusing to pull there deadlocks the pipeline (ClickHouse#106237).

The state was detected with canPush(), which cannot distinguish a consumer blocked
until another branch finishes from one that is merely busy this cycle. A shard that
receives no rows keeps its queue empty and its consumer keeps the port needed, so
the escape also fired on a plain GROUP BY under a Resize + AggregatingTransform
consumer, where the loaded shards were being drained every cycle. Peak memory then
scaled with the scanned data instead of with the cap. Bisected on a 16M-row,
4-distinct-key aggregation: 389 MiB required before this change against 17 MiB
after it, and the query failed inside a 96 MiB budget that the same aggregation
without sharding fits comfortably.

Require evidence of draining instead. An output port that is needed and still holds
an undelivered chunk belongs to a consumer draining right now, and that chunk
guarantees a further port-state change when it is taken, so the cap can be honoured
in that state without stalling. Where nothing is in flight, input remains the only
way forward and the escape still applies, so the deadlock fix is preserved: under a
ConcatProcessor no other shard can be pushed at all. This does not make the cap a
hard bound in that topology, which still needs an overflow path for the over-cap
shard.

The evidence has to be per port rather than per processor. A single processor-wide
"pushed since the last check" flag can record a push whose chunk the consumer has
already taken, leaving no pending wake-up; with a sparse key on the shard a narrowed
ConcatProcessor demands first, that stalls in 6 of 6 runs. The regression test covers
that shape, and asserts the topology it depends on because the same sums come back
without it.

The header comment claimed the escape was only reachable under a consumer that
activates outputs one at a time. EXPLAIN PIPELINE shows no ConcatProcessor in the
plain sharded GROUP BY that reaches it, so that claim is corrected.

Closes: ClickHouse#116038
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c25cbc8]

Summary: ✅


AI Review

Summary

This PR narrows BufferedShardByHashTransform's queue-cap escape so plain sharded GROUP BY pipelines stop growing per-shard queues when downstream consumers are still draining. I did not find a blocking correctness issue in the current code, but the PR metadata is inconsistent with the actual user-visible fix, and full functional CI evidence was not available yet.

PR Metadata
  • Changelog category should be Bug Fix, not Not for changelog. The PR fixes user-visible excessive memory usage in 26.8 when enable_sharding_aggregator is enabled, which matches "user-visible misbehavior in an official stable release."
  • Changelog entry is therefore required. Suggested replacement:
    Fixes excessive memory usage for some GROUP BYqueries withenable_sharding_aggregator, so shard queues stay bounded while downstream consumers are still draining.
Missing context / blind spots
  • ⚠️ As of 2026-08-25, Praktika exposed only the Build profile diff report for this PR; no stateless or integration results were available for me to cross-check the new 04656 coverage.
  • ⚠️ This checkout has no existing build_* directory, so I could not rerun 04656_sharded_aggregation_queue_cap_memory locally to compensate for the missing functional CI.
Final Verdict

No blocking code issues found in the current diff. Update the changelog metadata and wait for full functional CI before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 16/16 (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 24, 2026
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c25cbc825 with master f7901a482 (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 709.92 MiB 706.88 MiB -3.04 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, 5 s compile time in total, 7 of them have a recent master baseline.

Job report

The test measured the shard-queue cap by scanning 16M narrow rows with
max_threads = 16. That exceeded the 180s ceiling the flaky check applies
(tests/clickhouse-test:3562) in all five of its jobs, 305-340s per run:
the check runs many copies of the same changed test concurrently, so one
test's own thread count and fixture size are multiplied by the worker
count.

What a queued chunk costs the memory tracker is its bytes, not its rows,
so the fixture now carries a wide string payload over 1M rows instead of
16M narrow ones, and max_threads is 4. Bisecting the minimum budget per
arm on three separate builds (cap-honoured, master, fixed) gives 39-43
MiB honoured against 259-290 MiB unbounded, a wider ratio than the shape
it replaces, with the no-sharding control at 11 MiB. The 96 MiB budget
therefore keeps 2.2x headroom below and 2.7x above. 500k rows was tried
and rejected: there the two requirements cross over and the oracle
inverts, so 1M is the floor for this oracle rather than a round number.

Under the runner's own condition - 8 concurrent copies pinned to 9 cores
- the file drops from 4.29s to 2.28s. Since the remaining cost cannot be
traded away without losing the oracle, the test is also tagged long,
which is what the three sibling enable_sharding_aggregator tests
(03927, 04097, 04603) do for the same reason and which exempts it from
that ceiling.

max_insert_threads is pinned in both fixtures because it is randomized
and changes only the fixture's cost, and both keys sets are checked to
still cover every shard at the lower thread count.

The reference output is unchanged, and both directions still hold: the
fixed build passes 12/12 and matches the reference, master still throws
Code: 241 while executing BufferedShardByHashTransform. The oracle also
holds in both directions across seven randomized aggregation settings
(group_by_two_level_threshold and _bytes, max_bytes_before_external_
group_by, optimize_aggregation_in_order, enable_memory_bound_merging).
The comment said the four keys reach four distinct shards. They reach
two: the transform seeds the hash accumulator and calls computeHashInto
with initial=false, so each key's own CRC32C is combined with the seed a
second time, and keys 0..3 map to shards 3, 0, 0, 3 at four shards.

The oracle is unaffected because the real routing is the more skewed of
the two, which is what the test needs; only the description was wrong.
Both arms asserted only that a sharded transform and a Concat were
present, which a narrower plan satisfies without reaching the predicate
under test. The memory arm now pins the four-wide fan-out it needs, and
the mixed arm matches a fan-out wider than one output plus the narrowing
Concat by shape.

The mixed arm was also not arming. Its keys were picked for a 16-wide
sharder, but max_streams_for_union_step narrows the fan-out well below
max_threads, and at the widths that actually occur the old keys 23 and 7
both land on shard 0, so no shard was left empty while demanded and the
arm degenerated into a plain query. Keys 0 and 4 are used instead: 4
lands on shard 0 and 0 never does, at every width from 4 to 16, so the
choice does not depend on the exact fan-out. The width is not pinned
there because it follows the reader's part count, which the earlier
statements in the file influence - measured 7 standalone and 9 in file.

With the keys corrected the arm discriminates again: the per-processor
push-flag build, which the per-port design replaced, aborts with
Pipeline stuck 3 of 3 runs, and this branch passes 8 of 8 matching the
reference. Master still throws Code: 241 while executing
BufferedShardByHashTransform, 3 of 3.

The reference changes only in the two group keys the mixed arm reports.
The character class [2-9] matches one digit, so a 16-wide sharder made
the precondition read 0 while the reference expects 1, which would have
failed the test on any run where the reader produced ten or more
streams. Verified directly: the old pattern returns 0 against
"× 16 1 → 16" and 1 against "× 9 1 → 9". The pattern now also accepts
two or more digits, and still rejects a width of 1, where there is no
fan-out to exercise.

The comment also credited the wrong mechanism for the width. Measured on
one fixture, the sharder stays 7 wide at max_streams_for_union_step of
1, 2 and 16, so the narrowing builds the Concat but does not set the
sharder width; that follows the reader's stream count.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 438d01bd2368399: the new test 04656 was over the flaky check's 180s per-test limit in all five jobs (305-340s), because that check runs many copies of the same changed test at once, so its own max_threads and fixture size get multiplied.

The queued chunks the cap bounds are measured in bytes, not rows, so the fixture is now 1M wide-payload rows instead of 16M narrow ones at max_threads = 4. Bisected per arm, that separates better than the shape it replaces: 39-43 MiB with the cap honoured against 259-290 MiB without, and 11 MiB off the sharded path, so the 96 MiB budget keeps 2.2x headroom below and 2.7x above. 500k rows was tried and rejected - the two requirements cross over there and the oracle inverts. Under 8 concurrent copies pinned to 9 cores the file goes 4.29s -> 2.28s, and since the rest cannot be traded away without losing the oracle it is also tagged long, as the sibling enable_sharding_aggregator tests 03927/04097/04603 are.

Two test defects found while doing this, both now fixed:

  • the mixed Concat arm was not arming its own predicate. Its keys were chosen for a 16-wide sharder, but the sharder is only as wide as the reader's streams (measured 7, unchanged at max_streams_for_union_step 1, 2 and 16 - the narrowing builds the Concat, it does not set the width), and at the widths that occur both old keys landed on shard 0. Keys 0 and 4 hold at every width from 4 to 16. With them the arm discriminates again: the per-processor push-flag variant that review rejected aborts Pipeline stuck 3/3, this branch passes 8/8.
  • both topology preconditions asserted only that the processors were present, which a narrower plan satisfies without reaching the state under test. They now assert the fan-out.

One correction to the description above: 26.8 was cut after this PR opened and does carry the faulty predicate (26.6 and 26.7 do not), so it needs this fix too. I have not hand-authored a release-branch PR - that goes through the v26.8-must-backport label if you want it.

… shape

The test failed two different ways on the same commit, and both came from a
randomized setting that decides how the part is read, not from the property
under test.

index_granularity_bytes is randomized from 1024 bytes up. At the low end 1M
rows become about 143k marks, the reader then serves the part with a single
stream, and canUseShardedAggregation rejects a single stream, so the sharded
plan disappears and the topology precondition prints 0 instead of 1. Both
fixtures now name it in the DDL, which also stops the runner randomizing it at
all: get_random_settings skips any merge-tree setting the DDL already sets.

merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability
is worse, because it does not fail the test, it disarms it. Splitting the mark
ranges changes the order the shards are demanded in, so no unbounded queue
builds: measured on a build without the fix, the sharded query peaks at 300-540
MiB below 0.4 and at 13-15 MiB from 0.45 up, against a 96 MiB budget. Above
that point the query fits the budget whether or not the cap is honoured. The
setting is randomized uniformly over 0..1, which is why holding every other
randomized setting constant still left about half the reruns green. It is now
pinned to 0 in every query.

max_streams_to_max_threads_ratio scales the reader's stream count directly and
is pinned for the same reason, though it is not randomized today, so that part
is hardening rather than a fix.

The MEMORY_LIMIT_EXCEEDED rows while reading column b had the same cause: the
tiny granules, not sanitizer overhead. With the granularity pinned, the
non-sharded control arm peaks at 3 MiB under ASan against the 96 MiB budget, so
no build exclusions are needed and none are added.

Verified with the real test runner, fresh randomization per invocation and no
skips: 12/12 pass on a debug build with the fix, and 6/6 fail on each of debug,
ASan and an official release master binary without it, every one of them on
"While executing BufferedShardByHashTransform" rather than in the reader. With
either pinned setting forced from the client, the builds without the fix still
fail, so the query level pins hold against the runner. The mixed Concat arm
still discriminates too: the per-processor variant of the fix aborts with
"Pipeline stuck" while this one returns the expected rows.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 9893eb457321454: 04656 was flaky for its own reasons, both in the read shape rather than in the property it tests.

index_granularity_bytes is randomized from 1024 bytes up. At the low end 1M rows become ~143k marks, the reader serves the part with one stream, and canUseShardedAggregation rejects a single stream, so the sharded plan disappears and the topology precondition prints 0 - that is the result differs signature. Both fixtures now name the setting in the DDL, which also stops the runner randomizing it (get_random_settings skips merge-tree settings the DDL already sets).

merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability was the more serious one, because it did not fail the test, it disarmed it. Splitting the mark ranges changes the order the shards are demanded in and no unbounded queue builds. On a build without the fix the sharded query peaks at 300-540 MiB below 0.4 and 13-15 MiB from 0.45 up, against the 96 MiB budget, so above that point the query fit the budget whether or not the cap was honoured. It is randomized uniformly over 0..1, which is why the runner's own rerun diagnosis split 22/46 with every other setting held constant. Now pinned to 0.

The MEMORY_LIMIT_EXCEEDED ... while reading column b rows had the same root cause, not sanitizer overhead: with the granularity pinned the non-sharded control arm peaks at 3 MiB under ASan. So no build exclusions were needed and none were added.

Verified with the test runner, fresh randomization per invocation, no skips: 12/12 pass with the fix, and 6/6 fail on each of debug, ASan and an official release master binary without it, all on While executing BufferedShardByHashTransform. Forcing either pinned setting from the client does not change that, so the query-level pins hold.

The 26.8 note from my previous comment still stands: that branch carries the same predicate, and the backport would need the v26.8-must-backport label on this PR.

All five CI failures at 9893eb4 were the same query and the same drawn
setting: query 5, the non-sharded control arm, on runs where the test
runner randomized use_uncompressed_cache to 1.

Reading through the uncompressed cache charges every block inserted into
it to the query that populates the cache. On this fixture that is 143 MiB
against the test's 96 MiB budget, so such a run exhausts the budget inside
CachedCompressedReadBuffer while reading column b, before either arm's
aggregation is reached. A warm cache reads 5 MiB, so the failure follows
whichever run populates the cache, which is what made it intermittent.

Measured with uncompressed_cache_size at its shipped 8 GiB: the control arm
peaks at 142.9 MiB cold with the cache on and 5.0 MiB with it off, and the
budgeted query reproduces Code: 241 at 97.87 MiB deterministically. With
the cache pinned off and every other read-path, cache and aggregation knob
maximally hostile the control arm stays at 5 MiB, so no other setting can
reach the budget.

The pin also protects the oracle rather than just the control: with the
cache on the sharded arm peaks at 158-162 MiB, so it would exceed the
budget for a reason unrelated to the queue cap. Pinned off it is 35-42 MiB,
and the arm still separates - the test fails 6 of 6 against a build without
the cap fix, every time on the BufferedShardByHashTransform allocation.

Applied only to the two queries that carry max_memory_usage; the EXPLAIN
and mixed-Concat arms assert topology and are unaffected.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed c25cbc82521: 04656 was failing because the test runner randomizes use_uncompressed_cache and the test did not pin it.

All five reds on the previous head were the same query - the non-sharded control arm - and all five had drawn the cache on. Blocks inserted into the uncompressed cache are charged to the query that populates it, which is 143 MiB on this fixture against the test's 96 MiB budget, so those runs ran out of budget inside CachedCompressedReadBuffer while reading column b. A warm cache reads 5 MiB, which is why it was intermittent.

Measured with uncompressed_cache_size at its shipped 8 GiB: control arm 142.9 MiB cold with the cache on, 5.0 MiB with it off, and Code: 241 at 97.87 MiB reproduces 3/3. With the cache pinned off and every other read-path and aggregation setting maximally hostile, the control arm stays at 5 MiB in 6/6 runs.

The pin also protects the oracle: with the cache on the sharded arm reaches 158-162 MiB, so it would have exceeded the budget for a reason unrelated to the queue cap. Pinned off it is 35-42 MiB and still discriminates - 12/12 pass here, and 6/6 fail against a build without the cap fix, every time on the BufferedShardByHashTransform allocation.

@nihalzp

nihalzp commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

@nihalzp nihalzp closed this Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, leaving it closed.

I checked that #116532 removes the surface rather than relocating it: at bec7b8e,
src/Processors/Transforms/BufferedShardByHashTransform.{cpp,h} are gone, AggregatingStep.cpp has
zero remaining references to the transform, and enable_sharding_aggregator becomes MAKE_OBSOLETE,
so an existing profile carrying it is still accepted and inert. That takes both halves of this work
with it: the escape-predicate narrowing here, and the queue bound @ alexey-milovidov asked for as a
follow-up on #106251.

The path that survives already has the bound the follow-up would have had to build, which is why I am
not proposing to carry anything over. Rare keys stage into the per-bucket backlogs, and past the
external-aggregation threshold a pressure sweep drains them and spills the routing table through the
ordinary external-aggregation machinery (AdaptiveAggregation.h:20-23), with staging paused on the
spill reservation whenever a producer waits for a writer (AdaptiveAggregationKernels.cpp:1636-1638).
That matches what was measured on the issue's own 16M-row, 4-distinct-key shape: 23 MB flat with
enable_sharding_aggregator = 0 against the 389-395 MiB the sharded path needed.

Not reopening this; I will follow #116532 instead.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shard-queue cap bypass buffers the whole input on a plain GROUP BY (40x memory)

2 participants