Skip to content

Preserve hung_check.log on stress-test deadlock failure - #103551

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:stress-preserve-hung-check-log
Apr 27, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:stress-preserve-hung-check-log

Conversation

@groeneai

@groeneai groeneai commented Apr 26, 2026 •

Copy link
Copy Markdown
Collaborator

The stress test runs clickhouse-test --hung-check --capture-client-stacktrace after every job. When this detects long-running queries the runner collects the processlist and gdb backtraces of every server process and writes them all into hung_check.log. That log is the primary diagnostic evidence for any deadlock.

ci/jobs/scripts/stress/stress.py was deleting the log on exactly the failure path (hung_check_log.unlink()), leaving only the bare row Hung check failed, possible deadlock found\tFAIL\t\N\t in test_results.tsv. The result is that every "Hung check failed" entry in CIDB has an empty test_context_raw, the S3 artifact upload picks up nothing useful, and investigators have no way to tell which mutex / condvar / processor was stuck.

This change:

  • Keeps hung_check.log on disk so the artifact upload (process_results in ci/jobs/stress_job.py) includes it.
  • Embeds the last 32 KiB of the captured output as the 4th column of test_results.tsv. The tail is the relevant region (Found hung queries in processlist:, the processlist with stacktraces, and the gdb backtraces all print at the end). The encoding mirrors the decoder in read_test_results (tab and newline escaped to \t / \n).
  • The success branch (No queries hung) is unchanged.

This is the smallest infrastructure fix that unblocks investigation of the chronic "Hung check failed, possible deadlock found" stress-test umbrella (~290 hits / 30 days, multiple independent root causes) — the chronic task explicitly identified the deleted log as the blocker.

Requested by @alexey-milovidov on #100941

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

Preserve hung_check.log and embed its tail in test_results.tsv when the stress-test hung check fails, so that the captured processlist and thread stacktraces survive into CI artifacts and CIDB.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.122

When the stress-test hung check detects long-running queries after the
test run, `clickhouse-test --hung-check --capture-client-stacktrace`
collects the processlist and gdb backtraces from every server process
into `hung_check.log`. This is the primary diagnostic evidence for any
deadlock.

`stress.py` was deleting that log on the failure path
(`hung_check_log.unlink()`), leaving only the bare row
`Hung check failed, possible deadlock found\tFAIL\t\\N\t` in
`test_results.tsv`. As a result, every "Hung check failed" entry in
CIDB has an empty `test_context_raw`, and the artifact upload picks
up nothing useful — investigators have no way to tell which
mutex/condvar/processor was stuck.

This change keeps the log on disk so the artifact upload includes it,
and additionally embeds the last 32 KiB of the captured output as the
4th column of `test_results.tsv`. The tail is the relevant region
(processlist + thread stacktraces print at the end). Encoding mirrors
the decoder in `read_test_results` (tabs and newlines escaped). The
behavior on the success branch is unchanged.

Requested by @alexey-milovidov on
ClickHouse#100941

Session: cron:clickhouse-ci-task-worker:20260426-121500

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation (self-review)

# Question Answer
a Deterministic repro? Yes. End-to-end Python simulation: write a fake hung_check.log with realistic processlist + gdb stacktraces → run the new code path → read back via the same decoder used by process_results (line[3].replace("\\t", "\t").replace("\\n", "\n")) → confirm the original content is recovered byte-for-byte. Also covers: empty log, oversized log (50 KiB → truncated to 32 KiB tail with header), TSV row parses into 4 fields, \t and \n survive the round-trip.
b Root cause explained? Yes. clickhouse-test --hung-check --capture-client-stacktrace writes the processlist with per-query stacktraces and the gdb backtraces of every server process into hung_check.log (via tee). On the failure path stress.py calls hung_check_log.unlink() after writing only Hung check failed, possible deadlock found\tFAIL\t\N\t to test_results.tsv. So the bytes that explain the deadlock are deleted exactly when they would be useful, and CIDB receives an empty test_context_raw.
c Fix matches root cause? Yes. The fix removes the unlink() (so the artifact upload in process_results picks the file up) and additionally embeds the last 32 KiB of the captured output as the 4th column of test_results.tsv so the same evidence is also queryable from CIDB. No band-aid, no widened tolerance — the deletion is just removed.
d Test intent preserved? Yes. Behavior on the success branch is unchanged. The failure row in test_results.tsv keeps the same first three columns; only the previously-empty 4th column is now populated. The FAIL status, the test name, and the artifact upload all behave identically, just with the diagnostic content present instead of missing.
e Both directions demonstrated? Yes. End-to-end test confirms (1) the file persists on disk after the failure path runs, (2) test_results.tsv now contains the captured processlist/stacktraces in column 4, and (3) the existing decoder round-trips them losslessly. The pre-fix behavior (deleted file, empty 4th column) is what produced the chronic CIDB blind spot we're closing.
f Fix is general? Yes — there is exactly one site in the codebase that handles this log (verified via grep -n "hung_check" in ci/jobs/scripts/stress/), and the fix is applied there. It also covers every stress-test variant uniformly because stress.py is the shared entrypoint for all Stress test (*) jobs (regular + experimental serverfuzz across debug/asan/tsan/msan/release on amd and arm).

Session: cron:clickhouse-ci-task-worker:20260426-121500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv @leshikus — could you review this? Small change to ci/jobs/scripts/stress/stress.py that stops the stress-test runner from deleting hung_check.log on the failure path and embeds its tail in test_results.tsv so the captured processlist + thread stacktraces are visible from CIDB. Requested by @alexey-milovidov on #100941.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [53ac21e]

Summary: ✅


AI Review

Summary

This PR fixes stress-test deadlock diagnostics by preserving hung_check.log and embedding a bounded 32 KiB tail into test_results.tsv on hung-check failure, which directly addresses the prior loss of debugging evidence. The current implementation is focused and safe for this CI-script scope; I did not find additional actionable issues beyond the already-addressed inline bot feedback.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ➖
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 26, 2026
Comment thread ci/jobs/scripts/stress/stress.py Outdated
# investigators access to the complete diagnostic output.
info_field = ""
try:
log_text = hung_check_log.read_text(errors="replace")

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.

Reading the whole hung_check.log here can allocate a lot of memory exactly on deadlock cases, where this file may be very large (full processlist + multiple gdb backtraces). Since we only need the last 32 KiB, please read just the tail (seek from end and decode that chunk) instead of read_text on the full file.

Address the bot review on ClickHouse#103551:

> Reading the whole `hung_check.log` here can allocate a lot of memory
> exactly on deadlock cases, where this file may be very large (full
> processlist + multiple `gdb` backtraces). Since we only need the last
> 32 KiB, please read just the tail (seek from end and decode that
> chunk) instead of `read_text` on the full file.

The previous version called `Path.read_text` which loads the entire
file into memory. On a real stress-test deadlock the log can grow into
the tens or hundreds of MiB once the processlist of every hung query
and the `gdb` backtrace of every server process are included, and the
machine is already under memory pressure.

Switch to a bounded tail read: open in binary mode, `seek` to
`max(0, size - 32 KiB)`, read the remaining bytes, decode with
`errors="replace"`. When the file did not fit in the budget, drop the
likely-partial first line so the tail always starts on a line
boundary, then prepend the existing truncation header. Successful
parsing of the resulting `test_results.tsv` row was verified end-to-
end against the same decoder used by `process_results` (tab/newline
escape round-trip), for empty / 1 KiB / 30 KiB / 40 KiB / 250 KiB /
5 MiB synthetic logs.

Behavior on the success branch and the small-file path is unchanged;
only the resource profile of the failure path is improved.

Session: cron:clickhouse-ci-task-worker:20260426-161500

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in 53ac21e566d.

Replaced hung_check_log.read_text(errors="replace") with a bounded tail read:

tail_bytes_size = 32 * 1024
with open(hung_check_log, "rb") as f:
    f.seek(0, os.SEEK_END)
    size = f.tell()
    offset = max(0, size - tail_bytes_size)
    f.seek(offset)
    tail_bytes = f.read()
log_text = tail_bytes.decode("utf-8", errors="replace")
if offset > 0:
    nl = log_text.find("\n")
    if nl >= 0:
        log_text = log_text[nl + 1:]   # drop the partial first line
    log_text = (
        "(truncated; see hung_check.log artifact for"
        " the full output; showing last 32 KiB)\n...\n"
        + log_text
    )

So on a multi-MiB hung_check.log we now allocate ~32 KiB (the read buffer + the decoded str) instead of the whole file.

Verified end-to-end against the same read_test_results decoder (line[3].replace("\\t", "\t").replace("\\n", "\n")) for empty / 1 KiB / 30 KiB / 40 KiB / 250 KiB / 5 MiB synthetic logs — small files round-trip byte-for-byte; truncated files start on a line boundary and the body is a strict suffix of the original log. Tab and newline survive the TSV escape/decode round-trip on UTF-8 and on byte sequences that don't decode cleanly.

Thanks for the catch — the read pattern was indeed fragile on the very cases the PR is meant to surface.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Apr 26, 2026
@alexey-milovidov alexey-milovidov self-assigned this Apr 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 27, 2026
Merged via the queue into ClickHouse:master with commit bbbfc2c Apr 27, 2026
165 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 27, 2026
@groeneai groeneai mentioned this pull request May 15, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 23, 2026
The `info` field of a `Hung check failed, possible deadlock found` row is
meant to carry the hung-check verdict and the processlist with stack traces.
Measured on the public CI database over the last 30 days, over the rows named
exactly `Hung check failed, possible deadlock found`: of more than 500 such
rows only a handful contain `Found hung queries`, and not one of the 500-plus
marked truncated does; they carry `system.text_log` statistics instead. Every
informative row is untruncated, so the truncation path has never once
delivered evidence.

`clickhouse-test --hung-check` prints the verdict and the `ORDER BY elapsed
DESC` processlist near the start of the log (a 1,231-byte prelude on the
artifact this was measured against), and `reportLogStats` prints five
`system.text_log` aggregate tables at the end. Those tables are bounded in
rows (LIMIT 100/30/20/50), not in bytes: each row carries up to 256 chars of
sampled message text and an exception message drags its stack along. The
embed read the last 32 KiB, so the window always landed inside the statistics
and structurally could never reach the verdict. It landed so far inside them
that not one of those rows contains even a statistics table header.

That is worse than having no evidence, because the surviving text is
plausible. On the artifact in question `No queries hung.` sits at byte 1,265
of a 309,245-byte log while the window started at byte 276,477, and the field
instead showed a sampled UNKNOWN_TABLE exception's throw-site stack from the
`Top messages not matching their format strings` table. That stack reads
exactly like a hung query's stack and was investigated as one.

Read the first 32 KiB instead. The bound is kept: one read of the budget plus
one byte from offset 0, no stat and no seek to end, which is what the review
on ClickHouse#103551 asked for. `--report-logs-stats` is kept as well, and reading the
head is not a compromise with it: this restores the shape Alexander Tokmakov
shipped in 472aa12, which embedded the log through `head_escaped` with
`--report-logs-stats` already in the same argument list (he had added it five
weeks earlier in f2b1778). `85deff3297117e6` dropped the embed when it
moved the row into `stress.py`, and ClickHouse#103551 re-added it from the tail.

The trailing partial line is kept rather than trimmed to a line boundary.
A tail window starts mid-line with no context, so dropping its first line is
right; a head window starts at byte 0 and needs no symmetric step. It would
also be harmful: `system.processes.query` is an unbounded String and Vertical
does not escape values, so one hung query is one line of arbitrary length.
On a fixture whose oldest query's line is 40,042 bytes, dropping the last
line yields 125 bytes and erases the entire processlist.

Content-based windowing was considered and rejected. `reportLogStats` prints
its header after running its query, inside a swallowing try, so a throw from
`SYSTEM FLUSH LOGS` leaves no header at all; and a fuzzed query text can
reproduce any boundary token including its delimiters. A parser could then
anchor on a query-supplied copy and truncate the diagnostics it exists to
preserve, silently, in exactly the scenario that matters.

The logic moves into `build_hung_check_info` so it is testable. It was inline
in `main()` before, which is why the defect shipped and survived hundreds of
rows.
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 23, 2026
The throttle test asserted that some `sleep` call existed somewhere under the
polling loop. That is not the contract, and four mutants prove it: `sleep(0)`
passed, `sleep(0.0001)` passed, and a `sleep(1)` moved into the
`hung_count == 0` branch, which is the one path never taken while queries are
hung, passed as well. A sub-second interval is worse than no throttle at all:
it emits hundreds of thousands of tokens inside the deadline and busy-spins the
probe query against a server just declared possibly deadlocked.

Assert the properties that make the throttle work instead: the sleep is a
direct body statement of the loop rather than nested in a branch, its interval
is a literal of at least one second, and it follows the zero-hung break, so it
paces the probes exactly on the path where the tokens compete with the verdict.
One second is what makes the 90-second deadline yield 90 probes and 180 bytes.

Nothing pinned that `main()` still routes the `info` cell through
`build_hung_check_info` either. Every other test calls the helper directly, so
reverting the call site alone reinstates the tail read with the whole suite
green. Moving the read into a helper is what opened that gap; it used to be
inline and therefore trivially wired.

`main` is not callable in isolation, since it parses arguments, queries a live
server and runs the functional tests before reaching the embed. Pin it
statically instead, and pin the data flow rather than the shape alone: three
further mutants passed a shape-only test. Handing the helper the results TSV
instead of the log, assigning `info_field = ""` after the helper call, and
dropping the interpolation from the emitted row each left the field empty or
wrong with every test green, and the second of those is the pre-ClickHouse#103551 state
this change exists to undo. So the test now requires the helper to receive
`hung_check_log` by name, requires the nested
`escape_tsv_info(build_hung_check_info(...))` to be the last write to
`info_field` rather than merely present, requires the row to interpolate that
name, and keeps requiring that no seek is left at the call site.
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.

3 participants