Skip to content

Let the hung check read the processlist when the server is over its memory limit - #116545

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:hung-check-no-aggregation
Aug 28, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:hung-check-no-aggregation

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Related: #110626 (requested in this comment; I posted a correction to my first analysis of it)

Stress test (amd_debug) reported Hung check failed, possible deadlock found, but the hung check had not managed to look at the server: all 180 of its liveness retries were refused with Code: 241. Something really was hung, so the verdict was right by accident; the check itself never read system.processes.

Root cause. stress.py passes --client-option max_memory_usage_for_user=0 to the hung check for exactly this reason, but those settings only become URL parameters inside if args.cloud: (clickhouse-test:7202), and every clickhouse_execute_http URL is built from that string. Meanwhile Aggregator::checkLimits calls CurrentMemoryTracker::check(), a zero-sized allocation whose will_be is the current amount, so no untracked-memory setting can affect it. Aggregation is therefore the exposure, and the check aggregated in all three of its own queries: the startup probe, get_processlist_size (count()) and the stacktrace dump. The NOTE claiming "neither hung check, nor 00001_select_1 has GROUP BY" was never true.

The change drops the aggregation from the probe and from get_processlist_size (including its two clusterAllReplicas branches), exempts the one query that must aggregate in all three of its branches, routes stress.py's last un-overridden query through make_query_command, stops a bare except: from reporting "I could not tell" as "yes" with no log line, and corrects a message that named a SELECT 1 it never runs. Nothing suppresses a verdict.

Reports: Stress test (amd_debug). Adjacent in intent: #115692.

I am sending the server-side hang, Context::setCurrentDatabase deadlocking against its own Context::mutex through a database-name hint, as a separate PR. Note that even with this change that hang would not have been named: it happens before the process-list insertion (executeQuery.cpp:2651 against :2791), so those threads were never in system.processes.

Validation (no test home exists for runner code; ci/tests/ is being removed)

Fixture: a 953.67 MiB per-user cap and a query holding 2.0-2.8 GiB: the flap setOrRaiseHardLimit(0) and ProcessList.cpp:397 produce in CI. Counters, not the exit code, are the oracle: both arms exit non-zero.

counter base C1 only with fix
Connection error, will retry 180 0 0
All connection tries failed 1 0 0
Server is not responding 2 0 0
Failed to get processlist size 0 1 0
Found hung queries in processlist 0 0 1

The base column matches the CI run's hung_check.log exactly (180/1/2). The middle column is a de-aggregated probe only: the failure moves to get_processlist_size, so both changes are needed. With the fix the check names the holding query. Without memory pressure both arms exit 0 with No queries hung., and 20 of 20 invocations plus --test-runs 50 pass.

Blast radius, from query_log: max_memory_usage_for_user = 0 on the stacktrace query (1 execution), the profile value on all 47157 other runner queries. Client-side counting is latency-neutral (p90 2 ms).

The clusterAllReplicas branches carry the same exemption. Measured with the cap armed: unexempted they fail with chunk of 0.00 B, exempted they return the dump, on the initiator's own local shard; against a replica that is itself over its cap the exemption changes nothing, since ClusterProxy/executeQuery.cpp marks the setting unchanged before forwarding and the test cluster has no <secret>. The initiator is the server the runner talks to, so it accumulates the workload.

One bound: setOrRaiseHardLimit restores a positive limit, so a query inserted while the dump runs re-arms the cap and the dump can still fail (measured). A large positive value defeats that but is never lowered again, so 0 is kept; when the race fires the check prints the server's own error.


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

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 26, 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; 2 findings), plus my own cold
review of the resulting code.

# Sev Finding Verdict Evidence / action
1 ⚠️ The single-query exemption clears the shared per-user tracker, which is reset only when the user has no queries left, so the over-limit workload can keep allocating and the diagnostics are lost to an OOM. Remedy proposed: drop the exemption, emit one stacktrace row per thread, and remove stress.py's --client-option DISAGREE The mechanics are right, three necessary steps are not. (1) The per-user tracker's parent is total_memory_tracker by construction (ProcessList.h:337 selects MemoryTracker.cpp:156), allocImpl propagates to it (:485), and its hard limit comes from max_server_memory_usage, untouched here, so total allocation is still bounded and an overrun still raises MEMORY_LIMIT_EXCEEDED rather than reaching an OOM. (2) The change does not introduce a lifted shared limit into that window: get_additional_client_options (clickhouse-test:6446) hands every --client-option to the native client, and both 00001_select_1 and get_stacktraces_from_clickhouse (:1094) use it, so stress.py already drives the shared limit to 0 twice in the same invocation. This extends that existing decision to the one HTTP query the cloud-only gate was excluding. (3) The remedy is measured not to work: with the exemption removed, that query fails on a real 4.00 MiB allocation, not the zero-sized Aggregator::checkLimits probe, so de-aggregating it would not reliably let it answer. Measured blast radius of what shipped: 1 query of 47158
2 ⚠️ No automated regression test would fail if the changed queries regained aggregation or the exemption stopped being applied. Remedy proposed: a fake-executor arm on the existing ci/tests/ harnesses AGREE on the fact, DISAGREE on the remedy The fact is real and stronger than stated. Both harnesses named live under ci/tests/, which is being removed (#115825), so an arm there would be code scheduled for deletion. There is no other home: tests/ci/ holds CI helper modules and no runner tests, and a stateless test cannot reach the runner because it runs inside it. I also considered and rejected a style-check rule matching aggregate functions inside SQL held in Python strings, as machinery larger and more speculative than the fix. Stated plainly in the description and in row (d) of the validation gate rather than papered over
3 💡 My own review: two line citations and one technical claim in my draft text were wrong, including "the two clusterAllReplicas branches cannot be exempted from the initiator" AGREE, corrected before publishing That claim is false for the initiator's own local shard: the local replica keeps local_addresses, SelectStreamFactory.cpp:226 routes it through createLocalPlan in the same query, and ProcessList.cpp:397 arms the user tracker from that query's own setting. Only the remote replicas are unreachable. The description now says exactly that, and records that the local shard could have been exempted and was not, because that path has no recorded occurrence

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

Session id: cron:clickhouse-review-slot-8:20260826-144800

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test --hung-check --report-logs-stats --client-option max_untracked_memory=1Gi max_memory_usage_for_user=0 memory_profiler_step=1Gi ast_fuzzer_runs=0 --database=system 00001_select_1, against a server whose profile caps max_memory_usage_for_user at 953.67 MiB while a query holding 2.0-2.8 GiB runs under its own max_memory_usage_for_user = 0. Fails on every run.
b Root cause explained? stress.py passes --client-option max_memory_usage_for_user=0 to the hung check, but --client-option only becomes URL parameters inside if args.cloud: (clickhouse-test:7202), and every clickhouse_execute_http URL is built from that string, so the runner's HTTP queries carry none of it. Aggregator::checkLimits then calls CurrentMemoryTracker::check(), a zero-sized allocation whose will_be is the current amount (MemoryTracker.cpp:309), so no untracked-memory setting can influence it and the per-user tracker throws Code: 241 ... (attempt to allocate chunk of 0.00 B). All three of the check's own queries aggregated, so the check burned 180 liveness retries and reported a deadlock about a server it had never read.
c Fix matches root cause? Yes. The aggregation is removed from the two queries that must answer while the server is over its limit, and the one query that cannot avoid aggregating is exempted explicitly. No verdict is suppressed and no bound is widened: something really was hung in that run, and a false-positive-suppression fix would have hidden it.
d Test intent preserved / new tests added? get_processlist_size's contract is unchanged: a stubbed-transport check of all three branches at 0 / 1 / 3 rows returns identical counts in 18 of 18 cells, base versus fix, while aggregates flips True -> False in every branch. No committed test is possible: a stateless test cannot reach the runner's own probe, and ci/tests/ (where test_hung_check_exit_code.py covers this region) is being removed. Verified that ci/tests/ references none of the changed symbols, so nothing there breaks. The protection is the recorded A/B in (e).
e Both directions demonstrated? Yes, on the counters rather than the exit code, since both arms correctly exit non-zero. Base: 180 Connection error, will retry, 1 All connection tries failed, 2 Server is not responding, 0 Found hung queries in processlist (matching the CI run's hung_check.log exactly). With the fix: 0 / 0 / 0 / 1, and the report names the holding query. A de-aggregated probe alone moves the failure to get_processlist_size, which is why both changes are needed. Without memory pressure both arms exit 0 with No queries hung., and 20 of 20 repeated invocations plus --test-runs 50 pass.
f Fix is general across code paths? All three get_processlist_size branches, including the two clusterAllReplicas ones whose remote shards a per-user override provably cannot reach (ClusterProxy/executeQuery.cpp:344-357 marks the setting unchanged so it is not sent to the shards). The full carrier list was re-walked; one is deliberately uncovered and stated in the PR body: the stacktrace query's two clusterAllReplicas branches keep no exemption, and while their remote shards are unreachable either way, the initiator's own local shard could have been exempted and was not, since that path has no recorded occurrence. So on a memory-pressured Replicated-DB or SharedCatalog lane its payload may still be lost, though the verdict and the presence gate are not affected. reportLogStats also aggregates and is unchanged; measured harmless, since a run whose --report-logs-stats failed still exited 0.
g Fix generalizes across inputs (params/datatypes/wrappers)? Row counts 0 / 1 / 3 across all three branches, in both the armed and unarmed states. The empty-result case matters and is covered: an empty body yields len(b"".splitlines()) == 0, equal to the old count() result of 0. SELECT 1 is projected rather than a column on purpose, because the count is splitlines() and a projected value containing a newline would over-count.
h Backward compatible? (maintainer-approved exception only) Nothing engaged. No setting default changes, so no SettingsChangesHistory.cpp entry; no serialization change; no user-visible behaviour change; no CIDB leaf renamed. Harness code only.
i Invariants and contracts preserved? get_processlist_size returns the same integer for the same server state, and hung_count is only ever compared (== 0, > 0, != 0, plus a -1 "could not tell" sentinel), never printed or reported, so no caller changes. HUNG_CHECK_QUERY_SETTINGS is merged before allow_introspection_functions, so a future collision on that key is won by the explicit entry rather than silently by the constant. In stress.py the failure path still returns True, since permitting a report is the conservative direction and the defect was the silence, not the conservatism; the wrapping check_output(timeout=30) is unchanged and the only behaviour change is --receive_timeout 30 to 15, matching the sibling call 16 lines above.

Session id: cron:clickhouse-impl-slot-7:20260826-135100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? All three of the hung check's own queries aggregated, and --client-option only becomes URL parameters when --cloud is set, so Aggregator::checkLimits refused every liveness probe with Code: 241 and the run reported a deadlock about a server it had never read. This de-aggregates those queries, exempts the one that cannot avoid aggregating, and drops the GROUP BY NOTE in stress.py that the aggregating probe had already falsified.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [326e293]

Summary: ✅


AI Review

Summary

This PR removes aggregation from the hung-check liveness probes and get_processlist_size, and applies the per-user memory-limit override to the remaining aggregating stacktrace query so the runner can still inspect system.processes under memory pressure. On the current head I did not find a remaining correctness or contract violation in the touched paths, and the earlier inline concern about the missing clusterAllReplicas exemptions is fixed.

Final Verdict

✅ No new inline findings. The current patch looks correct from the reviewed correctness and diagnostics standpoint.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 26, 2026
Comment thread tests/clickhouse-test Resolved
…emory limit

`Stress test (amd_debug)` reported `Hung check failed, possible deadlock found`
while the hung check had never managed to look at the server: all 180 of its
liveness retries were refused with `Code: 241`. The leaf therefore carries no
information about whether the check found a hang or failed to look for one.

`stress.py` passes `--client-option max_untracked_memory=1Gi
max_memory_usage_for_user=0 memory_profiler_step=1Gi` to the hung check for
exactly this reason, but `--client-option` only becomes URL parameters inside
`if args.cloud:` (`clickhouse-test:7242`), and every `clickhouse_execute_http`
URL is built from that string, so no non-cloud run carries any of it. The
native-client path is not cloud-gated, which is why `stress.py`'s own
`make_query_command` queries kept working.

The refusal itself comes from a check no untracked-memory setting can reach:
`Aggregator::checkLimits` ends in `CurrentMemoryTracker::check()`, i.e.
`allocImpl(0, /*enforce*/ true)`, and for a zero-sized allocation
`MemoryTracker.cpp:309` makes `will_be` the current amount and compares it
straight against the limit. Aggregation is therefore the exposure, and the
check aggregated in all three of its own queries: the startup probe
(`groupArray`), `get_processlist_size` (`count()`) and the stacktrace dump
(`groupArray ... GROUP BY`). The `NOTE` above the `--client-option` list
claiming "neither hung check, nor 00001_select_1 has GROUP BY" was never true,
and its proposed remedy could not have worked, so it is deleted rather than
corrected.

Changes:

* The startup probe uses scalar subqueries instead of `groupArray`. Removing
  the aggregation rather than lifting the limit here matters, because
  `check_server_started` runs for every `clickhouse-test` invocation and
  `max_memory_usage_for_user = 0` mutates the shared per-user tracker.
* `get_processlist_size` projects `SELECT 1` and counts rows client-side, in
  all three branches. De-aggregating rather than exempting is what covers the
  two `clusterAllReplicas` branches completely: an override does reach the
  initiator's own local shard, but `ClusterProxy::executeQuery` sets
  `max_memory_usage_for_user = 0` for the shard query and then marks it
  unchanged, so it never reaches a remote replica. A literal `1` is projected rather than a column because the count is
  `splitlines()` and a projected value containing a newline would over-count.
  This continues the direction of 140f6da ("hung_check check with
  lighter queries"), which split the expensive dump into a cheap gate plus a
  heavy payload; `count()` was just the spelling of the day.
* `get_processlist_with_stacktraces` folds several threads per query into one
  row, and rewriting that client-side would change the text `stress.py` embeds
  in the CI report, so it keeps its aggregation and gets an explicit per-user
  exemption instead, in all three branches. That is now the one place the
  shared tracker is touched, and it runs at most once per job, after the check
  already knows there is something to report. Only `max_memory_usage_for_user` is
  lifted: `max_untracked_memory` and `memory_profiler_step` make tracking
  coarse and are irrelevant to a zero-sized check. The exemption is per call
  site rather than in the shared `params` dict because `--hung-check` is on
  every functional lane and 11 stateless tests assert on that setting. It
  covers the initiator, which is the server that accumulates the workload
  (`clickhouse_proc.py` puts the other replicas on 19000 and 29000 while the
  runner talks to 9000); a replica that is itself over its cap cannot be
  exempted from the initiator and still fails there, on an ordinary allocation
  rather than on the zero-sized check.
* `prepare_for_hung_check`'s `elapsed > 300` query goes through
  `make_query_command` like its sibling 16 lines above, so it carries the
  override too, and its bare `except:` now logs. Reporting "I could not tell"
  as "yes, there are long-running queries" with no log line at all is the
  defect; the conservative `return True` is kept.
* The failure message no longer names a `SELECT 1` query that is never run.

Nothing suppresses a verdict. Note that even with this change the hang in that
particular run would still not have been named: `Context::setCurrentDatabase`
deadlocks 139 lines before the process-list insertion in `executeQuery.cpp`, so
those threads were never in `system.processes` at all. Only the thread dump had
them, and the job already collects it. That server-side hang is a separate
change.

Related: ClickHouse#110626
@alexey-milovidov alexey-milovidov self-assigned this Aug 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 0997210 Aug 28, 2026
179 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 28, 2026
@groeneai

groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Correction (2026-09-26): point 2 below is wrong. GitHub concluded that job at 20:32:41Z with The self-hosted runner lost communication with the server, 9.6 minutes after the hung check failed and 64 minutes into its 3-hour budget: the stress container ran with no memory limit on a 61.65 GiB host while the server held 47 GiB RSS. #118057 (merged 2026-09-13) caps the container below host memory, so the teardown option below is moot. The offer in the last paragraph is superseded by #117995.


Follow-up measurement on the residual of this fix, from Stress test (arm_debug) job 100390573972
(PR #117742, head 049882702b3b8b3d). The job reported ERROR with no Result. I traced it end to
end and I do not think a further test-runner patch is the right call, so I am putting the numbers
here rather than opening a third PR on this path.

What the log shows. Two separate things go wrong, and only the first is what this PR was about.

  1. collect_build_flags (tests/clickhouse-test:5741) is refused with Code: 241, chunk
    1.00 MiB, would use 40.96 GiB against maximum: 47.07 GiB. Since would-use is below the
    maximum, the throw is the RSS arm of MemoryTracker::allocImpl (MemoryTracker.cpp:346), and
    the 1.00 MiB chunk is an untracked-memory flush batch: tests/config/users.d/memory_profiler.xml
    pins max_untracked_memory and memory_profiler_step to 1Mi. stress.py already asks for
    1Gi via --client-option, but clickhouse-test only forwards --client-option into the HTTP
    query string under --cloud (:7751 vs :7801), so on CI it reaches the native client and
    never the HTTP probes.
  2. The lost Result is not caused by that. stop_server ran clickhouse stop --max-tries 300 --do-not-kill from 20:23:04 to 21:08:38, which is 45m34s for 275 wait iterations, about 9.9 s
    per iteration for a loop whose sleep is 1 s: on a host with a 47 GiB server at its ceiling, the
    isRunning pid-file read and signal cost roughly ten times normal. The server did stop
    (21:08:42), and the job was cancelled 24 s later inside the post-stress restart. So the budget was
    consumed by teardown wall-clock, and the timeout 30m gdb path never ran.

Why I stopped instead of patching the probes. Raising the untracked limits cannot establish the
invariant it looks like it establishes. CurrentMemoryTracker.cpp:88-89 flushes when either the
per-thread limit is exceeded or the per-CPU budget cannot cover the deferral, and that budget is
max_per_cpu_untracked_memory, default 8 MiB, independent of the per-query settings. Separately,
authenticateUserByHTTP.cpp:71-76 and TCPHandler.cpp:2169-2171 run a size-0
CurrentMemoryTracker::check() before any query setting is applied, bypassed only by the server
setting users_to_ignore_early_memory_limit_check. That check is visible in the same job: the
teardown SYSTEM STOP DISTRIBUTED SENDS was refused three times with chunk of 0.00 B and
current RSS: 47.24 GiB above maximum: 47.07 GiB. So a client-side change can make the refusal
rarer but cannot remove it, and I would rather not add a third mitigation here.

The choices, as I see them. All of the real ones are yours, not mine:

  • Teardown: bound stop_server by wall clock so a Result is always written. This is the one that
    recovers the lost signal. It costs the deliberate --do-not-kill behaviour that exists so an
    abnormal exit is not misreported as a hung check, and stop_server is shared with
    upgrade_runner.sh.
  • Probes, if they should survive at all: users_to_ignore_early_memory_limit_check for the early
    check, plus disabling the per-CPU untracked bound for the flush. Both are tests/config changes
    that weaken memory accounting for every stateless and stress job, and neither covers the other's
    path.

For context, I have seen two other Code: 241 hung-check refusals on this path whose numbers point
at the other arm of the same check, with would-use far above RSS (66.67 GiB against 2.67 GiB, and
128.92 GiB against 1.18 GiB) rather than the RSS arm above. Those are a different mechanism from this
one, which is why I read the whole path as needing one policy decision rather than a patch per
signature.

One thing I can do without a decision, if you want it: when the hung check dies during its own
startup, as here, stress.py still writes Hung check failed, possible deadlock found, which claims
a deadlock was found when the processlist was never read. Reporting that case distinctly is small and
self-contained. Say the word and I will send it; otherwise I will leave this alone.

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants