Skip to content

Throttle the clickhouse-test hung-check liveness probe so it stops starving the parent loop - #112393

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/throttle-hung-check-liveness-probe
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/throttle-hung-check-liveness-probe

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

The hung-check probe in do_run_tests sits inside the while processes: sleep(0.1) loop with no
interval gate, unlike the sibling memory check 40 lines above gated on MEMORY_CHECK_INTERVAL. The
comment says "Periodically"; there is no period. And check_server_liveness runs its whole
10-attempt retry loop synchronously. So a healthy 3 h run issues ~72000 SELECT 1 /*liveness check*/
probes at the very server whose saturation is being diagnosed, and while the server is slow the
parent blocks 65 to 165 s and re-enters at once (a 92.7% blocked duty cycle), running neither the
memory-pressure worker shed - the only mechanism that could relieve it - nor the deadline check, nor
stop_testing. The verdict itself is correct and is not made more tolerant: the gap to verdict
matches the probe's own budget exactly across 14 CI job logs, and 32 of 166 hits in 45 days had no
server.

Only the scheduling changes, in four caller-side edits; check_server_liveness is untouched:
interval-gate the probe at 30 s on a fresh time(); pass max_retries=1 and reproduce master's
10-attempt back-off as loop-owned state, bounding each poll by one socket timeout; require a liveness
confirmation at or after the deadline before claiming it; and drain a pending failure sequence past
the loop. The last two matter because splitting the window lets the loop reach the deadline block
between two failing probes, and exit mid-sequence when the workers finish - invariants master held
only incidentally.

Both abort budgets are preserved, the verdict string is byte-identical because CIDB keys on it, and a
312-scenario sweep finds 0 cases where this aborts and master does not. Detection latency rises
by up to 30.4 s against the job's own at-least-900 s margin. The new
ci/tests/test_hung_check_schedule.py drives the real do_run_tests on a fake clock: 29 tests, 14
failing on the pristine script.

Measurements, residuals, mutation matrix, and the #106385 interaction

A fake-clock harness drives the real do_run_tests through runpy with patched globals, comparing
pristine master against this branch. A real-server repro would need a multi-minute stall under 19-way
load on an instrumented build.

scenario master this PR
dead server, instant refusal: abort at 65.1 s 66.0 s
dead server, socket timeout: abort at 165.1 s 166.0 s
healthy 3 h run: probes issued 72001 359
healthy 3 h run: blocked duty cycle 33.3% 0.2%
dead-instant: blocked duty cycle 92.7% 0.0%

The instant-refusal band matters most: that is where the 32 hits with no server process land. An
earlier design of mine aborted those at 150 s instead of 65 s, 2.3x slower to report a real death, and
I rejected it for that reason. The 312-scenario sweep also finds 0 aborting earlier, and a
1314-scenario drain sweep 0 spurious aborts. Second residual: 156 of those 1314 are not reproduced,
every one a stall barely exceeding master's own window where the server recovered, so no permanent
death is missed.

33-mutant matrix, predicting the failing test before each run: 31 killed by a named test and 1 (M21)
by the suite failing to terminate, itself a detected defect. The one survivor guards against claiming
the deadline twice and is unreachable because the loop sets the flag together with stop_testing,
never cleared; rather than delete it I pinned the facts that make it so.

#106385 (@ PedroTadim, open) edits check_server_liveness itself, adding
if os.path.isfile(_RESTART_MARKER_FILE) and max_retries < 30: max_retries = 30 inside the retry
loop, so a max_retries=1 call would silently become a 30-attempt call during a stress restart -
exactly the per-poll bound this PR relies on. Complementary, but whichever lands second should confirm
the one-attempt contract still holds. Nothing to do on that branch.

groeneai added 2 commits July 28, 2026 16:49
The hung-check probe in `do_run_tests` sat directly inside the
`while processes: sleep(0.1)` loop with no interval gate, unlike the sibling
memory check 40 lines above which is gated on `MEMORY_CHECK_INTERVAL`. The
comment said "Periodically"; there was no period. And `check_server_liveness`
runs its whole 10-attempt, up-to-165s retry loop synchronously.

So a healthy hours-long run issued `SELECT 1 /*liveness check*/` roughly every
0.1s (72001 probes on a modelled 3h run), putting continuous pointless load on
the very server whose saturation is being diagnosed. And when the server was
slow the parent blocked inside the probe for the full 65 to 165s and re-entered
immediately on return, so starvation was effectively continuous (92.7% blocked
duty cycle measured). While blocked the parent ran neither the memory-pressure
worker shed, which is the one mechanism that could relieve the pressure, nor the
`args.stop_time` deadline check, nor `stop_testing` handling.

The verdict itself is correct and is not made more tolerant. Across 14 CI job
logs the gap to verdict is bimodal at 63-69s and 165-166s, exactly the probe's
own 10-attempt budget, zero log lines fall inside the probe window in 14 of 14
runs, and the progress index advances by exactly +1 across the verdict. The
`[ OK ]` lines after the verdict are recovery during lldb collection. This
changes only the probe's scheduling.

Four caller-side changes; the callee is untouched. Interval-gate the probe at
30s reading a fresh `time()`; pass `max_retries=1` and reproduce master's
10-attempt schedule as loop-owned state; gate the benign-deadline block on a
liveness confirmation taken at or after the deadline; and add a terminal drain
after the loop that finishes a pending failure sequence and claims the deadline.

The last two are not cosmetic. Splitting the retry window lets the loop reach the
deadline block between two failing probes, and lets the loop exit while a failure
sequence is pending because the workers finishing ends it. Master satisfied both
invariants only incidentally, since its single blocking call spanned the whole
window and so could not be cut short. Without the drain a death after the last
probe escapes the check and the run reports a generic failure, not `Server died`.

Both abort budgets are preserved (65.1s to 66.0s, 165.1s to 166.0s), healthy-run
probes drop from 72001 to 359, and the verdict string is kept byte-identical
because CIDB queries key on it. Across a 312-scenario stall sweep in both memory
regimes there are no cases where this aborts and master does not, and none where
it aborts earlier; a 1314-scenario drain sweep also finds none.

Two residuals, both conservative: detection latency rises by up to 30.4s against
the job's own margin of at least 900s, and 156 of 1314 drain-sweep aborts are not
reproduced, every one a case where the stall barely exceeds master's own window
and the server in fact recovered, with no permanent death missed.

Adds ci/tests/test_hung_check_schedule.py (25 tests, structural plus behavioural
on a fake clock), where there was previously no coverage of the hung-check
schedule at all.
Review round 1 on the hung-check test suite. Three defects in the test
harness, none in the production change.

The harness ran `do_run_tests`' graceful-deadline paths, which install
`SIGTERM = SIG_IGN` process-wide (tests/clickhouse-test:5220, :5349) and
never restore it. `run_loop` restored six module globals but not the
signal disposition, which is not a module global. `SIG_IGN` survives
exec (CPython's `_Py_RestoreSignals` resets only SIGPIPE/SIGXFZ/SIGXFSZ),
so the leak stopped every later test in the same pytest process from
being able to SIGTERM a child: TeePopen terminates via
`os.killpg(pid, SIGTERM)` and the three
`test_teepopen_timeout_kills_process` cases assert `rc == -SIGTERM`.
`run_loop` now captures and restores the disposition, and a regression
test asserts it is unchanged across a run that really takes the SIG_IGN
path.

The harness also kept the real `multiprocessing.Manager`, which forks a
server process and binds an AF_UNIX listener under `$TMPDIR` against a
108-byte path cap, so under a long `TMPDIR` all sixteen behavioural
tests died before `do_run_tests` ran. The IPC bought nothing: the
production code only calls `.list()` and `.extend()` on the result and
the fake workers never read the queue. A plain-list stand-in replaces
it; `Value` and `Event` need no server process and are kept.

Finally, the suite asserted the schedule arithmetic but not the property
the change exists for: that the parent keeps running the memory-pressure
worker shed, the deadline check and stop handling between failed probes.
Three tests now pin it, including that `workers_to_shed` is actually
incremented rather than the message merely printed.

25 tests to 29. Suite wall-time 5.0s to 2.5s, whole ci/tests 139s to
46s. No change to tests/clickhouse-test.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 9 findings, click to expand)

Before opening this I ran two independent review rounds against the change: a cold read of the
resulting code without the author's evidence, then an adversarial second-model pass. Round 1 bounced
the branch back with a blocker and two majors; round 2 came back clean from the second model. Every
finding is listed with its verdict, including the ones I disagreed with.

Round 1

❌ blocker - the test harness leaked SIGTERM = SIG_IGN into the shared pytest process. AGREED.
do_run_tests' graceful-deadline paths install SIG_IGN process-wide and never restore it; the
harness restored six module globals but not the signal disposition, which is not a module global.
SIG_IGN survives exec (CPython's _Py_RestoreSignals resets only SIGPIPE/SIGXFZ/SIGXFSZ), so
three later test_teepopen_timeout_kills_process cases - which assert rc == -SIGTERM against a
killpg-based watchdog and sort after this file alphabetically - could no longer terminate their
children. Fixed by capturing and restoring the disposition, plus a regression test.

⚠️ major - the harness bound a real multiprocessing.Manager AF_UNIX listener. AGREED. Under a
long TMPDIR the 108-byte socket path cap made all sixteen behavioural tests die before
do_run_tests ran. The IPC bought nothing: the production code only calls .list() and .extend()
on the result. Replaced with a plain-list stand-in, which also cut the file from 5.0 s to 2.5 s.

⚠️ major - the PR's headline property was asserted nowhere. AGREED. The suite pinned the schedule
arithmetic thoroughly but nothing checked that the parent actually keeps running the memory shed, the
deadline check and stop handling between failed probes, which is the entire point of the change.
Three tests now pin it, including that workers_to_shed is really incremented rather than the shed
message merely printed.

💡 Three nits on the PR text, all corrected: a self-contradictory test count, an unverified claim
about #106385 now quoted verbatim from its diff, and a mutation kill count that was one too high.

Round 2

The second model returned no findings, having read the full new test file, the complete
do_run_tests, the liveness callee and all of its callers, the deadline/stop/worker lifecycle paths
and the sibling memory scheduling.

My own cold read found three problems in the PR text rather than the code, all fixed here: the
description was several times longer than it should be for a merge decision and is now condensed
with the measurement detail collapsed; four figures were stale after the suite grew from 25 to 29
tests; and the mutation total was overstated by one in two places because a prose running total had
been incremented from the highest mutant id, while id M12 was skipped and never renumbered - the
matrix records 33 mutants, 31 killed by a named test, 1 by the suite failing to terminate, and 1
documented survivor. The matrix footer now carries the derivation rule so this cannot drift again.

💡 One nit noted and not fixed: there are two SIG_IGN producers, and the dedicated leak assertion
traverses only the in-loop one. The harness restores unconditionally in a finally, so both are
already protected for every test in the file; the gap is in which path that one assertion walks, not
in the protection, and two mutants pin the guarantee.

✅ Verified independently rather than taken on trust: the 65 s back-off ladder sums exactly;
max_retries=1 really does skip the callee's internal back-off; the memory limit really is not
cached on failure, which is what makes the fresh-time() gate load-bearing; master really does
check the deadline before the hung check; and all six check_server_liveness call sites resolve as
the change claims, with only the polled one altered. I also re-swept for other process-global state
the harness could leak - the class the round-1 blocker belonged to - and found none.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, in-process on a fake clock driving the real do_run_tests via runpy with patched module globals: 72001 vs 359 probes on a modelled 3 h healthy run and a 92.7% vs 0.0% blocked duty cycle, reproducible on demand with zero wall-clock waits. Not a "~1%" flake. The real-server stall it reports is not locally reproducible (it needs a multi-minute stall under 19-way load on an instrumented build) and the PR body says so explicitly rather than implying a repro.
b Root cause explained? Yes. The probe sits directly in the while processes: sleep(0.1) loop with no interval gate, unlike the sibling memory check 40 lines above which is gated on MEMORY_CHECK_INTERVAL; the comment says "Periodically" but there is no period. Compounding it, check_server_liveness runs its whole 10-attempt / up-to-165 s retry loop synchronously, so a slow server blocks the parent for the full window and the loop re-enters immediately on return, starving the memory-pressure worker shed, the args.stop_time deadline check and stop_testing handling.
c Fix matches root cause? Yes: gate the poll at 30 s off a fresh time() and move the retry window into the loop via max_retries=1. Explicitly not a band-aid: it does not widen a bound, add tolerance to the verdict, raise timeout/max_retries, reduce a dataset, or suppress the detector. Both abort budgets are preserved to within 1 s (65.1 to 66.0 s, 165.1 to 166.0 s) and the verdict string is byte-identical. The hung check's verdict is correct and stays correct.
d Test intent preserved / new tests added? Yes. The hung check still aborts and still reports; nothing is weakened or deleted. Added ci/tests/test_hung_check_schedule.py with 29 tests where there were 0 (ci/tests/ runs on every PR). The suite pins both abort budgets, so a future change cannot silently make the detector slower or more tolerant, and it now also pins the PR's headline property: that the parent keeps running the memory shed, the deadline check and stop_testing handling between failed probes.
e Both directions demonstrated? Yes. 14 of the new tests fail when the pristine tests/clickhouse-test is swapped in and all 29 pass here; every headline metric was measured on both trees; and a 33-mutant matrix (prediction recorded before each run, source md5 asserted restored after each) kills 31 by a named test and one by the suite failing to terminate, which is itself a detected defect. The single survivor is a guard against claiming the deadline twice, provably unreachable because the loop already sets the flag; rather than delete the assertion I added an invariant test that the deadline can be claimed only once. The starvation property additionally has a one-variable control: the same 493-test ci/tests suite on the same tree fails 3 test_teepopen_timeout_kills_process cases with the harness's signal leak present and 0 with it fixed, reproduced across alternating arms with 0 newly broken.
f Fix is general across code paths? Yes. All 6 check_server_liveness call sites re-grepped: only the parent-loop one is polled, one already passes max_retries=1, and the other four are event-driven one-shot classifiers where the full retry window is the point, so changing them would weaken SERVER_DIED classification and they are deliberately untouched. Sibling polling loops enumerated; the remaining two are already bounded. Fixed at the source (the caller's schedule), not guarded at the symptom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Parameterised over both probe costs (instant refusal and 10 s socket timeout), both memory regimes (cached and uncached limit fetch), 312 stall scenarios, 1314 drain scenarios, deadlines both on and off the 30 s probe grid, and worker-finish offsets straddling recovery by -30 s to +20 s. Boundary cases pinned: the first poll at t=0, the exact-deadline >= case, and workers finishing exactly at the deadline.
h Backward compatible? (maintainer-approved exception only) Yes, nothing engaged: no settings, no serialization, no formats, no protocol, and SettingsChangesHistory.cpp is not involved. The verdict string is kept byte-identical because CIDB queries key on it. No src/ or programs/ change, so the build is untouched.
i Invariants and contracts preserved? Yes, and two that master held only incidentally are now held explicitly, which is the most consequential surface here since it decides whether CI reports Server died or a benign timeout. (1) A death shortly before args.stop_time must not be reported as an expected timeout, so the deadline block now requires a liveness confirmation taken at or after the deadline. (2) A death after the last probe must still be reported: the loop's exit is a carrier, because the workers finishing can now end a pending failure sequence, hence the terminal drain. The drain honours the loop's remaining back-off so it cannot collapse two attempts and condemn a server that would have answered, costs at most one extra probe and ~0 wall-clock on a healthy run, and claims the benign deadline exactly once. The healthy-run graceful stop is separately pinned, since the flaky and targeted checks depend on that deadline being their expected stop condition.

Decisive result: across a 312-scenario stall sweep in both memory regimes there are 0 cases where this branch aborts and master does not, and 0 where it aborts earlier; the drain-specific sweep over 1314 scenarios also finds 0. Two residuals are disclosed in the PR body rather than claimed away: detection latency rises by up to 30.4 s (against the job's own >=900 s margin), and 156 of 1314 drain-sweep aborts are not reproduced, every one a case where the stall barely exceeds master's own window and the server in fact recovered (0 permanent deaths missed).

Session id: cron:clickhouse-review-slot-8:20260729-044501

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @leshikus - could you review this? It interval-gates the clickhouse-test hung-check probe and moves check_server_liveness's retry window into do_run_tests' own loop (max_retries=1 plus the 10-attempt back-off as loop state), so the parent stops blocking for the whole 65-165 s window and keeps running the memory shed and the deadline check between probes. Both abort budgets and the verdict string are unchanged; you have adjacent changes to this file in #112058/#111213.

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

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44b7759]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Logical error: Query context must be created after authentication (STID: 3197-20e5) FAIL cidb
Stress test (arm_debug) FAIL
Logical error: Query context must be created after authentication (STID: 3197-391f) FAIL cidb

AI Review

Summary

This PR moves the hung-check retry window out of check_server_liveness and into the parent do_run_tests loop, adds interval gating for healthy runs, and adds a large fake-clock regression suite around the new schedule. The main change looks directionally correct and the CI report is green, but the terminal drain still has a correctness gap: after the loop has already observed a successful liveness probe at or after args.stop_time, the drain re-probes unconditionally and can still downgrade that already-confirmed benign timeout into Server died.

Findings

⚠️ Majors

  • [tests/clickhouse-test:5436-5458] The terminal drain re-enters check_server_liveness even after the loop has already recorded last_hung_check_ok >= args.stop_time. That violates the new deadline contract: once the run has confirmed the server was alive at or after the deadline, later disappearance during worker teardown must not overwrite the result to STOP_TESTING_EXIT_CODE. On the current head, the PR’s own harness still reproduces this with run_loop(alive=lambda t: t < 200.11, deadline=200.0, workers_done=200.0), which returns server-died instead of the benign global-time-limit exit. Short-circuit the drain to GLOBAL_TIME_LIMIT_EXIT_CODE when a post-deadline success has already been recorded, and add that scenario as a focused regression case in ci/tests/test_hung_check_schedule.py.
Final Verdict

Needs changes: keep the existing inline thread open and fix the terminal-drain misclassification before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 29, 2026
Comment thread tests/clickhouse-test
# otherwise a death after the last successful probe would leave the run
# reporting a generic failure instead of `Server died` (master's single
# blocking call spanned the whole window and so could not miss it).
if args.hung_check and not stop_testing.is_set():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Once last_hung_check_ok >= args.stop_time has already been recorded in the loop, this unconditional drain probe can still overturn the already-confirmed benign deadline if the server disappears after the last worker exits. Using the new harness, run_loop(alive=lambda t: t < 200.11, deadline=200.0, workers_done=200.0) produces (200.10, True) from the deadline-triggered probe, then the drain immediately re-probes at 200.15, starts a fresh failure ladder, and eventually returns server-died. At that point the run has already proved the deadline condition; the drain should short-circuit to GLOBAL_TIME_LIMIT_EXIT_CODE instead of re-checking liveness, and a focused regression case should pin this race.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6b731df

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit fails 3/3 reruns under parallel replicas on coverage builds (result differs with reference variant of the same test) #112385 (ours, merged 2026-07-29 15:37Z) - this build predates the fix

Session id: cron:our-pr-ci-monitor:20260729-164745

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 44b7759

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_debug) / Logical error: Query context must be created after authentication (STID 3197-391f) pre-existing trunk race, not introduced by this branch: 64 hits in 30 days including 7 on true master, spread over 35 unrelated PRs and 7 sanitizer flavours #112940 (external, open)
Stress test (arm_release) / same logical error (STID 3197-20e5) same signature, 9 hits in 30 days, 0 on master #112940 (external, open)

Not PR-caused: this PR changes only tests/clickhouse-test (throttling the hung-check liveness
probe) and adds ci/tests/test_hung_check_schedule.py. Both aborts are server-side in the
authentication path, with no hung check involved.

Session id: cron:our-pr-ci-monitor:20260828-020000

This branch has not been deployed

No deployments
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 comp-testing Test content only (no production code). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants