Skip to content

clickhouse-test: identify the server process from argv, not from a substring of the whole command line - #112269

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-hung-check-false-positive
Aug 4, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-hung-check-false-positive

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111693

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):

clickhouse-test identified the ClickHouse server process by substring-matching the whole ps command line against clickhouse-server, which also matched the /bin/sh -c "clickhouse-server ..." wrapper CI interposes (the server is started with shell=True). Being the parent, that shell was picked deterministically. As a result the lldb dump collected from the hung-check path labelled a dash as the "main server" (and labelled the real server "replica"), and the memory-pressure worker shed compared the shell's ~2 MiB RSS against the server's multi-GB max_server_memory_usage, so the shed could never trigger. The server is now identified from argv instead.

Description

What this is not

This came out of investigating the Hung check failed: server is not responding aborts on
Stateless tests. I want to be explicit that the hung check itself is not changed here, and I no
longer believe it is a false positive.
I started from that hypothesis and measured it to be wrong,
over the 14 errored Stateless tests (amd_tsan, parallel) job logs:

  • the probe genuinely exhausts all 10 attempts. The gap between the verdict and the previous log
    line is bimodal, 165-166 s or 63-69 s, which is exactly its own budget
    (10 x 10 s socket timeout plus sum(min(2**a, 10) for a in 0..8) = 65 s of backoff);
  • in 14/14 runs, zero log lines fall strictly inside the probe window and the shared progress
    index advances by exactly +1, against a per-run baseline of p50 0 s / p95 1 s / max 3-8 s over
    ~8000 test completions. A 65-166 s window with no completions is 20-50x the largest gap ever
    observed in that same run;
  • the "tests pass after the verdict" observation is recovery, not concurrency: the first
    post-verdict [ OK ] is 9-171 s later, after the lldb apt-get install has finished.

So making the check tolerant would suppress a true signal. The probe's scheduling (it sits
directly in the while processes: sleep(0.1) loop with no interval gate, unlike
MEMORY_CHECK_INTERVAL just above it) is a separate concern and will be a separate PR. The
underlying stalls are server-side and out of scope here.

What the investigation did turn up is a mechanical bug in the harness on that same path.

The bug

get_all_server_pids and get_server_pid both used pgrep(command="clickhouse-server"), and
pgrep filters with command in p[3] - a substring match against the whole ps command
column. CI starts the server with subprocess.Popen(<command string>, shell=True)
(ci/jobs/scripts/clickhouse_proc.py), so the interposed /bin/sh -c "clickhouse-server ..."
wrapper necessarily contains that substring and matched too. get_server_pid returned the first
match and ps output is pid-ascending, so the parent shell was selected - deterministically, not
racily.

Observed verbatim in the Stateless tests (amd_tsan, parallel) report for
#111693
:

Collecting C stacktraces from main server process 699 with lldb:
  Process 699 stopped / Executable module set to "/usr/bin/dash".
  frame #1..#9  dash`___lldb_unnamed_symbol... / libc.so.6`__libc_start_call_main
Collecting C stacktraces from replica process 701 with lldb:
Collecting C stacktraces from replica process 702 with lldb:

701 is the real server (the watchdog parent) and 702 its serving child, so there was no main server in the dump at all. That is not only cosmetic: it is what led me and previous
investigations to believe the main server was hung in a shell wait4, and it spends part of the
per-abort lldb budget on a dash.

The same pid is also the sole input to the memory-pressure worker shed, via
get_server_memory_fraction -> /proc/<pid>/statm. Reading the shell's RSS against the
server's max_server_memory_usage yields a fraction three orders of magnitude below
MEMORY_PRESSURE_THRESHOLD = 0.8, so the shed has never been able to fire in CI. That is
corroborated by its own log lines appearing 0 times across all 14 runs (~90 000 test completions).

The fix

One predicate, _is_server_cmdline, consumed by both helpers so they can no longer disagree:
argv[0] is clickhouse-server, or argv[0] is clickhouse (or the basename of --binary) with a
server / --server selector. get_server_pid now delegates to get_all_server_pids.

Deliberately narrower than the dispatcher: isClickhouseApp (programs/main.cpp) accepts the
selector bare or ---prefixed but never inspects argv[0], so matching it literally would accept
podman server .... Requiring argv[0] to be clickhouse or the configured binary covers every
invocation the harness can produce, including "${CLICKHOUSE_BINARY} server" from
tests/queries/shell_config.sh, without matching foreign processes.

get_all_server_pids then has to exclude the watchdog, which can present a server argv: it
renames argv[0] to clickhouse-watchdog, but memcpy truncates that to the original argv[0] length
and the memset touches only argv[0], so a bare clickhouse argv[0] renames to exactly
clickhouse while argv[1] (server) survives. Reproduced locally - the watchdog parent and its
serving child then have byte-identical command lines:

pid=3147706 ppid=3147671 comm=ClickHouseWatch  clickhouse server --config-file=...
pid=3147839 ppid=3147706 comm=clickhouse       clickhouse server --config-file=...

Two tests, because neither alone is enough:

  • it parents another match. Not "the lowest pid": two sibling replicas share a ppid and both
    must survive.
  • its comm is ClickHouseWatch (setThreadName(ThreadName::CLICKHOUSE_WATCH), applied to the
    parent right after the fork). Needed because the first test only holds while the child is alive:
    after waitpid returns, the parent still logs before _exit, and that is precisely when the
    abort-path diagnostics run. With the child gone, the pid rule alone returns the watchdog as the
    server
    .

comm is inherited across fork, so it is only a tie-breaker: if it would leave nothing at all the
matches are kept, because reporting no server makes print_c_stacktraces claim the server crashed.
An unreadable /proc/<pid>/comm (the process exited between the ps scan and the read) is not
watchdog evidence.

This is reachable on today's lanes, not only in theory: the server is launched with shell=True,
and tests/queries/shell_config.sh falls back to "${CLICKHOUSE_BINARY} server" when no
-server binary exists, which is the ambiguous shape above.

Behaviour change to be aware of

Fixing the pid makes a mechanism that has never fired able to fire: the worker shed will now see
real server memory on saturated lanes. That is the intent of the existing code, and its safeguards
(the 0.8 threshold, the 30 s cooldown, and never draining below one worker) are pre-existing and
unchanged - but it is a real change in behaviour, not a pure no-op bug fix. The shed's constants are
deliberately not retuned in this PR.

Verification

The CI symptom needs a multi-minute server stall under 19-way load on an instrumented build and is
not locally reproducible; the defect itself is deterministic and was reproduced directly. I
launched a server through the identical Popen(<string>, shell=True) shape CI uses and called both
helpers, on master and with this change, against the same live process tree:

get_server_pid argv of that pid get_server_memory_fraction
master 2418214 /bin/sh -c : && clang++ ... -I.../clickhouse-server/... (1.9 MiB) 0.000196
this PR a serving process .../programs/clickhouse server --config-file ... (862.8 MiB) 0.0903

Note what master picked: not the server's launcher shell but an unrelated compile step, whose command
line merely contains clickhouse-server inside an include path. Any process on the machine can win
that match.

The orphaned-watchdog case was reproduced the same way: with the watchdog frozen so it cannot reach
its _exit, killing the serving child leaves the pid rule alone returning the watchdog and the
comm test rejecting it.

Tests (ci/tests/test_print_stacktraces.py, run by the CI Tests job): 22 predicate cases pinning
both directions - 8 accepted spellings including absolute paths, both selectors and a custom
--binary, and 14 rejected ones including shell wrappers, the renamed watchdog, other multicall
tools (local, client, chl), a foreign argv[0] with a server subcommand, a bare argv[0] with
no selector, and an empty cmdline - plus 10 process-graph shapes (both watchdog forms, an orphaned
watchdog, a watchdog-less server, the fail-safe, an unreadable comm, and a restart iteration where
the child inherits the watchdog comm so only the pid rule resolves it), a
get_server_pid == get_all_server_pids[0] consistency case, a print_c_stacktraces case whose
process table changes between calls, two comm-helper cases, a live-server case, and a shed-RSS
case. All 38 fail on master and pass here. I also checked each one is non-vacuous by mutating the
predicate, the graph filter, the comm read and the caller 18 ways; every mutant is caught,
including reintroducing the substring prefilter and dropping either watchdog test.

No src/ or programs/ change, so no changelog-visible behaviour and no SettingsChangesHistory
entry. The hung-check verdict string is untouched, so the CIDB signature and
functional_tests_results.py parsing are unaffected.

Merge order

PR #106385 edits the same two regions of tests/clickhouse-test (it adds get_server_pid_by_port
next to get_server_pid, and changes the pid line in get_server_memory_fraction), so a textual
conflict is likely depending on merge order. The two are complementary rather than overlapping: that
one selects which of several servers by port, and still falls back to get_server_pid - which,
on master, is the shell. Its own comment notes port resolution is unavailable on non-Linux, where
that fallback is the only path.

Version info

  • Merged into: 26.8.1.748 (included in 26.8 and later)

groeneai and others added 2 commits July 27, 2026 21:33
get_all_server_pids() and get_server_pid() located the server with
pgrep(command="clickhouse-server"), and pgrep filters with
`command in p[3]` - a substring match against the whole ps command
column. CI starts the server with subprocess.Popen(<string>, shell=True)
(ci/jobs/scripts/clickhouse_proc.py), so the interposed
/bin/sh -c "clickhouse-server ..." wrapper contains the same substring
and matched as well. get_server_pid() returned the first match and ps
output is pid-ascending, so the parent shell was selected every time.

Two consumers read that pid. print_c_stacktraces labelled the shell
"main server" and collected its nine-frame dash backtrace while the real
server was labelled "replica", which is what led several
investigations to believe the main server was hung in a shell wait4.
get_server_memory_fraction read the shell's /proc/<pid>/statm RSS
against the server's max_server_memory_usage, so the fraction driving
the memory-pressure worker shed was three orders of magnitude below
MEMORY_PRESSURE_THRESHOLD and the shed could never fire; its log lines
appear zero times across 14 errored job logs (~90000 test completions).

Identify the server from argv instead, in one predicate consumed by both
helpers so they can no longer disagree: argv[0] is clickhouse-server, or
argv[0] is clickhouse (or the basename of --binary) with a server or
--server selector. This is deliberately narrower than isClickhouseApp
(programs/main.cpp), which never inspects argv[0] and would therefore
accept any tool with a server subcommand. get_server_pid now delegates
to get_all_server_pids.

get_all_server_pids also drops a match that parents another match. The
watchdog renames argv[0] to clickhouse-watchdog, but the memcpy is
truncated to the original argv[0] length and the memset touches only
argv[0], so a bare clickhouse argv[0] renames to exactly clickhouse
while argv[1] survives, leaving the watchdog parent indistinguishable
from its serving child by argv alone. Today's CI lane launches
clickhouse-server and renames to a distinct clickhouse-watchd, so this
part affects the bare multicall and custom --binary launches; it is a
no-op when the rename is distinct or no watchdog exists. It is
expressed as "parents another match" rather than "the lowest pid"
because two sibling replicas share a ppid and both must survive.

Note this makes a previously dead mechanism able to fire: the worker
shed will now see real server memory on saturated lanes. Its
constants are not retuned here.

The hung-check verdict, its text and check_server_liveness are
deliberately untouched. The probe window in those 14 runs matches its
own 10x10s + 65s budget exactly and contains zero test completions
against a per-run baseline whose largest gap is 3-8s, so the verdict is
true and tolerating it would suppress a real signal.

Co-Authored-By: Claude Opus 5 <[email protected]>
…e snapshot

Review round 1 on top of the argv-based server identification.

Rejecting the watchdog by "parents another match" alone keys the decision on
live child membership, so once the serving child is reaped the watchdog is
returned as the server. That window is not incidental: after waitpid returns,
the watchdog still logs before _exit, which is exactly when the abort-path
diagnostics run. Reproduced by launching a server whose argv0 resolves to
"clickhouse", so BaseDaemon's rename to "clickhouse-watchdog" truncates to
len(argv0) and parent and child carry byte-identical command lines; freezing
the parent and killing the child then makes the pid rule alone return the
non-serving process.

Add a second, independent test on /proc/<pid>/comm, which BaseDaemon sets to
ClickHouseWatch on the parent. Both clauses are load-bearing: sibling replicas
share a ppid so the pid rule cannot be "drop the lowest", and comm is inherited
across fork (BaseDaemon forks before it renames), so on a watchdog restart the
serving child would inherit it. The comm test therefore only breaks ties, and
if it would empty the list the matches are kept, because reporting no server
makes the collector claim the server crashed. The comm read cannot raise: it
runs on the abort path, where an exception would replace the diagnostics it
exists to collect.

print_c_stacktraces also took two independent ps snapshots, one for the label
pid and one for the dump list. On a changing process table those disagree and
no pid gets the "main server" label, which is the same user-visible symptom the
previous commit fixes, from a different cause. Derive both from one snapshot.

18 mutants, each killed by a named case. Two survived first and were closed
rather than argued away: dropping the pid clause (no case covered the inherited
comm) and, in the previous round, the substring prefilter (the fake pgrep
ignored its filter kwargs).
@groeneai

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

Pre-publication review by an independent model (engine: codex; 3 rounds, 8 findings total;
uncapped fix rounds -- this PR went through one full fix round before publication).

# Sev Finding Verdict Evidence / action
1 ⚠️ get_all_server_pids rejected the watchdog only while it currently parents another match, so once the serving child is reaped a bare-multicall watchdog is returned as the server (tests/clickhouse-test, get_all_server_pids) AGREE -- fixed @ d8baa3744ab4 Reproduced live before fixing: with the watchdog frozen so it cannot reach its post-waitpid _exit and the serving child killed, the pid rule alone returned the non-serving watchdog. A second, independent test on /proc/<pid>/comm (ClickHouseWatch, set at BaseDaemon.cpp:639) is now layered on the pid rule, with a fail-safe so the list can never go empty. Both clauses proven load-bearing by mutation.
2 ⚠️ print_c_stacktraces took two independent ps snapshots (one via get_server_pid, one via get_all_server_pids), so on a changing process table no pid gets the main server label -- the same user-visible symptom this PR fixes, from a different cause AGREE -- fixed @ d8baa3744ab4 Both values now derive from one snapshot. New test drives a pgrep whose table changes between calls and asserts exactly one main server; reverting to two calls fails it.
3 ⚠️ The PR body carried no visible issue link and no CI report URL (the Related: line was inside the non-rendering HTML comment) AGREE -- fixed Visible full-URL Related: line plus the canonical report URL for the run the quoted lldb excerpt comes from.
4 💡 _process_comm decodes /proc/<pid>/comm with strict UTF-8 but catches only OSError, so invalid UTF-8 raises UnicodeDecodeError despite the helper's "never raises" contract (tests/clickhouse-test, _process_comm) AGREE -- noted, not blocking Real, and found independently by both reviewers. Not fixed here because it is unreachable in practice: the process must carry non-UTF-8 bytes in comm and already pass _is_server_cmdline, whose accepted argv[0] basenames are all ASCII, and every ClickHouse comm comes from an ASCII literal table. Remedy if wanted: errors="replace" (or also catch UnicodeError) plus a malformed-bytes case.
5 💡 A stale countable claim in the body ("20 predicate cases") AGREE -- fixed All counts re-derived by script (22 predicate cases = 8 accepted / 14 rejected, 10 graph shapes, 38 new tests, 18 mutants).
6 💡 Two em-dashes on added comment lines AGREE -- fixed @ d8baa3744ab4 Replaced with ASCII. The one remaining occurrence is pre-existing text, only re-indented.
7 💡 An issue-link spelling that did not match the template's full-URL form AGREE -- fixed Rewritten; the body was then re-reviewed rather than published with content the review had not seen.
8 💡 Four f()-style function references in prose AGREE -- fixed Normalised.

Severity: ❌ blocker / ⚠️ major / 💡 nit. No blockers were found in the code. DISAGREE verdicts
carry recorded evidence and are terminal per finding; there were none in this review.

Session id: cron:clickhouse-review-slot-54:20260728-104502

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A server launched through the identical subprocess.Popen(<command string>, shell=True) shape CI uses makes get_server_pid() return the /bin/sh wrapper on every call: the shell is the parent and ps output is pid-ascending, so the selection is deterministic, not racy. The CI symptom (a multi-minute stall under 19-way load on an instrumented build) is not locally reproducible and is a separate, server-side concern.
b Root cause explained? Yes. pgrep filters with command in p[3], a substring match against the whole ps command column, so the shell=True wrapper whose command line contains clickhouse-server also matched; get_server_pid() returned the first (lowest-pid, i.e. parent shell) match; both consumers then read a shell's pid, giving the main server mislabel in the lldb dump and a shell's RSS as the memory-pressure input.
c Fix matches root cause? Yes. The server is identified from argv in the helper whose docstring already promised to find it, rather than from a substring of the whole command line. No assertion widened, no check disabled, no timeout raised. Notably this is not the "make the hung check tolerant" change the symptom first suggested: measurement showed the hung-check verdict is true in both observed failure bands, so tolerating it would suppress a real signal.
d Test intent preserved / new tests added? Yes. No existing test weakened, relaxed or removed; the pre-existing live-server stacktrace test still passes unchanged (it passed before with the mislabel, since the shell was what got labelled main server). 38 new cases added in ci/tests/test_print_stacktraces.py, covering the predicate, the process graph (including an orphaned watchdog, a watchdog-less server and a restart iteration with an inherited short name), the comm helper, a process table that changes between calls, a live server, and the memory-pressure input.
e Both directions demonstrated? Yes, three ways. Behaviourally, against one live process tree: master selects a /bin/sh -c wrapper (1.9 MiB RSS, get_server_memory_fraction = 0.000196) while the change selects a real serving process (862.8 MiB, 0.0903). For the watchdog rule specifically: with the watchdog frozen so it cannot exit and its serving child killed, the pid rule alone returns the non-serving watchdog and the short-name test rejects it. At test level all 38 new cases fail on pristine origin/master and pass here, with the pre-existing failing set identical on both sides. The measuring binary was Build-ID-verified (SELECT buildId() matched the ELF note).
f Fix is general across code paths? Yes. Fixed once in the two shared helpers rather than at either call site, and get_server_pid now delegates to get_all_server_pids so the two can no longer disagree (that divergence was exactly what produced the main server/replica mislabel). A repo-wide grep confirms all four consumer sites are covered and no other consumer exists. The stacktrace collector now derives both the label pid and the dump list from a single process-table snapshot, so they cannot disagree in time either. pgrep itself is deliberately untouched: it is a generic ps wrapper with unrelated ppid=/pgid= callers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, pinned in both directions. Accepted: clickhouse-server bare and absolute-path, clickhouse server and clickhouse --server bare and absolute-path, and both selectors under a custom --binary basename. Rejected: dash/sh/bash wrappers, the renamed clickhouse-watchdog, other multicall entry points (local, --local, client, the chl alias), a server subcommand under a foreign argv[0], an accepted argv[0] with no selector at all, and an empty command line. Plus 10 process-graph shapes: the CI tree, the truncated-rename tree where parent and child present identical argv, a lone server with a child, two sibling replicas sharing a ppid, a server whose own command line does not contain clickhouse-server, an orphaned watchdog whose child is already gone, a watchdog-less server with no children at all, an orphaned watchdog as the only match (which must still be reported), an unreadable short name, and a restart iteration where the serving child inherits the watchdog's short name.
h Backward compatible? (maintainer-approved exception only) Yes, and nothing is at risk: test-harness helpers only. No setting, no SettingsChangesHistory entry (that file tracks Settings), no serialization or wire format, no src/ or programs/ change. The hung-check verdict string is unchanged, so CIDB signatures and functional_tests_results.py parsing are unaffected. Both helpers gained a positional args; all in-tree callers are updated and getattr(args, "binary", "clickhouse") keeps the minimal spawn-worker namespace working, which is the scenario that test module exists to reproduce.
i Invariants and contracts preserved? Yes. The invariant is "every pid reported as a server is a server", which was previously violated. get_all_server_pids still returns the whole remaining server family so all replicas are still dumped; the watchdog rule drops only a match that parents another match (never "the lowest pid": two sibling replicas share a ppid and both must survive) or that carries the watchdog's short name while another match survives, and is a no-op when the rename is distinct or no watchdog exists. Two contracts have their own cases: the returned list never goes empty because of the short-name test, since reporting no server would make the collector claim the server crashed; and the short-name read never raises on a pid that has already exited, because it runs on the abort path where an exception would replace the diagnostics it exists to collect. get_server_pid still returns None when nothing matches, which is the contract the empty-pid-list branch and the pid is None branch both depend on. No new failure path: a short or empty command line cannot raise, and that guard is pinned by its own cases.

Session id: cron:clickhouse-impl-slot-46:20260728-095600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv — could you review this? clickhouse-test identified the server process by substring-matching the whole ps command line against clickhouse-server, so the shell=True launcher wrapper (and even an unrelated compile step with that string in an include path) won deterministically; the lldb dump then labelled a dash as the "main server" and the memory-pressure shed read a shell's RSS. It is now identified from argv, with the watchdog excluded. Same abort-path diagnostics family as #108582.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [489d07f]

Summary: ✅


AI Review

Summary

This PR fixes the immediate Linux shell=True false positives by switching clickhouse-test's server lookup to argv-based matching, adds the watchdog filters needed for restart/orphan shapes, and refreshes the cached PID when RSS reads stop working. The core CI mislabel / memory-shed bug is addressed, but I still see one live correctness gap in multi-server custom---binary setups, and the focused selector/watchdog regression coverage that would pin this logic was removed.

Findings

⚠️ Majors

  • [tests/clickhouse-test:1148] [dismissed by author -- https://github.com/clickhouse-test: identify the server process from argv, not from a substring of the whole command line #112269#discussion_r3665478832] _is_server_cmdline still accepts any plain clickhouse-server even when args.binary points at a custom build, so on a host with another ClickHouse instance get_server_pid / get_server_memory_fraction can still bind to the foreign lower-pid server instead of the one under test. I re-ran the current helper with args.binary=/opt/ch/ch and mocked rows for /usr/bin/clickhouse-server ... and /opt/ch/ch-server ...; it returned [100, 200] and chose 100 as the main server. Suggested fix: resolve the server by connection identity (for example by port, or by /proc/<pid>/exe plus the expected binary prefix) rather than by a name-only predicate.
  • [ci/tests/test_print_stacktraces.py:75] [dismissed by author -- https://github.com/clickhouse-test: identify the server process from argv, not from a substring of the whole command line #112269#discussion_r3691913432] The checked-in tests no longer exercise _is_server_cmdline, watchdog filtering, or mocked ps / /proc tables, so they stay green if the selector regresses back to the shell=True wrapper match or if the orphaned-watchdog / restart tie-breakers break. I still consider this real because the current file has zero references to _is_server_cmdline, WATCHDOG_COMM, or get_all_server_pids outside the live smoke path. Suggested fix: restore a small mocked-process-table test layer for the wrapper, orphaned-watchdog, restart-with-inherited-comm, and custom -server cases.
Final Verdict

Changes requested: the Linux false-positive fix is good, but the PID selector still is not scoped to the actual server under test in multi-server custom-binary environments, and the subtle selector/watchdog logic is no longer pinned by focused tests.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 28, 2026
Comment thread tests/clickhouse-test Outdated
Comment on lines +1150 to +1153
argv0 = os.path.basename(parts[0])
if argv0 == "clickhouse-server":
return True
if argv0 not in ("clickhouse", os.path.basename(binary)):

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.

This still doesn't scope matching to args.binary when the test runs a custom build. _is_server_cmdline("/usr/bin/clickhouse-server ...", "/opt/ch-build") and _is_server_cmdline("clickhouse server ...", "/opt/ch-build") both return True, so on a machine with another ClickHouse instance under the same user get_server_pid can still bind to that lower-pid foreign server and feed the wrong PID into the lldb / RSS code paths.

Could we keep the generic clickhouse / clickhouse-server aliases only for the default binary, and otherwise disambiguate by the configured path (or /proc/<pid>/exe on Linux)? Without that, the new predicate narrows the false positives from arbitrary commands to arbitrary ClickHouse servers, but it still doesn't identify the server under test.

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.

You are right on the mechanism, and your two examples are correct: I confirmed both return True.

Where I disagree is the remedy. I measured it, and scoping to basename(args.binary) does not
actually separate the two. This host runs many worktrees concurrently, each with its own
build/programs/clickhouse, so it is exactly the "another ClickHouse instance under the same user"
case you describe. Against its live process table, with --binary pointing at my own build:

processes accepted
the predicate as shipped 13, all foreign
your proposal (generic aliases only for the default binary) 13, unchanged
/proc/<pid>/exe prefix match against args.binary 0

The middle row is the problem: every one of those builds is itself named clickhouse, so the
basename is byte-identical for the server under test and for all thirteen foreign ones. The
proposal also rejects three server shapes the harness really produces -
/usr/bin/clickhouse-server ..., /build/programs/clickhouse server ..., and bare
clickhouse-server ... - so as stated it would trade this gap for a regression.

The deeper reason is that --binary is not a handle on the server at all. clickhouse-test never
starts a server; it connects over HTTP (args.tcp_host / args.http_port). --binary is a
client-side path, consumed only for CLICKHOUSE_BINARY, args.client and extract-from-config,
while the server is started separately by ci/jobs/scripts/clickhouse_proc.py as
clickhouse-server --config-file .... The two are decoupled by design, and in a packaged container
they are genuinely different files: /usr/bin/clickhouse-server ships as its own file
(packages/clickhouse-server.yaml, type: file, unlike the clickhouse-keeper* entries just below
it which are symlinks) whereas /usr/bin/clickhouse comes from clickhouse-common-static. So a
strict exe == args.binary test would reject the real CI server.

/proc/<pid>/exe is the right instrument, as you suggest, but it has to be a prefix comparison: once
a binary is rebuilt under a running server the link reads <path> (deleted), and an exact match then
silently skips exactly the process you were looking for. It measured 0/13 on foreign trees and 5/5 on
each server's own tree.

I would rather not fold this into this PR. This one closes a defect that is live on CI today: the
shell=True launcher wrapper, and even an unrelated compile step with clickhouse-server inside an
include path, won the old substring match deterministically. Identifying which of several servers
is under test is a different failure mode, it is not reachable on the current lanes (no CI job passes
--binary, and the extra servers in a CI container are the replicas the helper is meant to return),
and the sound fix is connection identity rather than a name - which is already implemented in #106385
as get_server_pid_by_port, in the same two regions of this file. Doing it here would mean either
duplicating that or pre-resolving a conflict with it.

I have filed it as a follow-up with the measurements above, the (deleted) caveat, and the
constraint that the packaged clickhouse-server shape must keep matching. One thing I will pick up
there as well, found while checking your case: shell_config.sh prefers
"${CLICKHOUSE_BINARY}-server" when it exists, and the predicate rejects that today - a real server
under test that is currently missed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d8baa37

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
(none) 174 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260728-183000

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai remove the test

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 31, 2026
@PedroTadim
PedroTadim enabled auto-merge July 31, 2026 16:04
Comment thread tests/clickhouse-test Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Accepted, and sorry I made you do it yourself. 0de5293 drops the 8 mocked-ps test functions (38 executable cases) and keeps the 4 live-server ones; the file compiles clean and nothing references the removed helpers. I will not re-add them.

One call for you: 36 minutes after your commit the review bot asked for that coverage back, on the grounds that the selector fix is now unpinned. It is right on the fact. I checked, and with the mocked tables gone a regression to the old substring rule leaves the remaining smoke test green, so nothing would fail. I am leaving it removed unless you say otherwise.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0de5293

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 (arm_binary, parallel) / 04612_join_runtime_filters_index_analysis_multi_key_anti randomized-settings result diff; the runner confirms it (143/143 reruns fail with the same settings, 207/207 pass without randomization) and names join_runtime_filter_min_probe_rows as the culprit #111691 (external, merged) - this build predates it
Fast test (arm_darwin) / (job-level, no test row) job wedged: the Run step was still in_progress when the job was recorded failed at 29.5 min, the fast test itself reported success, and no artifact or CIDB row was produced #112267 (external, merged) - this build predates it

Not PR-caused: this PR only changes tests/clickhouse-test server-process identification, which cannot
affect either an index-analysis result or the Darwin job harness.

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

Comment thread tests/clickhouse-test Resolved
Comment thread tests/clickhouse-test Resolved
Two defects in the new server selector, both found by review of this PR.

1. `_is_server_cmdline` rejected one of the two launch shapes the harness
itself supports for a custom `--binary`. `find_clickhouse_command` and
tests/queries/shell_config.sh both prefer `${BINARY}-server` when that
executable exists, so with `--binary /opt/ch/ch` the real server under test
(`/opt/ch/ch-server ...`) was not a match, and `get_all_server_pids` could
fall back to an unrelated `clickhouse`-named process or to no server at all.
Now `basename(binary) + "-server"` is accepted alongside `clickhouse-server`.

2. The `WATCHDOG_COMM` tie-breaker was applied to every survivor, so it could
drop a real server as soon as some other replica had a normal short name.
comm is set on the watchdog but inherited across fork, so a server restarted
by its own watchdog carries `ClickHouseWatch` while being the process that
serves; with survivors [101, 201] and comm(101) == "ClickHouseWatch" the
restarted replica was silently skipped exactly on the abort path. The comm
test now only decides for a survivor that no other match parents, which is
the only case where comm is evidence of a childless watchdog rather than of
inheritance. The same scoping also fixes the mirror-image over-fire: an
orphaned watchdog whose child died is now dropped even when a sibling
replica's live child also inherited the watchdog comm, where the old
whole-set rule kept both.

Verified against mocked `ps` and `/proc/<pid>/comm` tables: 26 assertions
pass with the change and 4 of them fail without it, covering the restarted
replica, the orphaned watchdog beside a healthy replica, the single-tree
healthy and post-restart shapes, the empty-result fail-safe, sibling
replicas, the packaged argv0 whose watchdog renames out of the match set,
the original shell-wrapper defect, and the custom-binary symlink shape.
auto-merge was automatically disabled August 2, 2026 15:17

Head branch was pushed to by a user without write access

Comment thread tests/clickhouse-test Resolved
…reading

get_server_memory_fraction resolved the server pid on its first call and then
treated it as immutable for the whole run. Two shapes broke it permanently:

- A watchdog restart replaces the server process. The selector above already
  handles that case (a restarted server serves while carrying the inherited
  ClickHouseWatch comm), but this consumer kept probing the dead pid's
  /proc/<pid>/statm, returned None from then on, and the worker-shed path under
  memory pressure stayed disabled for the rest of the run.
- The first call can land before the server is up, when get_server_pid returns
  None. The cache was keyed on hasattr, so None was cached just as eagerly and
  never re-resolved, disabling worker-shed even though the server came up
  moments later.

The pid is now a hint: read the RSS through the cached pid, and on any failure
re-resolve once and retry. Steady state still resolves the pid once, so the
cache keeps doing the job it was added for.

Verified with a mocked harness driving both shapes against real short-lived
processes: 3 of 7 assertions fail before this change (restart unrecoverable,
shed permanently disabled, racing first lookup never recovers) and all 7 pass
after, including a control asserting the pid is resolved once per five reads.

Reported by the automated reviewer on ClickHouse#112269.
The watchdog tie-breaker rescued a restarted server only when its parent was
itself in the match set. In the real restart sequence the parent is not: on
restart the watchdog restores the server argv (BaseDaemon.cpp:764), forks, then
renames itself to `clickhouse-watchdog` and sets comm to ClickHouseWatch
(:639-645). By the time the process table is sampled the parent presents a
watchdog argv, which the selector correctly rejects, so the child was an
unparented survivor carrying the inherited ClickHouseWatch comm and got
filtered out. With a second replica present the fail-safe did not restore it,
so print_c_stacktraces silently skipped the restarted server on the abort path.

Test the parent's comm as well, which is what actually identifies a watchdog
once it has renamed itself. This also stops an orphaned watchdog from being
kept alongside a replica whose live child inherited the same comm.

Verified against process-table shapes derived from BaseDaemon's fork/rename
sequence: 2 of 11 cases fail before this change (restarted server plus healthy
sibling; orphaned watchdog beside an inherited-comm child) and all 11 pass
after, including the shapes the comm test must keep rejecting.

Reported by the automated reviewer on ClickHouse#112269.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 489d07f

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
(none) 175 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260803-180000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit e818ad5 Aug 4, 2026
181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 2026
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 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.

4 participants