Repository navigation
Fix unkillable hang in random distribution functions with extreme parameters - #111909
Conversation
…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
|
Workflow [PR], commit [55e048a] Summary: ✅
AI ReviewSummaryThis PR hardens the random distribution functions against unkillable hangs by adding unconditional bounds for the gamma-backed distributions and for Findings
Final Verdict
|
…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
…its values and not trials
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 35/36 (97.22%) · Uncovered code |
|
Hi @alexey-milovidov — while reviewing this PR I found the following:
Could you review the test PR and add the |
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.
randChiSquared,randStudentT,randFisherFandrandBinomialcould occupy a thread for an unbounded time inside the sampler of the standard library. The loops are not interruptible, somax_execution_timeandKILL QUERYhad no effect and the thread stayed busy until the server was restarted. Constant folding executes the function during query analysis, so even a plainSELECT randChiSquared(1.7976931348623157e308)hung before a pipeline existed.std::gamma_distribution, which backs the first three functions, draws candidates assqrt((3 * shape - 0.75) / w) * (u - 0.5)wherew = u * (1 - u)never exceeds 1/4. Once12 * shapeoverflows to infinity every candidate is infinite, both acceptance criteria evaluate to NaN, and the loop never terminates.std::binomial_distributionstarts 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 oflgamma(t + 1)evaluated indouble, whose terms grow ast * ln(t), so cancelling them loses a relative accuracy of aboutt * 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 alltvalues instead of the few around the mode it normally needs. Measured against thelibc++incontribforp = 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_parameterandmax_rand_distribution_trialsalready reject such arguments with their default values, but both are disabled by0, which04057_rand_distribution_settingsdoes. The server-side AST fuzzer then rewrites numeric literals to boundary constants such asDBL_MAX, which is how this reached the stress test. From the fullhung_check.logartifacts of the 50 most recent hung-check dumps (2026-07-19 to 2026-07-25), the fuzzed queryis 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:
DBL_MAX / 12, which keeps a factor of two of headroom for the rounding of the intermediate products. Verified over 300 seeds each thatrandChiSquared,randStudentTandrandFisherFreturn immediately at that bound, that1.6e307still works, and that3e307does not return.randBinomialis capped at 10^9, which is exactly the shipped default ofmax_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 forrandBinomial, but no longer raise it. Verified over 400 seeds thatrandBinomialreturns immediately at 10^9 trials.randNegativeBinomialandrandPoissonalso honourmax_rand_distribution_trials, and they were verified not to hang even atUInt64::maxtrials and a mean ofDBL_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a hang in
randChiSquared,randStudentT,randFisherFandrandBinomialwith extreme parameters. The query could not be interrupted bymax_execution_timeorKILL QUERY. Such parameters are now rejected even whenmax_rand_distribution_parameterormax_rand_distribution_trialsis set to 0, andmax_rand_distribution_trialscan no longer be raised above its default of 10^9 forrandBinomial.Version info
26.8.1.180(included in26.8and later)