Skip to content

Fix "Scraping system tables" losing every replica's system tables - #111979

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-stop-server-signals-real-server
Jul 31, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-stop-server-signals-real-server

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

stop_server signalled the wrong process, so a server that clickhouse stop could not stop gracefully was left running — and it kept its exclusive lock on <run_path>/status, which made the later "Collect logs" phase fail to scrape that replica's system.*_log tables.

The servers are started with subprocess.Popen(command, shell=True), so Popen.pid is the sh -c ... wrapper, and BaseDaemon::setupWatchdog forks once more below it — the server is the wrapper's grandchild, and the only handle on it is the pid it writes to its own --pid-file. The SIGTRAP "generate core file" branch and the proc.kill() after it both went to the shell instead:

  • the TRAP dumped a useless core.sh.<pid> rather than a core of the wedged server, so that branch never once produced the dump it exists to produce, and uploaded a junk core as a job artifact;
  • the shell died immediately, so proc.wait(timeout=10) returned at once and stop_server moved on while the server kept running.

The orphaned server then blocks clickhouse local --path <run_path>:

Code: 76. DB::Exception: Cannot lock file <run_path>/status.
Another server instance in same directory is already running. (CANNOT_OPEN_FILE)

and every system table of that replica is lost from the report.

Observed on master 3401bc9cdfa1187d229dc4f84ba3aa380bec4f0b in Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3): replicas 1 and 2 (pids 802 and 952) both outlived stop_server, which had TRAPped their wrappers (pids 792 and 943 — hence the core.sh.792-3832 and core.sh.943-3998 artifacts), and all 11 scraped system tables then failed for both replicas.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3401bc9cdfa1187d229dc4f84ba3aa380bec4f0b&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%202%2F3%29

This is not specific to that shard: CIDB has 159 Scraping system tables failures carrying this exact status-lock error across 20 different check configurations since 2026-04-29, 1–7 per day.

The fix

Signal the pid from the pid file, wait for the server to finish writing its core dump (TRAP_CORE_DUMP_TIMEOUT, 300s — a coverage or sanitizer build needs far longer than the 10s that used to be allowed), and escalate to SIGKILL if it is still there, so the status lock is always released before the scraping runs. The wrapper is then reaped, so it is not left behind as a stray process — that is all reaping it does, since the server is the wrapper's grandchild and outlives it. The same wrapper-versus-server mixup in the force path is fixed alongside it. As a side effect the TRAP branch now produces what it was always meant to: a core dump of the server that would not stop.

The pid is taken from the pid file as it reads at teardown time, not from the snapshot captured when the server was started. Under CLICKHOUSE_WATCHDOG_RESTART=1, BaseDaemon::setupWatchdog respawns the server under a new pid — and the new server rewrites its --pid-file — while the wrapper and the watchdog above it keep theirs, so the snapshot goes stale and signalling it would be a no-op on a dead pid. The pid file is reread once more after the teardown, in case the watchdog got another server up in the meantime; nothing may outlive stop_server holding the status lock.

A server that came back that way cannot be dealt with by killing it, though: the watchdog restarts it after every abnormal exit, so each SIGKILL only triggers the next restart. The watchdog itself is therefore stopped first — the parent chain of the pid-file server is walked upwards for as long as the ancestor is a ClickHouse server process itself (the parent pid comes from the PPid: line of /proc/<pid>/status, whose fields, unlike those of /proc/<pid>/stat, are safe to split), and those are the watchdogs BaseDaemon::setupWatchdog left above it. This only happens once a server has been observed coming back, so on the normal teardown path the watchdog still exits on its own and gets to log the server's exit status.

Every signal is gated on an identity check of the target, so a pid the kernel has already recycled is never signalled: argv[0] from /proc/<pid>/cmdline, compared exactly against clickhouse-server after stripping the directory. That is the argv[0] the servers are started with, and it survives the BaseDaemon::setupWatchdog fork. A substring search over the whole command line would not do — the pid file is <config dir>/clickhouse-server.pid, so an unrelated process merely naming it among its arguments would be taken for the server. Bare clickhouse is not accepted either: the log scraping this teardown exists to unblock runs clickhouse local in the very same directory.

Testing

ci/tests/test_stop_server_signals_server_not_wrapper.py drives the real stop_server against a fake server built to have the same wrapper → watchdog → server topology, and asserts that the process named by the pid file is gone and the data-directory lock is free once it returns, including when the server ignores the TRAP, plus that an unrelated process occupying a recycled pid — with the production clickhouse-server.pid path in its command line — is left alone, that a server whose pid drifted under a restarting watchdog is still stopped, and that a watchdog which restarts the server after every abnormal exit is itself stopped rather than being allowed to outlast a bounded number of child kills. The fake server takes its identity from argv[0] the way the real one does, by running the interpreter through a symlink named after the binary. The behavioural tests fail on the pre-fix code with the server outlived stop_server.

Also verified end-to-end against a real clickhouse-server build: TRAPping the Popen handle leaves the server alive and reproduces the Code: 76 ... Cannot lock file .../status scraping error verbatim, while signalling the pid-file pid releases the lock and the scrape succeeds.

Related: #110816 (the tracking issue for this test name; its recorded failure is the other Scraping system tables mode — the minio_audit_logs dump timeout — not this one)

Changelog category (leave one):

  • CI Fix or Improvement

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

`stop_server` signalled the wrong process. The servers are started with
`subprocess.Popen(command, shell=True)`, so `Popen.pid` is the `sh -c ...`
wrapper, and `BaseDaemon::setupWatchdog` forks once more below it - the server
is the wrapper's grandchild, and the only handle on it is the pid it writes to
its own `--pid-file`.

So when `clickhouse stop` could not stop a server gracefully, the `SIGTRAP`
"generate core file" branch and the `proc.kill()` after it both hit the shell:

- the TRAP dumped a useless `core.sh.<pid>` instead of a core of the wedged
  server, so the branch never once produced the dump it exists to produce, and
  uploaded a junk core as a job artifact;
- the shell died immediately, so `proc.wait(timeout=10)` returned at once and
  `stop_server` moved on while the server kept running.

An orphaned server keeps its exclusive lock on `<run_path>/status`, so the
later "Collect logs" phase, which scrapes `system.*_log` with
`clickhouse local --path <run_path>`, fails for that replica with

    Code: 76. DB::Exception: Cannot lock file <run_path>/status.
    Another server instance in same directory is already running.
    (CANNOT_OPEN_FILE)

and every system table of that replica is lost from the report.

Seen on master 3401bc9 in `Stateless tests
(amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel,
2/3)`: replicas 1 and 2 (pids 802 and 952) both outlived `stop_server`, which
had TRAPped their wrappers (pids 792 and 943 - hence the `core.sh.792-3832` and
`core.sh.943-3998` artifacts), and all 11 scraped system tables then failed for
both replicas. The report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3401bc9cdfa1187d229dc4f84ba3aa380bec4f0b&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%202%2F3%29

Signal the pid from the pid file instead, wait for the server to finish writing
its core dump (`TRAP_CORE_DUMP_TIMEOUT`, 300s - a coverage or sanitizer build
needs far longer than the 10s that used to be allowed), and escalate to
`SIGKILL` if it is still there, so the `status` lock is always released before
the scraping runs. The wrapper is then reaped, which also remains the only way
to stop a server whose pid file has gone stale. The same wrapper-vs-server mixup
in the `force` path is fixed alongside it.

Signals are gated on a `ps -ww -p <pid> -o command=` match for
`clickhouse-server`, so a pid the kernel has already recycled is never signalled
- `-ww` matters, because `ps` truncates the command line to 80 columns when its
output is not a terminal and would drop the match for a server started from a
long path.

The new tests drive the real `stop_server` against a fake server built to have
the same wrapper -> watchdog -> server topology, and assert that the process
named by the pid file is gone and the data-directory lock is free once it
returns. Both fail on the pre-fix code, which left the server running.
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1077bac]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) DROPPED

AI Review

Summary

The PR fixes the wrapper-vs-server mixup in stop_server and adds focused regression coverage for the pid-file and respawn paths. The remaining CLICKHOUSE_WATCHDOG_RESTART=1 fix is still incomplete, because the new watchdog-kill path identifies ancestors only as clickhouse-server, while the real watchdog renames itself to clickhouse-watchdog.

Findings

❌ Blockers

  • [ci/jobs/scripts/clickhouse_proc.py:862-962] The restart-mode contract is still violated on the real server topology. BaseDaemon::setupWatchdog rewrites the parent process name to clickhouse-watchdog in src/Daemon/BaseDaemon.cpp, but _server_watchdog_pids and _signal_server gate everything through _server_process_alive, which only accepts clickhouse-server. On an actual CLICKHOUSE_WATCHDOG_RESTART=1 run that leaves the watchdog undiscovered and alive, so _stop_respawned_server can still exit after a bounded number of child kills with a respawned server holding <run_path>/status. The new fake-watchdog test keeps the parent argv[0] as clickhouse-server, so it does not cover this production shape.
Final Verdict

❌ Changes requested

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 26, 2026
Comment thread ci/jobs/scripts/clickhouse_proc.py Resolved
…its command line

`_server_process_alive` accepted any process whose whole command line
contained `clickhouse-server`. That is not an identity check: the pid file
is `<config dir>/clickhouse-server.pid`, so an unrelated process that had
been given the server's recycled pid and merely names that path - or any
other `clickhouse-server` path - among its arguments was taken for the
server, and the `SIGTRAP`/`SIGKILL` went to it.

Compare `argv[0]` from `/proc/<pid>/cmdline` exactly against
`clickhouse-server` instead, which is the `argv[0]` the servers are started
with and is inherited by the process `BaseDaemon::setupWatchdog` forks.
Reading `/proc` also removes the `ps` command-line truncation hazard the
`-ww` flag was there to work around. Bare `clickhouse` is deliberately not
accepted: the log scraping this teardown exists to unblock runs
`clickhouse local` in the very same directory.

`test_stop_server_leaves_an_unrelated_process_alone` used to sidestep the
production shape by renaming the pid file away from
`clickhouse-server.pid`. The fake server now always uses the production
pid-file name and instead takes its identity from `argv[0]` - it runs the
Python interpreter through a symlink named after the binary under test, the
same `argv[0]`-versus-`/proc/<pid>/exe` split as the real
`clickhouse-server` symlink to `clickhouse`, which a `#!` script cannot
reproduce because the kernel overwrites its `argv[0]`. The test fails
against the old substring check, which kills the unrelated process.
Comment thread ci/jobs/scripts/clickhouse_proc.py Outdated
The wrapper (and the watchdog between it and the server) normally exits
on its own within a moment of the server going away; kill it if it does
not, so it is not left behind as a stray process. This is also the only
thing that stops a live server whose pid file went stale, since then

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.

proc.kill() here only reaps the /bin/sh -c ... wrapper; it does not stop the watchdog or the live server child. That means this fallback does not cover the stale-pid case the comment describes. In the supported CLICKHOUSE_WATCHDOG_RESTART=1 mode, BaseDaemon::setupWatchdog can respawn the server under a new pid while the same wrapper/watchdog chain stays alive, but stop_server still uses the startup snapshot in self.pid_0/1/2. Once that old pid is gone, _signal_server becomes a no-op, _wait_server_gone returns immediately, and this branch leaves the restarted server alive holding <run_path>/status.

The teardown needs to refresh the current server pid (or otherwise track the watchdog child) before signalling; killing proc alone is not enough.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

In the supported CLICKHOUSE_WATCHDOG_RESTART=1 mode

As long as it's not used in the CI, it's okay.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 11b9058: stop_server now rereads the pid file before signalling (_current_server_pid) and again after the teardown (_stop_respawned_server), so a pid that drifted under CLICKHOUSE_WATCHDOG_RESTART=1 is signalled rather than skipped, and a server the watchdog brought back is killed instead of being left holding <run_path>/status. The comment claiming that reaping the wrapper stops a server whose pid file went stale is gone - it does not, the server is the wrapper's grandchild. New test test_stop_server_stops_the_server_the_pid_file_names_now models the drift (the fake watchdog restarts the server under a new pid before the teardown); it fails against the snapshot-only code.

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.

ci/jobs/scripts/clickhouse_proc.py:848 still leaves the original restart-mode issue reachable. _stop_respawned_server only kills the pid-file server up to RESPAWN_STOP_ATTEMPTS times; it never stops the watchdog that is respawning it, so a later server can still survive after the loop returns.

I reproduced this against the current head with a fake watchdog that restarts on every abnormal exit. The loop killed three respawned servers and then returned with a fourth one still alive and back in clickhouse-server.pid:

ClickHouse process 12 came up again after the teardown - send KILL signal
Send KILL signal to ClickHouse process 12
ClickHouse process 13 came up again after the teardown - send KILL signal
Send KILL signal to ClickHouse process 13
ClickHouse process 14 came up again after the teardown - send KILL signal
Send KILL signal to ClickHouse process 14
WARNING: ClickHouse process 15 is still alive after the teardown - system tables in ... will not be scraped

So the stale-pid/watchdog-restart case is not actually fixed yet; the teardown needs to stop the watchdog itself (or otherwise prevent further respawns), not rely on a bounded number of child kills.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 1077bac. You are right that a bounded number of child kills cannot win against a watchdog that restarts after every abnormal exit, so _stop_respawned_server now stops the watchdog first: for a server that came back, _stop_server_watchdogs walks the parent chain of the pid-file server and SIGKILLs every ancestor that is a ClickHouse server process itself (outermost first), which is the watchdog BaseDaemon::setupWatchdog left above it - the sh -c wrapper above that is not touched here, it is _reap_server_wrapper's business. Once the watchdog is gone nothing can respawn the server, and the remaining loop is only a backstop for a chain that reappears mid-teardown. The watchdog is killed only after a server has been observed coming back, so the normal teardown path is unchanged and the watchdog still exits on its own and logs the server's exit status.

The parent pid comes from the PPid: line of /proc/<pid>/status, not from /proc/<pid>/stat, whose fields cannot be split on whitespace (the command name is parenthesised and may contain spaces).

New test test_stop_server_stops_the_watchdog_that_keeps_restarting_the_server models exactly your repro - the fake watchdog restarts the server after every abnormal exit - and asserts that no server the pid file names is alive and that <run_path>/status is unlocked when stop_server returns. It fails against the bounded-kill code (a server the watchdog restarted (...) outlived stop_server) and passes with the fix; all 6 tests in the file pass.

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.

ci/jobs/scripts/clickhouse_proc.py:899-962 still misses the real restart-mode watchdog. _server_watchdog_pids walks parents only while _server_process_alive is true, and _signal_server uses the same guard before sending SIGKILL. But _server_process_alive accepts only argv[0] == clickhouse-server, while BaseDaemon::setupWatchdog rewrites the parent process name to clickhouse-watchdog in src/Daemon/BaseDaemon.cpp:641-645.

On an actual CLICKHOUSE_WATCHDOG_RESTART=1 server the parent of the pid-file server is therefore filtered out immediately, no watchdog is killed, and _stop_respawned_server falls back to the bounded child-kill loop that can still return with a respawned server holding <run_path>/status. The new fake watchdog test keeps the parent argv[0] as clickhouse-server, so it still does not exercise the production shape this change is trying to fix.

@@ -0,0 +1,269 @@
"""

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is trash, but ok to keep.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
…up snapshot

`stop_server` signalled the pid captured when the server was started. With
`CLICKHOUSE_WATCHDOG_RESTART=1`, `BaseDaemon::setupWatchdog` respawns the
server under a new pid - and the new server rewrites its `--pid-file` - while
the `sh -c` wrapper and the watchdog above it keep their pids. The snapshot is
then stale: `_signal_server` no-ops on a dead pid, `_wait_server_gone` returns
at once, and `_reap_server_wrapper` only tears down the shell, so the live
server is left holding `<run_path>/status` and the `clickhouse local` scraping
of `system.*_log` loses every system table of that replica - the very failure
this pull request is about.

Reread the pid file before signalling, and again once the teardown is over, in
case the watchdog got another server up in the meantime. Also drop the claim in
the `_reap_server_wrapper` comment that killing the wrapper stops a server whose
pid file went stale - it does not, the server is the wrapper's grandchild.

The new test models the drift: the fake watchdog restarts the server under a new
pid before the teardown. It fails against the snapshot-only code.
`_stop_respawned_server` only killed the server the pid file named, up to
`RESPAWN_STOP_ATTEMPTS` times. Under `CLICKHOUSE_WATCHDOG_RESTART=1` the
watchdog brings a new server up after every abnormal exit, so each `SIGKILL`
only triggered the next restart: the loop ran out of attempts with yet another
server alive and still holding `<run_path>/status`, which is exactly the state
that makes the later `clickhouse local` scraping of `system.*_log` fail with
`CANNOT_OPEN_FILE` and lose every system table of that replica.

Now the watchdogs above a server that came back are killed first
(`_stop_server_watchdogs`), so nothing can respawn it. They are found by walking
the parent chain of the pid-file server (`_parent_pid` reads `/proc/<pid>/status`,
whose `PPid:` line is safe to split, unlike `/proc/<pid>/stat`) for as long as
the ancestor is a ClickHouse server process itself - above the watchdog sits the
`sh -c` wrapper, which is `_reap_server_wrapper`'s business. This only happens
once a server has been seen coming back, so the normal teardown path still lets
the watchdog exit on its own and log the server's exit status.

New test `test_stop_server_stops_the_watchdog_that_keeps_restarting_the_server`
models a watchdog that restarts after every abnormal exit; it fails against the
bounded-kill code with a respawned server left alive.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into master with commit ce675be Jul 31, 2026
177 of 179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-stop-server-signals-real-server branch July 31, 2026 13:20
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
@maxknv

maxknv commented Jul 31, 2026

Copy link
Copy Markdown
Member

Reverting this in #112812. On macOS the new _server_process_alive reads /proc/<pid>/cmdline, which doesn't exist on Darwin — so Fast test (arm_darwin) teardown always concludes the server is "already gone" and never stops it. The orphaned server holds praktika's stdout pipe open and praktika run hangs after a green run; since the macOS runners are ephemeral, each hung job permanently consumed a host (ap-southeast-2 pool went 10→2 in ~4h). Please re-land with a cross-platform liveness check (os.kill(pid, 0) + ps, or branch on platform.system()).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants