Skip to content

Fix server hang multiplying a quantile/median aggregate state by a huge constant - #110779

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reservoir-sampler-multiply-total-values-overflow
Jul 17, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reservoir-sampler-multiply-total-values-overflow

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 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 server hang when multiplying a median/quantile (ReservoirSampler-backed) aggregate function state by a huge integer constant (e.g. medianState(x) * 18446744073709551615). The query became unresponsive to cancellation and could run indefinitely.

Description

Found by the server-side AST fuzzer in Stress test (arm_asan_ubsan, s3), auto-matched to the hung-check umbrella #107941. Investigated per @alexey-milovidov request on #110606.

The query still running at hung-check time was SELECT finalizeAggregation(10 * (SELECT medianState(number) FROM numbers(100000))), is_cancelled=1 but elapsed ~3100s. Stack: ReservoirSampler::merge -> executeAggregateMultiply -> QueryAnalyzer::resolveFunction (constant folding). (The dictGet line in the report's error-frequency table was an unrelated ILLEGAL_TYPE_OF_ARGUMENT exception, not the hang.)

Root cause: executeAggregateMultiply self-merges the reservoir with exponentiation by squaring, doubling ReservoirSampler::total_values (size_t) each step. A huge multiplier overflows the total_values += b.total_values sum in ReservoirSampler::merge; the wrapped-small value makes frequency = total_values / b.total_values drop below 1, so for (double i = 0; i < sample_count; i += frequency) runs billions of iterations with no cancellation check.

Fix: saturate the sum on overflow so frequency stays >= 1 and the loop is bounded. ReservoirSamplerDeterministic::merge is not affected (it merges via insertImpl, no frequency loop).

Reproduced deterministically (fails/hangs on master, passes with the fix); regression test 04603_reservoir_sampler_multiply_total_values_overflow added.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110606&sha=93359c59c1f878daeaedc91e6383f9e4ae893ce3&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

Version info

  • Merged into: 26.7.1.1123 (included in 26.7 and later)

…ge constant

executeAggregateMultiply self-merges the ReservoirSampler-backed state with
exponentiation by squaring, doubling ReservoirSampler::total_values (size_t)
each step. A huge multiplier overflowed the total_values += b.total_values sum
in ReservoirSampler::merge; the wrapped-small value made
frequency = total_values / b.total_values drop below 1, turning
for (double i = 0; i < sample_count; i += frequency) into a near-infinite loop
with no cancellation check. The query stayed running for ~3100s after being
cancelled, tripping the stress-test hung check.

Saturate the sum on overflow so frequency stays >= 1 and the loop is bounded.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "SELECT length(toString(finalizeAggregation(18446744073709551615 * (SELECT medianState(number) FROM numbers(100000)))))" hangs indefinitely on master, completes instantly with the fix. Requires numbers(N) with N > DEFAULT_SAMPLE_COUNT (8192) so the frequency-loop branch is taken.
b Root cause explained? Yes. executeAggregateMultiply self-merges the reservoir via exponentiation by squaring, doubling ReservoirSampler::total_values (size_t) each step. A huge multiplier overflows total_values += b.total_values in ReservoirSampler::merge; the wrapped-small value makes frequency = total_values / b.total_values < 1, so for (double i = 0; i < sample_count; i += frequency) becomes a near-infinite loop with no cancellation check.
c Fix matches root cause? Yes. Saturates the sum on overflow (__builtin_add_overflow -> size_t max) so frequency stays >= 1 and the loop is bounded. Directly targets the overflow identified in (b), not a symptom.
d Test intent preserved / new tests added? New regression test 04603_reservoir_sampler_multiply_total_values_overflow. Existing tests 04117 / 00647 / 00920 still pass unchanged.
e Demonstrated both directions? Yes. Test file hangs (timeout) on the unpatched master snapshot binary; passes on the patched binary. Correctness for small multipliers unchanged (median of [0,100000) = 50501.5).
f Fix general, not a narrow patch? Yes. The single overflow site in ReservoirSampler::merge covers all ReservoirSampler-backed aggregates (median, quantile, quantiles, ...). Sibling ReservoirSamplerDeterministic::merge was audited: it merges via insertImpl with no frequency loop, so it is not affected.
g Generalizes across inputs? Yes. Verified across multipliers 10^18, 9223372036854775806, UInt64-max (all previously hung); small multipliers (1, 10) and 0 remain correct. Covers medianState and quantileState.
h Backward compatible? Yes. No format/setting/wire change. Only bounds an internal merge loop; results for non-overflowing multipliers are byte-identical.
i Invariants and contracts preserved? Yes. total_values is only used to derive the resampling frequency; saturating it at size_t max preserves the "replace roughly every frequency'th element" contract and the reservoir contents. The self-merge (this == &b) early-return and the two small-reservoir branches are untouched.

Session id: cron:clickhouse-worker-slot-2:20260717-042200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @rschu1ze — could you review? Bounds a ReservoirSampler::merge loop that hung on total_values overflow when a median/quantile state is multiplied by a huge constant (fix for the umbrella #107941 hung-check hit on #110606, per @alexey-milovidov's request).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e73009d]

Summary: ✅


AI Review

Summary

This PR fixes the ReservoirSampler overflow that could make aggregate-state multiplication (median/quantile state by a huge integer constant) enter an effectively unbounded merge loop, and the follow-up insert saturation keeps a saturated state safely mergeable in both operand orders. I traced the current merge/insert paths in the merged checkout, checked the existing discussion, and did not find any remaining correctness issues in the touched code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4a5fb73

Every failure below has an owner (a fixing PR). No failure is caused by this PR's diff (a 7-line ReservoirSampler::merge overflow saturation + one regression test).

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, s3 storage, parallel, 2/3) / 01730_distributed_group_by_no_merge_order_by_long flaky (Code 241 MEMORY_LIMIT_EXCEEDED, 14 master hits + many unrelated PRs in 30d) #109847 (fix aggregation hash-table stats cache key, open)
Stateless tests (amd_tsan, s3 storage, parallel, 2/3) / Scraping system tables infra (minio audit-log dump timeout on s3 configs) #110099 (drop minio audit-log webhook, open)

Neither touches ReservoirSampler / aggregate-multiply. This PR is unaffected.

A saturated (SIZE_MAX) state can still be merged into another state via the
insert() branches of merge() (b.total_values <= sample_count, or the current
state's total_values <= sample_count). The plain ++total_values in insert()
wrapped SIZE_MAX to 0 and then reached genRandom(0) = UB / a debug assert.
Guard the increment to keep total_values saturated once it hits the max, and
extend the regression test to cover huge_state + small_state in both operand
orders.

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

Copy link
Copy Markdown
Collaborator Author

Good catch, fixed in e73009d.

insert() now guards the increment so total_values stays saturated at SIZE_MAX instead of wrapping to 0. Confirmed on a debug build that both merge orders aborted at genRandom(0) before the change and pass after:

SELECT length(toString(finalizeAggregation((18446744073709551615 * (SELECT medianState(number) FROM numbers(100000))) + (SELECT medianState(number) FROM numbers(1)))));
SELECT length(toString(finalizeAggregation((SELECT medianState(number) FROM numbers(1)) + (18446744073709551615 * (SELECT medianState(number) FROM numbers(100000))))));

Both are added to 04603 in both operand orders.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 8/9 (88.89%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e73009d

CI fully finished on this head (Config Workflow, Finish Workflow, Mergeable Check, CH Inc sync all green). No failed checks: zero FAIL/ERROR test rows across all jobs. The bot-CR fix (saturate total_values in ReservoirSampler::insert) is clean.

Session id: cron:our-pr-ci-monitor:20260717-193000

@alexey-milovidov alexey-milovidov 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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 17, 2026
Merged via the queue into ClickHouse:master with commit 1926f1b Jul 17, 2026
178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…voir-sampler-multiply-total-values-overflow

Fix server hang multiplying a quantile/median aggregate state by a huge constant
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 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.

4 participants