Skip to content

Bound each stress teardown attempt so a wedged server cannot burn the job budget - #112927

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:ci/bound-stress-teardown-handshake
Sep 12, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:ci/bound-stress-teardown-handshake

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

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

Related: #108775 (its failing Stress test (arm_tsan) job, and the request for a separate fix PR)

This completes bada962, whose message states the goal: stop_server's
SYSTEM STOP DISTRIBUTED SENDS loop could burn 30 x 300 = 9000 s. It added
--receive_timeout=10, but that flag is inert here, so the loop is still unbounded.

The client holds handshake_timeout until sendHello completes (Connection.cpp:264-265) and
swaps in receive_timeout only afterwards (:352-353); the CLI's handshake default is
300 000 ms (ConnectionParameters.cpp:177), not the setting's 10 000 ms. Against a server that
accepts TCP but never answers Hello, receive_timeout is therefore never reached: measured,
--receive_timeout=10 and =3 both take 300 s and report 300000 ms, while
--handshake_timeout_ms=10000 takes 10.2 s.

I pass --handshake_timeout_ms=10000 so the common case fails in 10 s with a diagnostic, and
wrap the attempt in timeout -s KILL 15 so the bound is unconditional, since the flag alone
leaves a mid-send stall on send_timeout, still 300 s. timeout is the shape used for this in
2f787c6. All 30 iterations are kept: worst case 450 s, not 9000 s, so patience is
redistributed, not reduced.

This does not fix the server-side stall and is not offered as one: a job that now hits the
10800 s cap and dies before uploading anything will instead report the stall with its logs
attached. Its "server did not stop yet" rows appear 91 times in 2026-08-11..2026-09-09, 84% on
TSAN variants, 9 on master.

Validation is local, not in-tree: against a mock client the loop finishes on a wedged server
while the pre-fix text does not, and a server recovering on the 6th try is still retried. A
pytest file under ci/tests carried this at first; I dropped it, because the job that ran
pytest there was removed in 8ff3720. Changing the 300 s client default would be
user-visible, so I left that out.


Workflow [PR]
Sync PR [sync-upstream/pr/112927]

… job budget

`stop_server` retries `SYSTEM STOP DISTRIBUTED SENDS` up to 30 times before
`clickhouse stop`. bada962 added `--receive_timeout=10` to cap each attempt
at 10 s, because at the 300 s default the loop can burn 30 x 300 = 9000 seconds
and consume the whole CI job timeout. The intent was right, but the flag is
inert on this path, so the loop is still unbounded today.

The client sets the socket to `handshake_timeout` before `sendHello`
(src/Client/Connection.cpp:264-265) and swaps in `receive_timeout` only once the
handshake completes (:352-353, "Now that the handshake is complete, use the
regular timeouts"). The client CLI's own handshake default is
DBMS_DEFAULT_RECEIVE_TIMEOUT_SEC * 1000 = 300000 ms
(src/Client/ConnectionParameters.cpp:177), not the 10000 ms of the
`handshake_timeout_ms` setting. So against a server that accepts the TCP
connection but never answers Hello, `receive_timeout` is never reached.

Measured against a socket that accepts and never writes: `--receive_timeout=10`
takes 300.4 s and reports `300000 ms`, `--receive_timeout=3` also takes 300 s
and reports `300000 ms`, and `--handshake_timeout_ms=10000` takes 10.2 s and
reports `10000 ms`. Two different `receive_timeout` values producing the same
elapsed time is the proof that the flag does not apply here.

Pass `--handshake_timeout_ms=10000` so the common case fails in 10 s with a
diagnostic, and wrap the attempt in `timeout -s KILL 15` so the bound is
unconditional: the flag alone still leaves a mid-send stall on `send_timeout`
(300 s, not passed here) and a DNS or TLS wedge on nothing at all. The wrapper
is the shape 2f787c6 used for this same failure mode in the PGO readiness
probe, and `timeout` is already used in this file and in upgrade_runner.sh, so
the image is unchanged. 10000 ms is the `handshake_timeout_ms` setting's own
default (src/Core/Settings.cpp:402) and one third of the server's own handshake
ceiling (src/Core/ServerSettings.cpp:1405), so it sits well above a healthy
handshake under thread fuzzer and well below the point where the server itself
would have dropped an unauthenticated connection.

All 30 iterations are kept, so the worst case goes from 9000 s to 450 s. This
is a redistribution of patience rather than a reduction: a server that is merely
slow to stop still gets 30 attempts.

This does not fix the server-side stall and is not intended to. When the loop
consumes the job budget the runner is killed before the artifact-upload step, so
`clickhouse-server.stress.log.zst`, the one file that could identify the stalled
threads, is never uploaded. Bounding the loop converts a lost job into a job
that reports the stall with its logs attached.

The new test runs the loop text verbatim, extracted between the BEGIN/END
markers, against a mock client, in the shape of the existing
ci/tests/test_logs_cluster_probe_loop.py. It asserts that the loop finishes
against a wedged mock, that the pre-fix text does not finish under the same
budget, that a mock recovering on the 6th attempt is still retried, and that the
handshake bound reaches the client's argv.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (0 blockers, 0 majors, 2 nits) — click to expand

Before opening this PR I ran an independent cold review of the resulting code (without the
implementation notes, to avoid anchoring) and a second-model review pass. Verdicts and evidence:

# Finding Severity Verdict
1 The bounded-loop test asserts that the loop finished, not an explicit elapsed time, so it does not directly measure the per-attempt cap. 💡 nit Disagree — the oracle is behavioral, just indirect. The wedged mock sleeps 60 s against a 12 s budget, so a missing timeout wrapper makes the run exceed the budget and the assertion fires. Reverting the shipped line to the exact pre-fix text produces AssertionError: loop did not finish within its budget, i.e. a timing failure rather than a text match. An elapsed assertion would duplicate an already-red oracle.
2 stress_tests.lib:299 (start_server) and :325 (check_server_start) still pass only --receive_timeout 30, so they keep the same 300 s handshake exposure. 💡 nit Agree, deliberately out of scope — neither can burn the job budget the way this loop can: start_server's until loop is bounded by its own counter > max_attempt and check_server_start is a single call whose failure is handled. Left as a named follow-up rather than folded in (one concern per PR).

Things I checked that did not produce findings, since they are the parts most worth doubting:

  • The flag is genuinely plumbed, not a setting the client would reject. Every Settings entry
    is registered as a CLI option (ClientBase.cpp:4184-4186 -> BaseSettingsProgramOptions.h:70-76)
    and argsToConfig (ClientApplicationBase.cpp:237) copies it into the client config that
    ConnectionParameters.cpp:177 reads. --handshake_timeout_ms has existed since 846804f
    (v23.5), which matters because upgrade_runner.sh:149 runs stop_server with a
    previous-release client on PATH.
  • A 15 s ceiling cannot truncate a legitimate success. With no table, SYSTEM STOP DISTRIBUTED SENDS resolves to startStopActionInDatabase -> ActionLocksManager::add ->
    getActionLock, which is async_insert_blocker.cancel() for Distributed
    (StorageDistributed.cpp:1960-1965) and the IStorage.h:602 no-op default elsewhere: in-memory
    lock bookkeeping, no I/O and no flush. In the reference job's own log all four healthy
    invocations completed in 0-1 s.
  • Patience is preserved, not traded away. {1..30} is untouched, so the worst case moves from
    the 30 x 300 = 9000 s that bada962's own message names to 30 x 15 = 450 s.
  • The regression test cannot go vacuous. Its pre-fix arm is a frozen literal copy of the old
    loop text, so it cannot silently start exercising the fixed text, and test_production_values
    pins the shipped values independently of the scaled copies.
  • The breadth figure quoted in the description (54 rows over 30 days, 74% arm_tsan) reproduces
    against the CI database: 54 rows / 25 commits / 40 arm_tsan / 2 on master.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, no build and no server needed. A 5-line python listener that accept()s and never writes reproduces the wedged-handshake state; clickhouse client --receive_timeout=10 against it takes 300.4 s and reports 300000 ms. Size the outer timeout above 300 s, otherwise both arms read identical.
b Root cause explained? Yes. The client sets the socket to handshake_timeout before sendHello (Connection.cpp:264-265) and swaps in receive_timeout only after the handshake completes (:352-353). The client CLI's handshake default is 300 000 ms (ConnectionParameters.cpp:177), not the 10 000 ms of the handshake_timeout_ms setting, so a server that accepts TCP without answering Hello is bounded at 300 s and receive_timeout is never reached.
c Fix matches root cause? Yes, and it is the completion of bada962 rather than a new mitigation: that commit's own message states the 30 x 300 = 9000 s arithmetic and the intent to cap each attempt at 10 s. The flag it chose is inert on this path. --handshake_timeout_ms=10000 addresses the exact phase; timeout -s KILL 15 makes the bound unconditional. No bound is widened, no assertion weakened, no upstream error masked.
d Test intent preserved / new tests added? Both. The loop's intent (be patient with a server that is merely slow to stop) is preserved: all 30 iterations are kept, asserted by test_production_values and by test_recovering_server_is_still_retried (mock fails 5 times, succeeds on the 6th, loop breaks after exactly 6 invocations). A new pytest guard ci/tests/test_stress_stop_server_bounded.py is added, including an arm that runs the pre-fix text and requires it to be unbounded.
e Both directions demonstrated? Yes. Mutating the shipped line back to the exact pre-fix text takes the suite from 5 passed to 3 failed / 2 passed, and restoring returns 5 passed. The bounding test reddens on a timing observation (loop did not finish within its budget), not on a text match. The client arms measure 300.4 s (pre-fix flag) against 10.2 s (post-fix flag) and 15.0 s (wrapper).
f Fix is general across code paths? Yes. The invariant is that every client probe in stress and upgrade teardown terminates in bounded time regardless of server state. All carriers were enumerated: this loop was the only unbounded one; make_query_command's 15 consumers are already bounded at 30 s via call_with_retry and check_output, RandomQueryKiller at 5 s, start_server and check_server_start by their own retry loops, and the PGO readiness probe by 2f787c6. The fix is in the owning function, so all 6 stop_server call sites inherit it.
g Fix generalizes across inputs (params/datatypes/wrappers)? The input axis here is server state, not data types. All three states are covered by tests: wedged before Hello (bounded), transiently failing then recovering (still retried), immediately failing (loop runs its course). The timeout wrapper covers states the flag cannot: a post-Hello stall is bounded by receive_timeout, a mid-send stall by send_timeout (still 300 s and not passed here), and a DNS or TLS wedge by none of them.
h Backward compatible? Yes, trivially: this is CI harness only. No setting default changes, so no SettingsChangesHistory.cpp entry; no serialization or format change; clickhouse-client itself is untouched.
i Invariants and contracts preserved? Yes. stop_server already tolerated this command failing: the if falls through to the next iteration and clickhouse stop --max-tries ... --do-not-kill runs regardless, so a timeout-induced failure is indistinguishable downstream from the pre-existing failure mode. set -ex is in force (stress_tests.lib:3) but the command stays inside an if condition, so a non-zero exit still does not abort the script. -s KILL targets only the spawned client, leaving the server, the pid file and the $pid capture untouched, and nothing before the loop can be skipped by a shorter loop.

Session id: cron:clickhouse-impl-slot-46:20260801-143400

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? The stress teardown loop passed --receive_timeout=10, but the client holds the 300 s handshake timeout until Hello completes, so against a server that accepts TCP without answering, each of the 30 attempts blocked 300 s and only the job cap bounded the loop. This passes --handshake_timeout_ms=10000 and wraps the attempt in timeout -s KILL 15, keeping all 30 iterations.

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

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4d9c924]

Summary: ✅


AI Review

Summary

This PR updates stop_server in tests/docker_scripts/stress_tests.lib so each SYSTEM STOP DISTRIBUTED SENDS attempt is bounded by --handshake_timeout_ms=10000 and an outer timeout, preventing a wedged pre-Hello connection from consuming the CI job budget. I reviewed the current diff, the prior discussion, and the shared callers in the stress and upgrade runners, and I did not find remaining correctness or compatibility problems in the current code.

Final Verdict

✅ Approve. No new blockers or majors.

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

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a3fb630

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.

CI is terminal on this head (174 check-runs, 0 queued or in progress, both aggregators green). Three failures, all one signature:

Check / test Reason Owner / fixing PR
Stress test (arm_msan), Stress test (arm_asan_ubsan), Stress test (amd_asan_ubsan) / Logical error: Query context must be created after authentication (STID 3197-391f) a trunk regression that first appeared today, not caused by this pull request. PostgreSQLHandler::cancelRequest builds a query context from a Session that has not authenticated. Keyed on the message rather than the STID (three STIDs are pooled: 3197-391f, 3197-3ab5, 3197-20e5), the last 30 days hold 38 rows across 19 carriers including 9 on master, with the first hit ever at 2026-08-01 15:04:09Z. My diff here is two files, ci/tests/test_stress_stop_server_bounded.py and tests/docker_scripts/stress_tests.lib, and touches nothing in the PostgreSQL wire protocol or session handling a fix task is created (investigating at full effort - fixing PR link to follow on this pull request)

Session id: cron:our-pr-ci-monitor:20260801-203000

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the pre-auth Query context must be created after authentication abort in the Stress test (*) failures ledgered above: #112940.

That PR reapplies #110760 (reverted in #112935) together with the fix: PostgreSQLHandler::cancelRequest no longer builds a query context from the unauthenticated session, cancelling through the new ProcessList::sendCancelToQueryOfAnyUser instead. Verified at its head bfc13929ce68df79, where the signature no longer appears in CIDB while the same Stress flavours ran.

`ci/tests/test_stress_stop_server_bounded.py` can never run. The `CI Tests` job
that ran `pytest` over `ci/tests/` was removed in 8ff3720 along with
`JobConfigs.ci_tests` and the `ci_tests` lane of the generated workflow, and the
suite itself was emptied by ClickHouse#115650. Nothing in the tree invokes pytest over
`ci/` today: the only remaining `ci/tests` references are the `example_1` cache
samples in ci/praktika/cache.py, and a file landing there is deleted again
(2c10dbc). So the file was a guard that no check could turn red.

The BEGIN/END marker comments existed only so that test could extract the loop
text verbatim, so they go with it. The invariant comment stays: it is why the
`timeout` wrapper is load-bearing rather than belt-and-braces.
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 51173b2 Sep 12, 2026
175 checks passed
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-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI 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.

5 participants