Repository navigation
Make isProbablePrime observe cancellation and max_execution_time on UInt128/UInt256 - #114032
Conversation
isProbablePrime on UInt128/UInt256 evaluated a whole block of rows inside one executeImpl call with no cancellation point. The pipeline samples cancellation only between blocks, so neither max_execution_time nor KILL QUERY could interrupt it, and each wide row costs milliseconds in boost::multiprecision::miller_rabin_test. Measured on master f9801d5, 10000 UInt256 rows at rounds = 64 against max_execution_time = 1: Code: 159. Timeout exceeded: elapsed 203157.095 ms, maximum: 1000 ms. 203x past its own deadline; the UInt128 carrier measured 382467 ms against the same deadline. Observed in CI as a Stress test (amd_msan) hung check with one query at elapsed = 1796 s, is_cancelled = 1 and max_execution_time = 10. The pre-existing rounds <= 256 cap already bounds a single call, so it does not help here: what was unbounded is the loop over the block. That is also why restoring the cancellable Miller-Rabin loop reverted in 736c7ee would not have fixed this - it would have added a checkpoint inside an already-bounded 82 ms call. Boost is retained, in line with the reasoning recorded on ClickHouse#104806. Primality.h takes an optional check_cancellation callback, invoked once per call just before the Miller-Rabin rounds, i.e. after the three cheap exits. The callback is opaque there, so Common stays free of ProcessList - the same split Base58.h already uses. isProbablePrime.cpp owns the query-status side via makeCancellationCheck and additionally charges a CancellationBudget per wide row, which bounds a block made only of cheap-exit rows (measured 0.04-0.26 us each) without making those rows pay for a check. Two mutation builds confirm both halves are load-bearing: with the callback removed the rounds cases overshoot again (203846 ms), and with the budget removed the cheap-exit case overshoots (10149 ms). The narrow path and the cheap exits are untouched and unslowed: 1M rows measured 3766 -> 3632 ms and 373 -> 360 ms, both within noise.
The timing cases were validated against a bare local server. The CI `default` profile (tests/config/users.d/limits.yaml) caps `max_rows_to_read` at 20M, and the cheap-exit case read 40M rows, so in CI it aborted with TOO_MANY_ROWS at plan time and mismatched the reference on every run. Its shape is now `materialize(toUInt256(...))` over 16M rows: under the cap, and its prologue is a per-row copy rather than a conversion, measured 368 ms of the block's 57000 ms so the deadline measures the function. The deadline scales with the build too, because a sanitizer stretches that prologue and only the bound scaled before. The `break` case asserted wall time with the output discarded, so any fast unrelated failure finished under the bound and scored as a pass. It now reads `query_duration_ms` and `ProfileEvents['OverflowBreak']` out of the query log, as 04722 does. Verified against a forced fast failure: a read-limit abort at 172 ms now reports `DEADLINE NEVER OBSERVED` where wall time alone passed it. The KILL case waited for the target to be visible in `system.processes`, which happens before the pipeline is built; a kill winning that race is served by the generic path and returns promptly even unfixed. It now waits for `elapsed > 0.5` (the old predicate was satisfied at elapsed = 0.001 s) and bounds the synchronous KILL, which polls without a deadline of its own, so a regression fails with a verdict instead of hanging until the runner's limit. The two no-regression cases accepted 20 s and 40 s against 373 ms and 3766 ms baselines, so they could not redden on the per-row-check regression they guard. No ProfileEvent counts cancellation checks, so there is nothing to assert mechanically without a source change; they keep their correctness assertions over a full block and the performance numbers move to the PR body. Adds `no-coverage`: coverage instrumentation stretches the fixed side of a timed case past its deadline, which doubling the bound does not address. Every arm re-measured through the new oracles on a server that loads limits.yaml: pristine and the callback-removed mutation overshoot the rounds cases (203101 / 203475 ms), the budget-removed mutation overshoots exactly the cheap-exit case (56796 ms), and the fix passes 50/50 randomized runs.
The case asserted that a synchronous kill of an `isProbablePrime` block returns within a bound, but it passed on unfixed code, so it was not testing the checkpoint the rest of the file tests. Two windows serve a kill through the generic path instead, and either one ends the query without ever reaching the primality checkpoint: `ProcessList` publishes a query before its executor is attached, and `ExpressionActions` checks cancellation after every action, so a conversion done per row in the prologue is interruptible on its own. The readiness predicate now waits for the target to be running rather than merely visible, which closes the first, and `materialize` wraps the finished `UInt256` rather than the string, which makes the prologue a copy rather than one parse per row and closes the second. The row count is sized against the sanitizer rather than the debug build. The bound scales with the sanitizer while this work does not: an instrumented build is optimized where a debug build is not, so a row at 256 rounds costs 42 ms there against 82 ms here. Sized for a comfortable margin on the debug build, an unfixed sanitizer run came within 271 ms of its own bound and would have gone vacuous on every sanitizer job. At 2000 rows an unfixed block is 5x the bound on the tighter of the two, and the fixed side is unaffected by the count because it notices the flag within one row. Measured in isolation, unfixed servers now report 160465 ms (debug) and 82002 ms (sanitizer) against bounds of 8000 and 16000 ms, where both previously reported success. Also lowers the internal timeouts from 900 s to 600 s. The runner arms its own per-test alarm at `int(timeout * 1.1) + 60`, 720 s by default, so the higher guard could never be the one to fire and a regression would have hung instead of failing with a readable verdict.
The comments accumulated across review rounds: each round answered a question by writing its justification into the test body and nothing removed one, so prose comments grew from 52 to 71 lines with blocks of 8 and 10. The merged sibling 04722 carries 48 with no block above 5. This brings the file back to 52 with a longest block of 5, deleting only what a commit message already records or what the code plainly shows, and keeping every invariant a future editor would otherwise break. Facts moved out of the test body and preserved here: Case 4's row count. `materialize` wraps the finished UInt256 rather than a narrower literal, which makes the per-row prologue a copy rather than a conversion: 368 ms for 16M rows against 57000 ms for the block itself. 16M rows stays under the 20M `max_rows_to_read` of the CI `default` profile, so no override is needed for the block to be reached. Case 4's margin on a sanitizer. The verdict bound scales to 18000 ms while the deadline only doubles, so the case is loosest where it is instrumented. Measured in isolation on the pristine snapshot: 58419 ms against 18000 ms, 3.25x; on a pristine debug build 56893 ms against 8000 ms, 7.11x. The cheap exit stretches only 1.03x under the sanitizer, unlike the rounds path (1.95x faster) or this case's own prologue (2.9x slower), because it is register-resident integer work rather than a memory-bound copy. Case 5's row count. An instrumented build is optimized where a debug build is not, so a row at 256 rounds costs 42 ms there against 82 ms here while `KILL_BOUND` doubles. Sizing against the debug build alone left the sanitizer arm 271 ms from its bound. 2000 rows keeps an unfixed block above 5x the bound on the tighter of the two. Case 5's readiness predicate. Two windows serve a kill through the generic path and would return promptly even unfixed: `ProcessList` publishes the query before the executor is attached, and `ExpressionActions` checks cancellation after every action, so a per-row conversion in the prologue is interruptible on its own. Waiting for elapsed time rather than for visibility closes both. Case 1's unfixed cost, about 200000 ms against a 2000 ms deadline, and case 3's per-row cost of roughly a fifth of case 1's.
Internal second-model reviewFour rounds of independent review. The source change was settled in the first round and is
Two findings were raised and dropped on verification rather than accepted: a suspected Both halves of the fix are independently load-bearing: with the callback removed the rounds Session id: cron:clickhouse-review-self-slot-58:20260809-113500 |
Pre-PR validation gate (a-i)
Performance, 1M rows in one block, base vs fix: narrow Test runs: 4/4 with |
|
cc @nihalzp @george-larionov, could you review this? A block of UInt128/UInt256 rows ran entirely inside one isProbablePrime executeImpl call, and the pipeline only samples cancellation between blocks, so max_execution_time and KILL QUERY were both ineffective (measured 203157 ms against a 1000 ms deadline). Primality.h now takes an optional cancellation callback invoked after the cheap exits and before the Miller-Rabin rounds, so Boost and the existing rounds <= 256 cap are both retained. |
|
Workflow [PR], commit [6125c2c] Summary: ✅
AI ReviewSummaryThis PR threads query cancellation into the Tests
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 20/22 (90.91%) · Uncovered code |
CI finish ledger — c6a6334CI is fully finished and green: 0 failing checks ( Session id: cron:our-pr-ci-monitor:20260809-220000 |
| @@ -0,0 +1,181 @@ | |||
| #!/usr/bin/env bash | |||
| # Tags: long, no-fasttest, no-coverage, no-flaky-check | |||
| # no-coverage: per-test coverage instrumentation stretches the fixed side of the timed cases. | |||
There was a problem hiding this comment.
Removed in 4aabcb5.
One consequence worth recording: it was the only test that failed when the checkpoint was absent, so the fix now has no regression coverage. 04201_is_prime and friends assert results only, and the stress harness caps isProbablePrime inputs at 1000, which never reaches the Miller-Rabin call the checkpoint guards. With no test file left, new_tests_check.py falls through to its CI-report-link branch, so the report of the original hang is now in the description as the evidence of record.
If you want coverage back without timings, I can assert on ProfileEvents instead, or add a gtest with a callback that throws on the second call. Otherwise I will leave it uncovered.
| for (size_t i = 0; i < input_rows_count; ++i) | ||
| result_data[i] = Primality::isProbablePrime(data[i], rounds); | ||
| { | ||
| if constexpr (Primality::is_big_uint<ValueT>) |
There was a problem hiding this comment.
@groeneai does it need this constexpr branch? We can reduce the code explosion
There was a problem hiding this comment.
Collapsed to a single call in 4aabcb5: the narrow overload now takes and ignores the callback, so if constexpr only decides whether the row is charged to the budget.
I kept the branch rather than deleting it because removing it entirely is not free. Charging every row costs 26% on the cheapest narrow path (200M UInt16 rows, one thread, debug: 0.646 s vs 0.512 s, 5 interleaved runs each; a control query without the function shows no difference), and it does not shrink anything either: the object grows 967568 -> 968592 bytes and executeImpl 0xbc4 -> 0xca7, since the budget check gets inlined into the narrow instantiations too. Guarding only the charge keeps both at the pre-change values and measures free.
Requested by @PedroTadim in review of ClickHouse#114032. Test removal: 04823_is_probable_prime_cancellation asserted wall-clock deadlines, and every timing assertion of that shape is a flakiness risk on loaded CI hosts regardless of the margin it was tuned for. Removing it leaves the fix with no regression coverage; the CI report of the original stress-test hang is now the evidence of record and is linked from the PR description, which is the fallback ci/jobs/scripts/workflow_hooks/new_tests_check.py accepts for a bug-fix PR that adds no test. Call site: the `if constexpr` no longer selects between two calls, only whether the row is charged to the cancellation budget, so there is one call to Primality::isProbablePrime instead of two. The narrow overload takes and ignores the callback to make that possible. Measured why the branch itself is retained rather than deleted outright. Dropping it entirely - charging every row and letting the budget see narrow values too - costs 26% on the cheapest narrow path (200M UInt16 rows, one thread, debug: 0.646 s vs 0.512 s over 5 interleaved runs each, with a control query that does not call the function showing no difference) and does not even shrink the code: the object grows 967568 -> 968592 bytes and executeImpl grows 0xbc4 -> 0xca7. Guarding only the charge keeps both at the pre-change values (967496 bytes, 0xbc4) and measures free (0.494 s). Results are unchanged: base and this build agree on UInt8/16/32/64/128/256 primality counts over 20000 values per width, and 04201_is_prime, 04202_is_prime_oracle and 04203_is_prime_wide pass.
CI finish ledger - 4aabcb5Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The two hung-check reds are the chronic trunk signature, not this diff: this PR touches only Session id: cron:our-pr-ci-monitor:20260810-193000 |
|
@nihalzp @george-larionov can you give a final look? The PR is small |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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. Object file sizes8 object files changed (+50.01 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units10 translation units recompiled, 27 s compile time in total, 10 of them have a recent master baseline. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
isProbablePrimeonUInt128/UInt256ignoringmax_execution_timeandKILL QUERY. A block of wide values ran to completion inside a single function call with no cancellation point, so a query could run for minutes past its deadline.Description
Requested in #112203.
isProbablePrimeonUInt128/UInt256evaluated a whole block inside oneexecuteImplcall with no cancellation point. The pipeline samples cancellation only between blocks, so neithermax_execution_timenorKILL QUERYcould interrupt it, and each wide row costs milliseconds inboost::multiprecision::miller_rabin_test.Measured on master, 10000
UInt256rows atrounds = 64againstmax_execution_time = 1:Observed in CI as
Stress test (amd_msan)Hung check failed, possible deadlock foundon an unrelated PR, with one query atelapsed = 1796 s,is_cancelled = 1,max_execution_time = 10: both channels ineffective. The existingrounds <= 256cap bounds a single call, not the loop over the block.The change adds a checkpoint at the layer owning that loop:
Primality.htakes an optionalcheck_cancellationcallback, invoked once per call just before the Miller-Rabin rounds, i.e. after the three cheap exits.Commonstays free ofProcessList, the same splitBase58.huses. Boost is retained.isProbablePrime.cppbuilds the callback from the query status and charges aCancellationBudgetper wide row, bounding a block of only cheap-exit rows (0.04-0.26 us each) without making them pay for a check.Scope is
UInt128/UInt256, as the changelog entry says. The narrow widths are unchanged (1M rows 3766 -> 3632 ms) and keep the between-blocks granularity they share withisPrime: 3.5 us per row worst case, so one default block is 232 ms, against 20.4 ms per row and 1333 s per block on the wide path.The regression test was removed in review as it asserted wall-clock deadlines; the evidence of record is the CI report of the hang:
Stress test (amd_msan)on #113656.04201_is_prime,04202_is_prime_oracleand04203_is_prime_widestill cover results on every width, but nothing fails if the checkpoint is removed.Version info
26.8.1.1519(included in26.8and later)