Skip to content

Fix flaky 04365_cancel_insert_when_client_dies_distributed under host load - #119778

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/04365-inflight-client-pid
Sep 13, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/04365-inflight-client-pid

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #96844

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

04365_cancel_insert_when_client_dies_distributed now finds the insert client it has to kill in constant time instead of scanning every process on the host, so its "something was cancelled" guard no longer reads 0 on a loaded machine.

Description

Requested by @ alexey-milovidov in #96844 (comment). Line 3 of the reference flips to 0 while both data lines stay 500000: 10 public failures across 9 pull requests in 90 days, all on ..., parallel lanes. His own report is on a private lane I cannot read, so this PR fixes the public signature; his lane is ..., parallel too.

Root cause. thread_cancel locates the in-flight client by grepping /proc/*/cmdline, which costs O(all processes on the host) and forks five processes per poll. One sweep measured 0.08 s at 6,400 processes and 0.31 s at 27,900, against a 10 ms poll, while the client lives about 130 ms. Once a sweep outlasts the client, the poll starves (kills per 40 s run fall from ~120 to 0-8) and the pids it returns are stale (12-50% hit an exited process). Nothing gets cancelled, and the anti-vacuity guard prints 0 truthfully. #111157 shortened the poll interval but kept the sweep.

Change. insert_data runs its client asynchronously and publishes $!; thread_cancel reads that one pid and accepts it only while /proc/<pid>/cmdline still carries the query id: liveness and identity in one check. The guard, its whitelist and .reference are untouched.

Validation (debug build, one server): 9 failures in 11 unmodified runs, 0 in 114 fixed runs including two clickhouse-test --test-runs 50 sets, with 110-133 cancellations per run and every kill landing on a live pid. Received 'Cancel' packet rows stay at 7-10 per run, so SIGINT still reaches a backgrounded client: clickhouse-client installs its own handler, curl does not. That is why 02434 and 04366 keep the sweep here, even though they flip 3/3 under the same induced load.

Its 24 master hits over 90 days are a different, LLVM Profile Error facet, fixed by merged #113619.

Measurements

Six alternating pairs, one unmodified run and one fixed run each, with the sweep cost sampled just before. The fleet's own load fell during the arm, so no processes were spawned for this table:

sweep unmodified its kills fixed its kills
0.31 s FAIL 0 PASS 112
0.34 s FAIL 0 PASS 126
0.29 s FAIL 0 PASS 119
0.26 s FAIL 0 PASS 112
0.09 s PASS 90 PASS 127
0.08 s PASS 33 PASS 133

Over all 11 unmodified runs the guard reads 1 in every run with at least 33 kills and 0 in every run with at most 8, and no run of any variant ever produced a row count other than 500000.

A cheaper scan does not help: pgrep -f and ps also walk all of /proc, so they stay O(host processes); only publishing the pid makes the lookup independent of host load.

Two mutants of the fixed test, three runs each, both expected to fail and both failing with guard 0: disabling kill -s (the poll still found the client 115-126 times per run), and publishing the pid where the poll does not read it (2,600 polls per run, no candidate ever). A control of the fixed test in the same window passes 3/3 with 129-133 kills.

Client wall time per insert path, 5 invocations each: 04365 native 116-137 ms; 02434 native 104-116 ms; 02434 curl 31-36 ms; 04366 curl 80-90 ms. So the two curl-driven siblings are not protected by a longer-lived client, and with 6,000 extra processes on the host (sweep 0.33-0.36 s) they flip 3/3 each. Porting this fix to them needs a different way to publish the pid, because a backgrounded curl ignores SIGINT, which would silently turn half of their kill signals into no-ops.

One thing this does not touch: the whitelist entry Query was cancelled or a client has unexpectedly dropped the connection has matched nothing in src/ since cea797e254e6 (2024-11-11) and is still present in four test files.


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

…s_distributed

thread_cancel located the client to kill by grepping /proc/*/cmdline. That
sweep globs every process on the host and forks five processes per poll, so its
cost is set by the machine's process count rather than by the test: measured on
a shared 96-core box, one sweep takes 0.08 s at 6,400 host processes and 0.31 s
at 27,900, against the loop's intended 10 ms. An insert client here lives about
130 ms, of which the server-side insert is 42.5 ms.

Once a sweep outlasts the client, two things fail at once. The poll starves, so
the number of kills in a 40 s run falls from about 120 to between 0 and 8; and
the pid a sweep returns is up to one sweep old, so 12 to 50% of the kills that
do fire hit a process that has already exited. No cancellation then lands inside
the in-flight window, and the anti-vacuity guard on line 3 prints 0 truthfully
while both data lines stay at 500000. That is the failure seen in CI: 10 public
occurrences across 9 pull requests in 90 days, all on ..., parallel lanes.
8a43197 shortened the poll interval but kept the sweep, which is why the
failure survived it.

insert_data now runs its client asynchronously and publishes the pid, and
thread_cancel reads that one pid, accepting it only while /proc/<pid>/cmdline
still carries the query id, so liveness and identity are checked at once and a
reused pid is never killed. The guard, its whitelist and the reference file are
untouched.

Backgrounding is safe for this test in particular because clickhouse-client
installs its own SIGINT handler (ClientApplicationBase::setupSignalHandler),
overriding the SIG_IGN that bash gives an asynchronous command. A backgrounded
curl does not, and was measured to survive SIGINT, so 02434 and 04366 keep the
sweep even though they were measured to flip 3/3 under the same induced load;
porting this there needs a different way to publish the pid.

Measured: 9 failures in 11 unmodified runs against 0 in 114 runs with this
change, 110 to 133 cancellations per run, every kill landing on a live pid, and
the graceful-cancel evidence unchanged at 7 to 10 text_log rows per run. Six
alternating pairs place the flip boundary between a 0.09 s and a 0.26 s sweep,
with the fixed test flat across that range.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 13, 2026
@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; 0 findings), plus 4 findings from
the reviewing model's own cold pass over the resulting code. Adjudicated below.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description stated the flip signature as observed in the private sync lanes, which is second-hand: that report is not readable from my account AGREE, fixed before publication Rewritten to say plainly that I cannot read the private report and that this PR fixes the public signature. No unverifiable count is asserted anywhere in the body
2 💡 The cheaper alternative was left unaddressed: keep the scan but run it in one process AGREE, fixed before publication One clause added: pgrep -f and ps also walk all of /proc, so they stay O(host processes); only publishing the pid makes the lookup independent of host load
3 💡 Backgrounding the client means bash sets SIGINT to SIG_IGN, so an early signal is a no-op where it previously terminated the client DISAGREE A signal landing before the insert reaches the server yields no cancellation either way, so no evidence is lost. sigaction(SIGINT, ...) at src/Client/ClientApplicationBase.cpp:111 is unconditional, SIGKILL (half the signals) cannot be ignored, and the graceful-cancel rows measure 7, 9 and 10 per fixed run against 6 and 7 on passing unmodified runs
4 💡 Validated on a debug build although the test is tagged no-debug DISAGREE The direction is conservative: a debug client lives longer, so poll starvation is harder to induce, and it still reproduced 9 times in 11 unmodified runs. The fix removes the dependence on client lifetime, and the tag line is byte-identical to base

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Independently re-verified while reviewing, rather than taken from the implementation notes:
CLICKHOUSE_TMP is per random database (tests/clickhouse-test:2462-2464), so the un-suffixed
pid file cannot collide between concurrent runs of this test, including the flaky check's 50 runs
of it; CLICKHOUSE_CLIENT is a simple command (shell_config.sh:46, never preset elsewhere), so
$! is the client and not a wrapper; 04365 is the only member of this family whose inserts are
100% native protocol (02434 is 1/3 native, 04366 and 02435 are curl only), which is what
makes backgrounding safe here and not there; and the 10 public failures across 9 pull requests
reproduce exactly on play.clickhouse.com, with LLVM Profile Error absent from all 10 and
present in all 24 master rows, confirming the two facets are distinct.

Session id: cron:clickhouse-review-slot-10:20260913-111400

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, once the variable the mechanism names is set: with the /proc sweep costing >= 0.26 s (about 20k+ processes on the host, or 6,000 spawned sleeps) the unmodified test failed 7/7; at <= 0.09 s it passed. Harness: an instrumented copy driven in a loop, kill log per run.
b Root cause explained? Yes. thread_cancel finds the in-flight client by grepping /proc/*/cmdline, which is O(all processes on the host) and forks five processes per poll. One sweep grows to 0.31 s at 27,900 host processes while a client lives about 130 ms (42.5 ms of it server-side), so the poll starves (kills per run fall from ~120 to 0-8) and the pids it returns are stale (12-50% of those kills hit an exited process). No cancellation lands in the in-flight window, so the anti-vacuity guard prints 0 truthfully.
c Fix matches root cause? Yes: the search itself is removed. insert_data publishes the pid of the client it runs and thread_cancel reads that one pid, so the lookup is O(1) in host process count. No widened bound, no no-random-* tag, no retry loop, no reduced dataset; the guard, its whitelist and .reference are byte-identical.
d Test intent preserved / new tests added? Preserved and strengthened: the same guard now observes 110-133 cancellations per run instead of 0-8. Two mutants confirm it still reddens (disabling kill -s: 3/3 fail; publishing the pid where the poll does not read it: 3/3 fail). No new test file, since this is a test-driver fix with no src/ change.
e Both directions demonstrated? Yes, interleaved on one server: 9 failures in 11 unmodified runs against 0 in 114 fixed runs (14 harness runs plus two independent clickhouse-test --test-runs 50 sets). Six alternating pairs put the flip boundary between a 0.09 s and a 0.26 s sweep, with the fixed copy flat across that range.
f Fix is general across code paths? The same sweep exists in 02434 and 04366, and both were measured to flip 3/3 under the same induced load. They are deliberately not changed here: 2/3 and 3/3 of their inserts are curl, and a backgrounded curl ignores SIGINT (measured), so copying this fix would silently turn half of their kill signals into no-ops. 02435 carries the sweep but has no poll loop and its guard is commented out, so no invariant is at risk there.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type surface (test-only change, no src/ code, no settings). The input dimension that exists here is host load, and the fixed copy is invariant across a 4x sweep-cost swing plus a 6,000-process burst.
h Backward compatible? N/A: no setting, no format, no SettingsChangesHistory.cpp entry. The test's stdout contract is unchanged.
i Invariants and contracts preserved? Yes. insert_data still returns the client's exit status (wait "$CLIENT_PID") and still reads $DATA_FILE on the backgrounded command; there is no set -e in the test or in shell_config.sh, and clickhouse-test would fail the test on any stderr, which 50/50 green rules out. thread_cancel keeps its INT/KILL coin flip, its outer sleep 0.$RANDOM and its TIMELIMIT bound. Pid reuse is handled by matching the cmdline rather than trusting the file; a missing /proc/<pid>/cmdline is the expected miss, and a kill on a pid that died between check and signal fails harmlessly.

Session id: cron:clickhouse-impl-slot-6:20260913-091400

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fc2b4b2]

Summary: ✅


AI Review

Summary

The PR changes 04365_cancel_insert_when_client_dies_distributed.sh so insert_data publishes the native client PID and thread_cancel polls that PID instead of rescanning /proc/*/cmdline on every attempt. I did not find a material correctness, coverage, or metadata issue in the current diff; the row-count invariant and the anti-vacuity cancellation check remain in place while the host-load-dependent lookup is removed.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 13, 2026
@groeneai groeneai mentioned this pull request Sep 13, 2026
1 task done
@groeneai
groeneai requested a review from CheSema September 13, 2026 11:50
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 13, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 44d65c7 Sep 13, 2026
185 of 348 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). and removed comp-testing Test content only (no production code). labels Nov 22, 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 comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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