Repository navigation
clickhouse-test: identify the server process from argv, not from a substring of the whole command line - #112269
Conversation
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).
Internal second-model review -- adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds, 8 findings total;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-54:20260728-104502 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260728-095600 |
|
cc @maxknv — could you review this? |
|
Workflow [PR], commit [489d07f] Summary: ✅ AI ReviewSummaryThis PR fixes the immediate Linux Findings
Final VerdictChanges 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. |
| argv0 = os.path.basename(parts[0]) | ||
| if argv0 == "clickhouse-server": | ||
| return True | ||
| if argv0 not in ("clickhouse", os.path.basename(binary)): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger — d8baa37Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260728-183000 |
|
@groeneai remove the test |
|
Accepted, and sorry I made you do it yourself. 0de5293 drops the 8 mocked- 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. |
CI finish ledger - 0de5293Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused: this PR only changes Session id: cron:our-pr-ci-monitor:20260801-043000 |
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.
Head branch was pushed to by a user without write access
…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.
CI finish ledger - 489d07fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260803-180000 |
Related: #111693
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
clickhouse-testidentified the ClickHouse server process by substring-matching the wholepscommand line againstclickhouse-server, which also matched the/bin/sh -c "clickhouse-server ..."wrapper CI interposes (the server is started withshell=True). Being the parent, that shell was picked deterministically. As a result the lldb dump collected from the hung-check path labelled adashas 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-GBmax_server_memory_usage, so the shed could never trigger. The server is now identified fromargvinstead.Description
What this is not
This came out of investigating the
Hung check failed: server is not respondingaborts onStateless tests. I want to be explicit that the hung check itself is not changed here, and I nolonger 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:line is bimodal, 165-166 s or 63-69 s, which is exactly its own budget
(
10 x 10 ssocket timeout plussum(min(2**a, 10) for a in 0..8) = 65 sof backoff);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;
post-verdict
[ OK ]is 9-171 s later, after the lldbapt-get installhas 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, unlikeMEMORY_CHECK_INTERVALjust above it) is a separate concern and will be a separate PR. Theunderlying 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_pidsandget_server_pidboth usedpgrep(command="clickhouse-server"), andpgrepfilters withcommand in p[3]- a substring match against the wholepscommandcolumn. 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_pidreturned the firstmatch and
psoutput is pid-ascending, so the parent shell was selected - deterministically, notracily.
Observed verbatim in the
Stateless tests (amd_tsan, parallel)report for#111693:
701 is the real server (the watchdog parent) and 702 its serving child, so there was no
main serverin the dump at all. That is not only cosmetic: it is what led me and previousinvestigations to believe the main server was hung in a shell
wait4, and it spends part of theper-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 theserver's
max_server_memory_usageyields a fraction three orders of magnitude belowMEMORY_PRESSURE_THRESHOLD = 0.8, so the shed has never been able to fire in CI. That iscorroborated 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] isclickhouse(or the basename of--binary) with aserver/--serverselector.get_server_pidnow delegates toget_all_server_pids.Deliberately narrower than the dispatcher:
isClickhouseApp(programs/main.cpp) accepts theselector bare or
---prefixed but never inspects argv[0], so matching it literally would acceptpodman server .... Requiring argv[0] to beclickhouseor the configured binary covers everyinvocation the harness can produce, including
"${CLICKHOUSE_BINARY} server"fromtests/queries/shell_config.sh, without matching foreign processes.get_all_server_pidsthen has to exclude the watchdog, which can present a server argv: itrenames argv[0] to
clickhouse-watchdog, butmemcpytruncates that to the original argv[0] lengthand the
memsettouches only argv[0], so a bareclickhouseargv[0] renames to exactlyclickhousewhileargv[1](server) survives. Reproduced locally - the watchdog parent and itsserving child then have byte-identical command lines:
Two tests, because neither alone is enough:
must survive.
commisClickHouseWatch(setThreadName(ThreadName::CLICKHOUSE_WATCH), applied to theparent right after the fork). Needed because the first test only holds while the child is alive:
after
waitpidreturns, the parent still logs before_exit, and that is precisely when theabort-path diagnostics run. With the child gone, the pid rule alone returns the watchdog as the
server.
commis inherited acrossfork, so it is only a tie-breaker: if it would leave nothing at all thematches are kept, because reporting no server makes
print_c_stacktracesclaim the server crashed.An unreadable
/proc/<pid>/comm(the process exited between thepsscan and the read) is notwatchdog evidence.
This is reachable on today's lanes, not only in theory: the server is launched with
shell=True,and
tests/queries/shell_config.shfalls back to"${CLICKHOUSE_BINARY} server"when no-serverbinary 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 bothhelpers, on master and with this change, against the same live process tree:
get_server_pidget_server_memory_fraction/bin/sh -c : && clang++ ... -I.../clickhouse-server/...(1.9 MiB).../programs/clickhouse server --config-file ...(862.8 MiB)Note what master picked: not the server's launcher shell but an unrelated compile step, whose command
line merely contains
clickhouse-serverinside an include path. Any process on the machine can winthat 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 thecommtest rejecting it.Tests (
ci/tests/test_print_stacktraces.py, run by theCI Testsjob): 22 predicate cases pinningboth directions - 8 accepted spellings including absolute paths, both selectors and a custom
--binary, and 14 rejected ones including shell wrappers, the renamed watchdog, other multicalltools (
local,client,chl), a foreign argv[0] with aserversubcommand, a bare argv[0] withno 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 wherethe child inherits the watchdog
commso only the pid rule resolves it), aget_server_pid == get_all_server_pids[0]consistency case, aprint_c_stacktracescase whoseprocess table changes between calls, two
comm-helper cases, a live-server case, and a shed-RSScase. All 38 fail on master and pass here. I also checked each one is non-vacuous by mutating the
predicate, the graph filter, the
commread and the caller 18 ways; every mutant is caught,including reintroducing the substring prefilter and dropping either watchdog test.
No
src/orprograms/change, so no changelog-visible behaviour and noSettingsChangesHistoryentry. The hung-check verdict string is untouched, so the CIDB signature and
functional_tests_results.pyparsing are unaffected.Merge order
PR #106385 edits the same two regions of
tests/clickhouse-test(it addsget_server_pid_by_portnext to
get_server_pid, and changes the pid line inget_server_memory_fraction), so a textualconflict 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
26.8.1.748(included in26.8and later)