Skip to content

Free leftover server ports before starting ClickHouse in stateless test setup - #109707

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:ci-flaky-check-port-teardown
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:ci-flaky-check-port-teardown

Conversation

@groeneai

@groeneai groeneai commented Jul 7, 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

Free leftover server ports before starting ClickHouse in the stateless functional-test setup, so a stale clickhouse-server/clickhouse-keeper from a previous run in the same job container cannot silently break the fresh server.

Root cause: the CI test config sets listen_try=true (tests/config/config.d/listen.xml). When a lingering server still holds 9000/8123/9181/9009, the fresh server logs each Listen ... Address already in use only as a Warning, stays alive, but never listens on the TCP port. wait_ready() then times out with Code: 210. Connection refused (localhost:9000) and the job fails at setup, before any test runs — reported as an opaque SETUP FAILURE: clickhouse-server not ready (wait_ready). This surfaced as a false-red Stateless tests (*, flaky check) verdict (the changed test never executed) and recurs across many unrelated PRs.

Fix: ClickHouseProc.start() now runs a best-effort teardown once, before starting replica 0. It checks whether 9000/8123/9181/9009 are held (ss -Hlnt 'sport = :PORT'); if so it kills any lingering clickhouse-server/clickhouse-keeper and waits (up to 45s) for the sockets to be released before launching our own process. It never raises, so a failure here cannot mask a real start error; wait_ready() still reports if the server genuinely cannot listen.

…st setup

A stale clickhouse-server/keeper from a previous run in the same job
container can still hold 9000/8123/9181/9009 when the stateless functional
test setup starts a fresh server. Because the CI config sets listen_try=true,
the fresh server logs each Listen ... Address already in use only as a Warning,
stays alive but never listens on the TCP port, so wait_ready() times out with
Code 210 and the job fails at setup before any test runs.

ClickHouseProc.start() now frees the key server ports before launching replica
0: it detects held ports with ss, kills any lingering clickhouse-server/keeper,
and waits for the sockets to be released. Best-effort and never raises, so it
cannot mask a real start failure.

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

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Locally started a leftover server holding 19200/19210/19240, then started a fresh server with the CI listen_try=true config: the fresh server logs Listen [127.0.0.1]:19200 failed ... Address already in use (as a Warning) and never reaches Ready for connections — a select 1 probe stays refused, exactly the CI wait_ready timeout (Code 210).
b Root cause explained? A stale clickhouse-server/clickhouse-keeper from a previous run in the same job container still holds 9000/8123/9181/9009. Because the CI config sets listen_try=true, the fresh server treats each port bind failure as a non-fatal Warning, stays alive, but listens on nothing → wait_ready() polls select 1 on 9000 for 60s and times out → SETUP FAILURE, before any test runs.
c Fix matches root cause? Yes. start() now frees exactly those ports (kill lingering server/keeper, wait for the sockets to release) before launching the fresh server, removing the collision that listen_try=true silently tolerates.
d Test intent preserved / new tests added? No test is weakened. This is a CI-harness setup fix; wait_ready() still fails loudly if the server genuinely cannot listen (the teardown never raises and never masks a real start error).
e Both directions demonstrated? Yes. Without teardown: fresh server logs 2× Address already in use, 0× Ready for connections, probe refused. With teardown: ports detected busy → lingering server killed → ports free within the wait loop → fresh server ready in 2 probes, 0 bind errors (wait_ready would PASS).
f Fix is general across code paths? Yes. The teardown runs once for replica 0 before any replica starts, covering the single-server, DB-replicated (replicas 1/2 use 19xxx/29xxx which the fresh replica-0 process will own after cleanup), and flaky/bugfix restart paths that all go through ClickHouseProc.start().
g Fix generalizes across inputs? N/A (CI-harness Python change, not a ClickHouse code bug).
h Backward compatible? N/A (CI-harness only; no user-visible behavior, settings, or on-disk/wire format touched).
i Invariants and contracts preserved? Yes. Best-effort and idempotent: only acts when a port is actually held, only kills clickhouse-server/clickhouse-keeper, and never raises, so it cannot change the success/failure contract of start()/wait_ready().

Session id: cron:clickhouse-worker-slot-2:20260707-191200

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv @leshikus — could you review this? It fixes a stateless flaky-check setup failure: a leftover clickhouse-server/keeper from a prior run in the same job container holds 9000/8123/9181/9009, and because the CI config sets listen_try=true the fresh server logs the bind failures only as Warnings, stays up but never listens, so wait_ready() times out (Code 210) before any test runs. start() now frees those ports (kill lingering server/keeper + wait for release) before launching.

Comment thread ci/jobs/scripts/clickhouse_proc.py Outdated
# before we launch our own (listen_try=true otherwise turns a port
# collision into a silent wait_ready timeout). Done once, before any
# of our replicas start, so it only ever targets stale processes.
self._ensure_server_ports_free([9000, 8123, 9181, 9009])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai at stress_runner.sh it also waits for server ports to be free, and there are more than those. Can you check and update this list?

Per review: reconcile the port-teardown list with the authoritative
wait_server_ports_free() in tests/docker_scripts/stress_tests.lib. A
stateless test server listens on more than the four native/http/keeper/
interserver ports, so free the full set (adds https 8443, mysql 9004,
postgres 9005, tcp-proxy 9010, ssh 9022, grpc 9100, keeper-raft 9234,
native-tls 9440, prometheus 9988) before starting.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim good catch. Reconciled the teardown list with the authoritative wait_server_ports_free() in tests/docker_scripts/stress_tests.lib. Now freeing the full stateless-server listen set (@ 2327650):

8123 8443 9000 9004 9005 9009 9010 9022 9100 9181 9234 9440 9988

= HTTP, HTTPS, native TCP, MySQL, PostgreSQL, interserver HTTP, TCP-proxy, SSH, gRPC, Keeper, Keeper-Raft, native-TLS, Prometheus. This is the same set our own replica_command_1/2 bind (tcp_port_secure/mysql/postgresql/interserver/prometheus/etc), so the teardown now covers every port a leftover server or keeper could still hold.

@leshikus

leshikus commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Duplicates wait_server_ports_free (tests/docker_scripts/stress_tests.lib:269)

@leshikus
leshikus self-requested a review July 8, 2026 13:23
Remove the duplicated port list: define CLICKHOUSE_SERVER_PORTS once in
tests/docker_scripts/stress_tests.lib and have both wait_server_ports_free()
(bash) and clickhouse_proc.py's setup teardown read it, so the two lists can
no longer drift.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@leshikus done in 321dd56. Removed the duplicated list: stress_tests.lib now defines the port set once as CLICKHOUSE_SERVER_PORTS (single source of truth); wait_server_ports_free() iterates over it, and the Python setup teardown parses that same assignment (_server_ports() in clickhouse_proc.py) instead of hard-coding a second copy. The two can no longer drift.

I kept the setup teardown as a separate function rather than calling the bash helper directly because they do different things and run in different contexts: wait_server_ports_free() only waits, and runs in the stress runner; the functional-test setup additionally kills lingering clickhouse-server/keeper from a previous stage before waiting, and runs in the praktika Python job. Sharing just the data (the port list) removes the actual duplication without coupling the two execution paths. Verified both readers return the same 13 ports.

@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [321dd56]


AI Review

Summary

This PR adds a pre-start cleanup in ClickHouseProc.start() that kills leftover clickhouse-server / clickhouse-keeper processes when the stateless test ports are still busy, and it de-duplicates the port list by parsing tests/docker_scripts/stress_tests.lib. The direction is correct, but the new guard still misses database-replicated runs because it only probes replica 0's port set before recursively starting replicas 1 and 2.

Findings

⚠️ Majors

  • [ci/jobs/scripts/clickhouse_proc.py:520] The new cleanup only checks the base CLICKHOUSE_SERVER_PORTS set from stress_tests.lib, but start(replica_num=0) immediately launches replicas 1 and 2 on the 18xxx/19xxx/28xxx/29xxx ports. If a previous run leaked only replica 1 or 2, none of the probed ports are busy, so the pkill path is skipped and the same listen_try-masked startup failure still happens when the fresh replica binds its own ports.
    Suggested fix: extend the probed port set to include the replica port families used by replica_command_1 / replica_command_2, or perform the stale-process teardown unconditionally when is_db_replicated is enabled.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: make the pre-start teardown cover leftover replica 1 / 2 processes as well, so the fix actually closes the same failure mode for database-replicated functional-test jobs.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 12, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok.

@groeneai, now does it makes sense to also remove listen_try from the CI? So the errors will be instantly visible?

Comment thread ci/jobs/scripts/clickhouse_proc.py Outdated
# collision into a silent wait_ready timeout). Done once, before any
# of our replicas start, so it only ever targets stale processes.
# Port set is single-sourced from stress_tests.lib (see _server_ports).
self._ensure_server_ports_free(self._server_ports())

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.

start(replica_num=0) later fans out into replicas 1 and 2, but this cleanup only probes the base CLICKHOUSE_SERVER_PORTS set from stress_tests.lib. If the previous run leaked only replica 1 or 2, all of the ports checked here can be free while 19000/18123/19181 or 29000/28123/29181 are still occupied by the stale process. In that case we skip the pkill entirely and hit the same listen_try-masked wait_ready() timeout when the new replica starts. The teardown needs to cover the shifted replica port sets as well (or kill stale ClickHouse processes unconditionally in replicated mode), otherwise the fix still misses database-replicated jobs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch. Fixed in fe015fa: in db-replicated mode the teardown now also probes the shifted replica-1/2 port sets, derived from the authoritative replica_command_1/2 strings (19000/18123/19181..., 29000/28123/29181...), not a second hard-coded list. A leaked replica 1/2 now triggers the pkill instead of slipping past the base-port probe.

In database-replicated mode replicas 1 and 2 bind shifted port sets
(19000/18123/19181..., 29000/28123/29181...) rather than the base
CLICKHOUSE_SERVER_PORTS. A leaked replica 1/2 leaves the base ports free,
so the teardown skipped pkill and the stale process still held the shifted
ports, recreating the listen_try-masked wait_ready timeout for replicated
jobs. Derive the shifted ports from the authoritative replica_command_1/2
strings (no second hard-coded list) and probe them too when db-replicated.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The gap is deterministic by construction: _ensure_server_ports_free probed only the base CLICKHOUSE_SERVER_PORTS, so a leaked replica-1/2 process (holding 19000/18123/19181... or 29000/28123/29181...) leaves every base port free -> pkill skipped.
b Root cause explained? In db-replicated mode replicas 1/2 bind SHIFTED port sets, not the base set. Probing only base ports means a replica-1/2-only leak reads as "all free", the pkill is skipped, the stale process keeps the shifted ports, and listen_try=true turns the collision into a silent wait_ready timeout at setup.
c Fix matches root cause? Yes. In db-replicated mode the probe set is extended with the shifted replica ports, so a leaked replica 1/2 is now detected and killed.
d Test intent preserved? N/A (CI test-harness setup change, no product test modified).
e Demonstrated both directions? Before: base-only probe misses shifted ports. After: _replica_ports() yields the full 20 shifted ports (10 per replica) and they are probed when is_db_replicated.
f Fix general, not narrow patch? Ports are derived from the authoritative replica_command_1/2 strings that actually launch the replicas - no offset magic, no second hard-coded list to drift. Single-sourcing (per @ leshikus) is preserved.
g Generalizes across inputs? N/A (CI test-setup, not a code bug).
h Backward compatible? N/A (CI harness, no user-facing behavior/format/setting).
i Invariants preserved? Best-effort/never-raises contract kept; non-replicated path unchanged; only clickhouse-server/keeper are killed.

Session id: cron:clickhouse-worker-slot-3:20260712-145000

@alexey-milovidov

Copy link
Copy Markdown
Member

This PR looks superseded by #110122 ("CI: kill leftover clickhouse server processes before the first server start"), which merged into master on 2026-07-13.

#110122 fixes the identical root cause — a leftover clickhouse-server from a previous CI job holds the listen ports, and because the test config sets listen_try=true the fresh server logs each bind failure only as a Warning, stays up but never listens, so wait_ready() times out with an opaque Connection refused (Code 210) before any test runs — at the same spot (ClickHouseProc.start(), the replica_num == 0 branch, right after dmesg --clear). It does so via a shared kill_leftover_server_processes() in ci/jobs/scripts/server_cleanup.py that every server-start entry point now calls (start, start_light, sqltest_job, sqllogic_test, sqlstorm_test, clickhouse_light, collect_clickhouse_profiles), not only the stateless functional-test setup.

As a result this branch now conflicts with master and _ensure_server_ports_free() duplicates what is already there. Two concrete reasons not to re-land it as-is:

  1. _ensure_server_ports_free() has no Info().is_local_run guard, so on a local run it would pkill -9 a developer's own clickhouse-server whenever a probed port is busy. kill_leftover_server_processes() explicitly skips local runs to avoid exactly this.
  2. In the stateless setup every server (replica 0/1/2) runs as clickhouse-server with an embedded keeper (--keeper_server.tcp_port ...); there is no standalone clickhouse-keeper process in this path, so the extra pkill clickhouse-keeper matches nothing that killing clickhouse-server does not already cover.

Given that, I'd recommend closing this as superseded by #110122. If any incremental piece is still worth keeping — e.g. single-sourcing the port list via CLICKHOUSE_SERVER_PORTS in stress_tests.lib, or waiting on the actual sockets to be released rather than on process exit — it would be cleaner to add it directly on top of kill_leftover_server_processes() in a small follow-up. Leaving the keep-vs-close decision to @groeneai / @alexey-milovidov since this was already approved.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, closing as superseded by #110122.

Confirmed it covers the same root cause more generally: pattern-killing clickhouse[- ]server matches replicas 0/1/2 alike (so no shifted-port probing needed), the is_local_run guard avoids killing a developer's own server, and it's called from every server-start entry point rather than just the stateless setup. Both gaps you noted are handled there, and this branch now conflicts with master.

No incremental follow-up needed for now: the single-sourced CLICKHOUSE_SERVER_PORTS in stress_tests.lib stays as a small cleanup for wait_server_ports_free, and waiting on actual socket release vs process exit is a minor refinement that can go directly on top of kill_leftover_server_processes() if it ever proves necessary.

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 manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants