Skip to content

Make test_server_overload deterministic instead of probabilistic - #113529

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-server-overload-lottery
Aug 6, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-server-overload-lottery

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Related: #112878

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

test_server_overload/test.py::test_drop_connections fails intermittently with
Expected to drop the connection due to the server being overloaded at least once
(report).

Root cause: the test asserts an event it only makes probable. checkCPUOverload computes
probability_to_throw = (clamp(cpu_load, min, max) - min) / (max - min), so it reaches 1 only
once cpu_load >= max_ratio. The test configured min=1.0, max=6.0, demanding a wait/busy
ratio of 6.0 for a certain drop while its own load produces 3.3 to 5.3. Every probe was a coin
flip near p=0.5, which is why #96106, doubling the probe count and load duration, did not help:
more attempts do not remove the dice.

I instrumented checkCPUOverload locally and sampled every accept-path evaluation with a probe
loop that does not stop at the first drop. Over 318 loaded evaluations at the shape the test
runs, the probability never once reached 1 (mean 0.53); the Bernoulli model is exact, predicting
67.0 drops where 63 occurred.

This change puts max_ratio below the achievable ratio (6.0 to 1.5) so an overloaded window
always drops, and both tests now assert the logged probability is 1. One loaded probe then
suffices, and probe count, pacing and metric reset phase stop mattering. The sibling
test_overload gets the same treatment.

The test becomes stricter, not weaker. The busy_delta > os_cpu_busy_time_threshold
precondition is untouched, so an idle server still yields cpu_load == 0 and is not dropped:
over 254 idle probes that gate held every time with a 4x margin. Both contains_in_log
assertions and the Connection reset by peer check are unchanged.

Validation: 50 randomized repetitions of both cases pass, with the log now reporting
probability used to decide whether to drop the connection 1. Five mutants each turn the test
red, including removing the load, reverting only max_ratio, and neutering the accept-path
filter in Server.cpp.

test_server_overload/test.py::test_drop_connections fails intermittently with
"Expected to drop the connection due to the server being overloaded at least
once". The test asserts an event it only makes probable.

checkCPUOverload computes

    probability_to_throw = (clamp(cpu_load, min, max) - min) / (max - min)

so the probability reaches 1 only once cpu_load >= max_ratio. The test
configured min=1.0, max=6.0, demanding a wait/busy ratio of 6.0 for a certain
drop, while its own four-heavy-query load produces roughly 3.3 to 5.3. Every
probe was therefore a Bernoulli draw near p=0.5, and a run in which all draws
fail trips the assertion. That is also why ClickHouse#96106, which doubled the probe
count and the load duration, did not help: more attempts do not remove the
dice.

Measured with a throwaway instrumented build that logs wait_delta, busy_delta,
cpu_load and probability_to_throw on every accept-path evaluation, driven by a
probe loop that does not stop at the first drop. Over 318 loaded evaluations at
the four-concurrent-query shape the test runs, the probability never reached 1
(mean 0.53, range 0.45 to 0.87), and it never reached 1 in any of the 1236
loaded evaluations across every load shape measured. The Bernoulli model is
exact: the summed per-probe probabilities predicted 67.0 drops where 63
occurred. Of the loaded probes about 10 percent had cpu_load == 0, so the
busy-time gate was not the binding term.

Putting max_ratio below the achievable ratio makes an overloaded window drop
with probability 1. One loaded probe then suffices, so the probe count, the
probe pacing and the phase of the 1 Hz asynchronous-metrics reset all stop
mattering. 1.5 sits 2.17x below the weakest ratio observed at the shape the
test runs (3.2551) and above the highest idle raw ratio (1.4015); even a
degraded three-query load stays clear (weakest 1.8588). Contention on a slower
runner raises the wait/busy ratio, so it moves away from the band rather than
into it. The sibling test_overload had the identical band on the query path and
gets the same treatment.

Both cases now also assert that the probability the server logged is 1, so a
regression that reintroduced a fractional probability would be caught rather
than passing on a lucky draw.

The test becomes stricter rather than weaker. The
busy_delta > os_cpu_busy_time_threshold precondition is untouched, so an idle
server still evaluates to cpu_load == 0 and is still admitted: over 254 idle
probes that gate held every time, with a 4x margin (max busy_delta 74241 us
against the 300000 us threshold). Both contains_in_log assertions and the
"Connection reset by peer" check are unchanged.

Validation: 50 randomized repetitions of both cases pass, with the server log
now reporting "probability used to decide whether to drop the connection 1",
while 50 repetitions of the unmodified files reproduce the CI failure once.
Five mutants each turn the test red, including removing the synthetic load,
reverting only max_ratio, and neutering the accept-path connection filter in
Server.cpp.

Related: ClickHouse#112878
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 fix round; final delta
recheck returned 0 findings). Round 1 raised 4 findings, all AGREED and all fixed. Round 2
found no code defect: the four items below are corrections to the PR text and the validation
table, plus two hazards I went looking for and measured closed.

# Sev Finding Verdict Evidence / action
1 ❌ The tests could not tell a saturated drop from a lucky Bernoulli draw: reverting max_ratio to 6.0 left both cases passing whenever the dice landed right, so the determinism this change establishes was unpinned AGREE, fixed @ 0be329b Each case now asserts the probability the server logged is 1 (test.py:49, test.py:74). New mutant M5 (revert only max_ratio) turns both cases red on that assertion, having passed the pre-existing ones, so a drop did occur and was merely fractional
2 ⚠️ The commit message claimed "291 loaded evaluations", which reproduces under no definition of the population AGREE, fixed @ 0be329b Traced to two different units from two different arms being added together. Re-derived independently from the raw series: 318 loaded accept-path evaluations at the four-concurrent-query shape the test runs, and 1236 pooled across every load shape, with the probability reaching 1 on zero of them. The conclusion is unchanged and stronger
3 ⚠️ The published load range "roughly 2.3 to 4.9" and the "only 4 percent had cpu_load == 0" figure were both wrong AGREE, fixed @ 0be329b Measured 3.2551 to 5.3455 and about 10 percent at the shipped shape. The weakest ratio at that shape is 3.2551, so the margin below 1.5 is 2.17x rather than the 1.55x first published, and 1.24x even at a degraded three-query load
4 💡 The pre-PR validation table still carried the superseded load range, still said "four mutants" where there are now five, and did not mention the two added assertions AGREE, fixed All three corrected before posting, so the table and the commit message now agree
5 💡 Does the new band open a fresh false-red path? A cpu_load between 1.0 and 1.5 gives a fractional probability, which would satisfy the older assertions and then fail the new one DISAGREE Measured by concurrency over the raw series: that interval holds 296 of its 297 probes at exactly two concurrent heavy queries, all from deliberately weakened sweep arms. At three concurrent queries 0 of 228 probes fall in it, and at the shipped four-query shape 0 of 343, minimum 3.2551. Saturation is also exact rather than approximate: the expression evaluates to precisely 1 for every ratio at or above 1.5
6 💡 Can a certain drop starve the test of its own load, since the filter runs at connection-accept time and each heavy query opens a connection? DISAGREE Safe by construction: the four heavy queries are opened first, against an idle server, whose busy-time gate held on 254 of 254 idle probes with a 4x margin (max 74241 us against the 300000 us threshold). Confirmed by the 50-repetition run, which passed 100 of 100 while logging 154 saturated drops

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Every figure quoted in the PR body and commit message was re-derived
independently from the raw instrumented series during this review, including the Bernoulli check
(summed probabilities predicted 67.0 drops where 63 occurred) and the idle-server margin.

Session id: cron:clickhouse-review-slot-9:20260805-155700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The mechanism is deterministic and fully instrumented: a throwaway build logging wait_delta, busy_delta, cpu_load and probability_to_throw on every accept-path evaluation, driven by a probe loop that does not stop at the first drop. Across 318 loaded evaluations at the shape the test actually runs the probability never once reached 1 (mean 0.53, range 0.45 to 0.87); pooling every arm including deliberately weakened loads gives 1236 evaluations, again none at 1. The symptom is a lost coin flip, so it cannot be made on-demand: it reproduced at 1 of 50 locally, matching the CI rate of ~2 hits in 60 days.
b Root cause explained? probability_to_throw = (clamp(cpu_load, min, max) - min) / (max - min) reaches 1 only when cpu_load >= max_ratio. The test set min=1.0, max=6.0, so it demanded a wait/busy ratio of 6.0 for a certain drop while its own load produces roughly 3.3 to 5.3. Each probe was a Bernoulli draw near p=0.5, and a run in which all draws fail trips the assertion. Summing the measured per-probe probabilities predicted 67.0 drops where 63 occurred, so the model is exact.
c Fix matches root cause? It removes the dice at the parameter that controls them: max_ratio moves below the achievable ratio, making an overloaded window drop with probability 1. Not a widened bound, not a skip tag, not a data reduction, and not the lever #96106 already pulled (that lowered min_ratio, which only moves where the ramp starts).
d Test intent preserved / new tests added? Every pre-existing assertion is unchanged byte-for-byte (both contains_in_log checks and the Connection reset by peer check), and the busy_delta > os_cpu_busy_time_threshold precondition is untouched. The test becomes stricter in two ways: a drop is now required rather than probable, and each case gains one purely additive assertion that the probability the server logged is 1, so a regression reintroducing a fractional probability is caught instead of passing on a lucky draw. No new test file is added; this is a determinism fix to an existing test.
e Both directions demonstrated? Yes, same binary and same box. Unfixed (both files restored from HEAD), 50 randomized repetitions: 1 failure with the exact CI assertion Expected to drop the connection due to the server being overloaded at least once. Fixed, 50 randomized repetitions of both cases: 100 of 100 pass, with the server log reporting probability used to decide whether to drop the connection 1.
f Fix is general across code paths? The sibling test_overload reads the same shared CPU delta through the query path and shipped the identical 1 .. 6 band, so it has the identical defect and is fixed in the same PR. Instrumentation confirmed it too never reached probability 1 (5 evaluations, mean 0.5089). The three production checkCPUOverload sites are unchanged.
g Fix generalizes across inputs? A load-strength sweep measured how the achievable ratio degrades with weaker load, pooling every burst across all runs and grouping by the number of concurrently executing heavy queries: 1 query gives min 0.1218 / median 0.1917 (n=259), 2 queries 0.3373 / 1.2673 (n=401), 3 queries 1.8588 / 2.4830 (n=213), and the shipped 4-query shape 3.2551 / 3.5920 (n=318). No probe at 3 or 4 concurrent queries fell below 1.5, so 1.5 sits 2.17x below the weakest ratio observed at the shipped shape and still 1.24x below it at a degraded 3-query load, while remaining above the highest idle raw ratio (1.4015). Contention on a slower runner raises the wait/busy ratio, so it moves away from the band.
h Backward compatible? N/A, tests only. No src/ change. Both settings default to 0 in production (ServerSettings.cpp:1394,1398), so checkCPUOverload returns false immediately on a default server; only this test's own config and SQL change. No SettingsChangesHistory.cpp entry owed.
i Invariants and contracts preserved? The precondition gate busy_delta > os_cpu_busy_time_threshold && wait_delta > 0 is untouched, so "is the server actually overloaded?" is answered exactly as before. Measured over 254 idle probes: that gate held 254 of 254 times with a 4x margin (max busy_delta 74241 us against the 300000 us threshold), so an idle server still evaluates to cpu_load == 0 and is still admitted. Five mutants each turn the test red: removing the synthetic load (both cases fail on the original "at least once" assertion, so the band change did not make drops unconditional), reverting only max_ratio to 6.0 (both cases get past the pre-existing assertions and fail on the new saturation assertion, so a drop did occur and was merely fractional), setting both ratios to the production default 0, raising the busy-time threshold to 1e18, and neutering the accept-path filter in Server.cpp.

Session id: cron:clickhouse-review-slot-9:20260805-155700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexkats, could you review this? You wrote the overload connection filter and this test; the test asked for a wait/busy ratio of 6.0 for a certain drop while its own load produces 3.3 to 5.3, so every probe was a coin flip near p=0.5, and this lowers the test config's max ratio below the achievable ratio so an overloaded window drops with probability 1.

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0be329b]

Summary: ✅


AI Review

Summary

This PR makes test_server_overload deterministic by lowering the overload max_ratio used by the test from 6.0 to 1.5 and by asserting that the observed overload decision was taken with probability 1, not by a lucky Bernoulli draw. I reviewed the current diff, the touched test/config files, the relevant checkCPUOverload implementation and call sites, the full PR discussion, and the current CI state; I did not find a remaining correctness, coverage, or metadata issue that warrants an inline review comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0be329b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT rejected with LogCluster query failed with code 500, so the build-profile upload fails after the build itself succeeded #113409 (external, open)

All 174 check-runs completed, Finish Workflow succeeded, and this is the only failing row on this
commit. The Post Hooks row does not gate the check it runs under, which is why the enclosing
Build (arm_release) reports success while the per-test row is a failure.

Session id: cron:our-pr-ci-monitor:20260805-230000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 6, 2026
Merged via the queue into ClickHouse:master with commit e704174 Aug 6, 2026
180 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 Aug 6, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 23, 2026
test_server_overload::test_overload still failed intermittently after
ClickHouse#113529, which removed the Bernoulli lottery but left a sampling lottery.

checkCPUOverload calls getCPUOverload(os_cpu_busy_time_threshold) with
reset defaulted false (ProfileEvents.cpp:1972). getCPUOverload returns 0
at :2039 while the busy time accrued since the last reset is below the
threshold, and on 0 the caller's `cpu_load > DBL_EPSILON` test fails, so
the ratio, the probability ramp and the draw are never evaluated. The
only reset=true caller is AsynchronousMetrics.cpp:2734, so both
consumers share one prev_* pair: every reset window opens at zero busy
time and its first threshold/busy_rate is a window in which an
overloaded server provably cannot throw.

The probe loop samples that grid at about 0.99 s per iteration, because
each node1.query() spawns a fresh clickhouse-client process against a
one-core-pinned server, so the 0.3 s sleep is not the period. Against
the reset cadence that is a near-resonance: the phase drifts only about
9 ms per iteration, so a run whose starting phase lands inside the blind
window stays inside it for every probe that overlaps the 30 s load, and
the loop falls through to the assertion. On the failing CI runner the
per-probe busy time was around 8000 us against the 300000 us budget.

Setting the fixture's threshold to 0 removes the blind window, so the
verdict follows the measured wait/busy ratio rather than the probe's
arrival time. 0 is the degenerate in-domain value rather than another
calibrated constant: at :2039 the test becomes busy_delta <= 0 ||
wait_delta <= 0, exactly the liveness precondition the ratio needs to be
defined. Anything larger has to encode a busy rate and a reset cadence
that the setting cannot observe, which is why a smaller nonzero value
was measured to change no outcome at all.

This does not weaken the test. What excludes an unloaded server is
min_os_cpu_wait_time_ratio_to_throw, not the busy-time budget: measured
on an idle node at threshold 0, the ratios that now reach the ramp are
0.14 to 0.47, all giving probability 0 and no throw, while 5 of 9 idle
windows are still refused on the wait_delta clause. Both
"probability ... 1." assertions from ClickHouse#113529 are kept, so the saturated
ramp remains the thing under test, and the test now throws on its first
probe instead of iterating.

Validated in both directions. With the fix, test_overload passes 10/10
on debug, 10/10 on asan+ubsan and 50/50. With the throttle mutated it
still reddens: checkCPUOverload returning early fails 3/3, the
probability ramp forced to 0 fails 3/3, and the threshold set
unreachably high fails 3/3, each with the assertion CI reported. The
pre-fix config plus a disabled throttle also fails 3/3, so the
sensitivity was not created by this change. test_drop_connections passes
10/10 with its own config untouched.

node2's early_drop.xml keeps the same budget: it shares the blind window
but is green today, and its config also carries the drop-connection
ratios. The product default os_cpu_busy_time_threshold = 1'000'000 is
also unchanged; the shared prev_* pair gives any server a short blind
window each period, which is a product question rather than one to
settle from a test fix.
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 12, 2026
… test_server_overload

test_overload asserted the rendered value of the throttle's rejection
probability ("probability used to decide whether to discard the query 1."),
i.e. p == 1. Both setting pairs document p as a linear interpolation between
min and max ratio, and ProfileEvents::checkCPUOverload implements exactly
that: p = (clamp(cpu_load, min, max) - min) / (max - min), followed by one
Bernoulli draw. With the test's min=1, max=1.5, p reaches 1 only when the
runner's wait/busy ratio reaches 1.5. The CI runners that run this test
produce 1.287 - 1.393, so p is fractional and the second assertion fails
while the rejection itself is correct: the observed 1.2870989304812834 gives
0.5741978609625669, matching the failure log exactly. The assertion was a
statement about the runner, not about ClickHouse.

Drop the asserted value on both carriers and keep the message check. The
query-path assertion is rewritten value-free rather than deleted, because
SERVER_OVERLOADED is also raised by the workload scheduler (FifoQueue,
AllocationQueue), so asserting the error code alone would no longer pin the
rejection to the CPU throttle. On the connection path the identical assertion
is deleted outright, since the preceding line already asserts the same string
without its value.

max = 1.5 is kept on both paths: at the ratios CI produces it puts the
per-probe rejection probability at 0.57 - 0.79, so a rejection within the
test's 60 probes is effectively certain. The two comments stating the refuted
premise (that max is below the ratio the load produces, so the ramp
saturates) are rewritten to state the ramp semantics instead.

Verified by constructing the CI condition locally. This box reaches ratios of
3.5 - 7.1, above max, which is why the stock test passes here, so max was
raised above that range to put the ratio inside the band. On the unfixed tree
test_overload then fails 5/5 with the exact CI assertion and fractional
probabilities; with this change, on the same binary and configuration, it
passes 5/5, and 50/50 on the shipping config. Removing only the probability
clause from the server message reddens exactly the two rewritten assertions
while the error-code and log-line assertions still pass; zeroing the ramp,
disabling the check, and removing the synthetic load each still redden the
behavioural oracle.

Follow-up to ClickHouse#113529 and ClickHouse#115905.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-ci 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