Skip to content

Fix unkillable hang in random distribution functions with extreme parameters - #111909

Merged
alexey-milovidov merged 4 commits into
masterfrom
fix-hung-check-107941
Jul 27, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
fix-hung-check-107941

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

randChiSquared, randStudentT, randFisherF and randBinomial could occupy a thread for an unbounded time inside the sampler of the standard library. The loops are not interruptible, so max_execution_time and KILL QUERY had no effect and the thread stayed busy until the server was restarted. Constant folding executes the function during query analysis, so even a plain SELECT randChiSquared(1.7976931348623157e308) hung before a pipeline existed.

std::gamma_distribution, which backs the first three functions, draws candidates as sqrt((3 * shape - 0.75) / w) * (u - 0.5) where w = u * (1 - u) never exceeds 1/4. Once 12 * shape overflows to infinity every candidate is infinite, both acceptance criteria evaluate to NaN, and the loop never terminates.

std::binomial_distribution starts at the mode and walks outwards one value at a time, subtracting the probability of every visited value from a uniform draw, so a single sample costs O(t) in the worst case. All of those probabilities are derived from differences of lgamma(t + 1) evaluated in double, whose terms grow as t * ln(t), so cancelling them loses a relative accuracy of about t * ln(t) * epsilon. Their total therefore falls short of 1 by roughly that much, and whenever the draw lands above the total the walk traverses all t values instead of the few around the mode it normally needs. Measured against the libc++ in contrib for p = 0.999, the total falls short of 1 by 3.5e-7 at 10^9 trials, by 1.9e-5 at 10^10, by 2.9e-4 at 10^11 and by 3.2e-3 at 10^12, while the runaway walk takes seconds at 10^9 trials and hours at 10^12.

max_rand_distribution_parameter and max_rand_distribution_trials already reject such arguments with their default values, but both are disabled by 0, which 04057_rand_distribution_settings does. The server-side AST fuzzer then rewrites numeric literals to boundary constants such as DBL_MAX, which is how this reached the stress test. From the full hung_check.log artifacts of the 50 most recent hung-check dumps (2026-07-19 to 2026-07-25), the fuzzed query

SELECT count() FROM (SELECT moduloLegacy(toInt32(-1000), materialize(7)), randChiSquared(1.7976931348623157e308) FROM numbers(1))

is responsible for 6 of them, making it the most repeated single hung query in that window.

Those settings keep bounding the computation time and stay tunable. The new bounds delimit the domain where the samplers are usable at all and therefore always apply:

  • Degrees of freedom are capped at DBL_MAX / 12, which keeps a factor of two of headroom for the rounding of the intermediate products. Verified over 300 seeds each that randChiSquared, randStudentT and randFisherF return immediately at that bound, that 1.6e307 still works, and that 3e307 does not return.
  • The number of trials for randBinomial is capped at 10^9, which is exactly the shipped default of max_rand_distribution_trials, because the shortfall above grows with the number of trials and nothing above that default is safe. This is the one user-visible restriction: the setting can still lower the limit for randBinomial, but no longer raise it. Verified over 400 seeds that randBinomial returns immediately at 10^9 trials.

randNegativeBinomial and randPoisson also honour max_rand_distribution_trials, and they were verified not to hang even at UInt64::max trials and a mean of DBL_MAX, so they keep the tunable limit alone and the setting can still be raised for them.

Both shipped defaults are at or below the new bounds, so default behaviour is unchanged.

Note that the hung check aggregates several independent stress-only causes; this fixes one of them.

Related: #107941
Related: #67297

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):

Fixed a hang in randChiSquared, randStudentT, randFisherF and randBinomial with extreme parameters. The query could not be interrupted by max_execution_time or KILL QUERY. Such parameters are now rejected even when max_rand_distribution_parameter or max_rand_distribution_trials is set to 0, and max_rand_distribution_trials can no longer be raised above its default of 10^9 for randBinomial.

Version info

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

…ameters

`randChiSquared`, `randStudentT`, `randFisherF` and `randBinomial` could spin
forever inside the rejection loop of the standard library sampler. The loop is
not interruptible, so `max_execution_time` and `KILL QUERY` had no effect and
the query occupied a thread until the server was restarted. Constant folding
executes the function during query analysis, so even a plain
`SELECT randChiSquared(1.7976931348623157e308)` hung before a pipeline existed.

`std::gamma_distribution`, which backs the first three functions, draws
candidates as `sqrt((3 * shape - 0.75) / w) * (u - 0.5)` where `w = u * (1 - u)`
never exceeds 1/4. Once `12 * shape` overflows to infinity, every candidate is
infinite, both acceptance criteria evaluate to NaN, and the loop never
terminates. `std::binomial_distribution` derives the probability of the mode
from differences of `lgamma(t + 1)`; for a large number of trials their
cancellation loses all precision, the probability underflows to zero, and the
sampler then walks away from the mode one trial at a time, needing O(t) steps.

`max_rand_distribution_parameter` and `max_rand_distribution_trials` already
rejected such arguments with their default values, but both are disabled by 0,
which `04057_rand_distribution_settings` does. The server-side AST fuzzer then
rewrites numeric literals to boundary constants such as `DBL_MAX`, which is how
this reached the stress test: the fuzzed query
`SELECT count() FROM (SELECT ..., randChiSquared(1.7976931348623157e308) FROM
numbers(1))` accounts for 6 of the 50 most recent hung-check dumps.

Those settings bound the computation time and stay tunable; the new bounds
delimit the domain where the samplers terminate at all and therefore always
apply. Defaults are unaffected, since both defaults are far below the bounds.

Related: #107941
Related: #67297
@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [55e048a]

Summary: ✅


AI Review

Summary

This PR hardens the random distribution functions against unkillable hangs by adding unconditional bounds for the gamma-backed distributions and for randBinomial even when max_rand_distribution_parameter / max_rand_distribution_trials are disabled. The gamma-family change looks sound, but the new unconditional randBinomial cap also rejects endpoint probabilities that are already O(1), so I think the binomial guard needs one more refinement before merge.

Findings

⚠️ Majors

  • [src/Functions/randDistribution.cpp:245] The new unconditional t > 10^9 check changes randBinomial's contract for the degenerate cases p = 0 and p = 1. Those endpoints do not take the pathological O(t) path in std::binomial_distribution: __p12 becomes 0, _M_q becomes 0, and _M_waiting returns after a single iteration, so queries like randBinomial(18446744073709551615, 0) and randBinomial(18446744073709551615, 1) used to be safe with max_rand_distribution_trials = 0 but now raise BAD_ARGUMENTS.
    Suggested fix: special-case p == 0 / p == 1 before the hard-cap check and add a focused regression test that exercises both endpoint probabilities with a trial count above 10^9.
Final Verdict
  • Status: ⚠️ Request changes

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good.

…and_distribution_trials`

The previous bound of `2^40` was still inside the range where
`std::binomial_distribution` hangs, which is what made
`04628_rand_distribution_no_hang` time out under ASan and UBSan on the
`SELECT count() FROM (SELECT randBinomial(1099511627776, 0.999) FROM numbers(1))`
query. The sampler starts at the mode and walks outwards one trial at a time,
so a single sample costs O(t) in the worst case, and it takes that path
whenever the accumulated probabilities do not reach the uniform draw. Those
probabilities are all derived from differences of `lgamma(t + 1)` evaluated in
`double`, whose terms grow as `t * ln(t)`, so their total falls short of 1 by
about `t * ln(t) * epsilon`. Measured for `p = 0.999`, the shortfall is 3.5e-7
at 10^9 trials, 1.9e-5 at 10^10, 2.9e-4 at 10^11 and 3.2e-3 at 10^12, and the
runaway walk takes seconds at 10^9 trials and hours at 10^12. Nothing above
the shipped default of `max_rand_distribution_trials` is therefore safe, so the
hard bound now keeps exactly that default: the setting can still lower the
limit for `randBinomial`, but no longer raise it.

Verified against the `libc++` in `contrib` that `randChiSquared`,
`randStudentT` and `randFisherF` stay fast over 300 seeds each at the
degrees-of-freedom bound, that `randBinomial` stays fast over 400 seeds at
10^9 trials, and that `randNegativeBinomial` and `randPoisson` do not hang even
at `UInt64::max` trials and a mean of `DBL_MAX`, so they keep the tunable limit
alone.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111909&sha=9aa5132a7602a1d5d36c4c9265487e69f385daa8&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#111909
Comment thread src/Functions/randDistribution.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 35/36 (97.22%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 26, 2026
Merged via the queue into master with commit 81f6bc5 Jul 27, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-hung-check-107941 branch July 27, 2026 00:06
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 28, 2026
Resolved src/Backups/registerBackupEnginesFileAndDisk.cpp.

Master (ClickHouse#111909) extracted the File/Disk argument parsing out of the creator
lambda into resolveLocalBackupLocation() so that the same resolution can also
produce a destination identity for the backup-engine registry. This branch had
made checkPath() return the 'backups.allowed_path' entry the destination
resolved against, and threaded it into BackupWriterFile as the boundary for the
directory fsyncs.

Both changes are kept: the allowed_path is now carried in master's
ResolvedLocalBackupLocation struct, so it is computed once in
resolveLocalBackupLocation() and handed to BackupWriterFile from there. The
identity function reuses the same resolution and is unaffected, because it only
reads disk_name/path/archive_name.
PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants