Skip to content

Collect SQL stacktraces on the hung-check and server-died abort paths - #113059

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/sql-stacktraces-on-hung-check-abort
Aug 29, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/sql-stacktraces-on-hung-check-abort

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 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

On an ASan build, a stateless run aborting on the hung check records no stack of the hung server:

Hung check failed: server is not responding
Cannot collect C stacktraces under ASan: debugger attach is disabled.

Two things combine. print_c_stacktraces declines to attach lldb on ASan builds because ptrace disables LeakSanitizer; that refusal is correct and stays. And print_sql_stacktraces, needing no debugger, was unreachable: its pre-check check_server_liveness probes HTTP (http_port), while it collects over native TCP (args.client --port=). Different listeners, so this signature (alive, not answering HTTP, TCP still serving) failed the gate, and the hung-check site did not call it at all.

This drops the mismatched pre-check and lets the collector be its own liveness test: it is bounded (timeout=30) and reports failure as one trimmed line, so a dead socket cannot re-emit the Code: 210 tracebacks that motivated the pre-check. The dump is added to the four abort sites that had only the C path: hung check, server died, the liveness-check failure that master split out of server died in #115080, and the startup check.

Both jobs keep attaching the dump and now clear any left by a previous run in the same workspace, so an aborted run cannot upload a stale dump as its own; in fast_test a server-start failure reaches the attach without running a test. #114143 has since added the same attachment upstream, so this uses the equivalent helper rather than attaching twice.

It fixes no hang and does not restore C++ stacks on ASan.

Validated on the merged head: with HTTP dead and TCP live, master writes 0 bytes where this writes 356517 carrying thread_name and query_id; aimed at a dead socket it returns at once, writing and raising nothing. Prompting report.

Related: #42701
Related: #112265
Related: #114143
Related: #114675


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

groeneai and others added 5 commits August 2, 2026 12:04
On an ASan build, a stateless run that aborts on the hung check records no
stack of the hung server anywhere:

    Hung check failed: server is not responding
    Cannot collect C stacktraces under ASan: debugger attach is disabled.

Two things combine to produce that. print_c_stacktraces declines to attach
lldb on ASan builds, because a ptrace attach disables LeakSanitizer for the
rest of the process; that refusal is correct and stays. And
print_sql_stacktraces, the collector that needs no debugger at all, was
unreachable in this state: its availability pre-check went through
check_server_liveness, which probes HTTP on http_port (default 8123), while
the collector itself shells out to args.client on the native TCP port
(default 9000). Those are different listeners on different ports served by
different code paths, so a server whose HTTP endpoint is wedged or whose
handler pool is exhausted while TCP still answers queries failed the gate and
was never asked. That is precisely the reported signature: the process alive,
not responding. The hung-check abort site did not call the SQL collector in
the first place, and neither did the FailureReason.SERVER_DIED site.

Drop the pre-check and let the bounded TCP query be its own liveness test.
The reason the pre-check existed was to keep "Code: 210 Connection refused"
tracebacks out of every failed run, and that concern is now covered where it
belongs: get_stacktraces_from_clickhouse runs under shell_get_output with
timeout=30, which caps a dead or wedged socket at 30 seconds and reduces a
failure to a single trim_for_log-bounded stderr line with no traceback. The
existing "if bt:" guard still means nothing is written and nothing is claimed
when nothing was collected; an else branch now records that the attempt was
made, so "tried and got nothing" is distinguishable from "never tried".

Then add the SQL dump to the two abort sites that had only the C path. It
goes before the C dump for the reason the per-test timeout handler documents:
dump while the client connections are still up, because once they drop the
server cancels the wedged queries and their threads disappear.

A server-side alternative was considered and rejected. Sending SIGTSTP so the
server logs its own stacks would work mechanically, but onFault emits its
report at LOG_FATAL, check_fatal_messages_in_logs greps for any <Fatal> line
and appends a result carrying Result.Label.BLOCKER, and FuzzerLogParser
classifies "Received signal" as a signal failure. The diagnostic would have
manufactured a merge-blocking failure out of itself, which is worse than the
present silence. Teaching those scanners a benign exception was rejected too:
six independent consumers key on those strings, so it would weaken real-crash
detection in six places for a diagnostic gain. Nothing in this change writes
to the server log.

This does not fix any hang, and it does not restore C++ stacks on ASan
builds. What it changes is that a server alive but not answering HTTP now
yields the full system.stack_trace view with per-thread thread_name and
query_id, which identifies the query that wedged the server.

Measured on a live server, with HTTP dead and TCP live: master skips and
writes nothing, this change writes a 357 KB sql_stacktraces.log carrying
thread_name and query_id. An abort with HTTP wedged rather than closed gets
9.7 seconds faster, because the pre-check itself blocked for 10 seconds and
then collected nothing; the worst case is 20 seconds slower when both
transports are wedged, bounded by timeout=30. Green runs are unaffected,
since no caller runs on a passing test.

Regression coverage goes in the existing ci/tests/test_print_stacktraces.py.
The oracles key on the sql_stacktraces.log artifact and its columns, or on
per-site call order, never on stdout: the unfixed code, the rejected
call-site-only variant, and print_c_stacktraces all print lines, so a test
asserting that some output appeared would pass in every case and measure
nothing. The two abort sites are asserted independently, because the per-test
timeout handler and the end-of-run hung-query check already called both
collectors and would otherwise mask a revert of either new site.

Related: ClickHouse#42701
Related: ClickHouse#112265
Collecting a dump is only half a diagnostic: the stateless job never
attached either stacktrace log, so the dump landed at the harness cwd
(no `cd` in its test command, unlike fast_test's) where nothing uploads
it and `*.log` is gitignored, and it died with the runner. Only
`ci/jobs/fast_test.py` had this wiring.

The dumps are also appended to, and being gitignored they survive the
`git clean -ffd` in `Runner._pre_run` (an ignored file does not even
mark the repo dirty, so that clean often does not run). One left by a
previous job in a reused workspace would be uploaded as if this run had
aborted, which is worse than silence. They are cleared once at
TEST-stage entry, mirroring the existing `test_output_file` unlink;
append mode is deliberate, since a job makes several runs whose dumps
must accumulate.

Three oracles in ci/tests/test_print_stacktraces.py could have gone
vacuous without failing:

- `_abort_site` picked the innermost `if` by unparsed source length,
  a proxy for nesting with a 5-character margin over an unrelated
  candidate. One added comment flipped the selection while the test
  kept passing, silently ending the per-site independence it exists
  for. It now selects by nesting depth and pins the selected `if`'s
  condition, so a moved site fails loudly instead.
- the server-log test asserted inside a loop over a glob that does not
  exist outside the CI fixture, so an empty glob meant zero assertions
  and a green result. It now asserts the fixture is present, naming the
  path; this guards the invariant that ruled out a server-side
  self-dump, since `check_fatal_messages_in_logs` turns any `<Fatal>`
  line into a merge blocker.
- the wedged-socket test asserted only that the call finished under a
  ceiling, which a fast failure also satisfies while exercising the
  connection-refused path another test already owns. The fixture now
  reports its accepted connections and the test requires one, with the
  client pinned to the fixture's IPv4 bind.

Fourteen mutation arms each redden their own test for its own reason;
one is deliberately green, asserting that a no-op statement inserted
into an abort block does not change which statement is selected.
…ar runs first

Two oracles asserted the shape of the change rather than the property it
exists to deliver, so both could stop testing anything silently.

The line that attaches the dumps to the job result had no test: deleting
`debug_files += collect_stacktrace_logs(...)` left the whole suite green,
which is the same "collected but never attached" gap the attach was added
to close. Assert it as a tree rather than a substring search, because the
property is positional: the append must sit inside the collect-logs stage,
the list it appends to must be the one `Result.create_from` uploads, and it
must run before that result is built. A text search passes with the append
relocated after the upload.

The stale-dump clear was asserted only to appear somewhere in the test
stage. Relocating it later in that stage kept the test green while the job
deleted this run's own dumps moments before attaching them, which is worse
than the stale dump it prevents. Assert that it precedes the first
`run_tests` call.

Five mutation arms, one per assertion, so no leg is an assertion nothing
can redden: deleting the append, appending to an unused list, moving the
append out of the stage, building the result before the stage, and
relocating the clear.

Co-Authored-By: Claude Fable 5 <[email protected]>
…est run

Both ends of the dump lifecycle were guarded by a condition that varies
independently of whether a dump exists and gets uploaded, and each failed in
the opposite direction.

The stale-dump clear sat inside `if res and JobStages.TEST in stages:` while
the attach carried no `res` conjunct. `res` becomes False on any setup failure
(installing ClickHouse, or any step of starting the server), so such a run
skipped the clear and still reached the attach: a dump left by a previous job
in a reused workspace was uploaded as if this run had aborted. `clickhouse-test`
opens these files in append mode and the paths are gitignored, so `git clean
-ffd` does not remove them. A setup-failure report carrying an unrelated job's
abort stacktrace is worse than one carrying none.

The attach sat inside `if JobStages.COLLECT_LOGS in stages:`, a stage that
per-test-coverage jobs and local runs remove outright, so those jobs could
never upload a dump at all even though they pass `--hung-check` like any other.

Both now run under stage membership alone: the clear keyed on the test stage,
so a deliberate resume at `--param collect_logs` still preserves the dump it
was resumed to collect, and the attach as a top-level statement immediately
before the single result that uploads it.

The tests assert placement, not just presence: the clear's guard must not test
`res`, and the attach must not be nested inside any stage-membership branch.
The previous oracle asserted the attach was inside the collect-logs stage,
which encoded the defect, so it is retargeted rather than removed. Each
assertion is checked against a mutation that reddens it alone, including one
new arm for the upload assertion, which turned out to have had none.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The upload half of this change rests on the dumps landing at the harness
cwd, outside the server log directory prepare_logs globs, and nothing
asserted that. Both neighbouring tests are blind to it: one selects the
attach by call shape and never reads its arguments, the other calls the
collector with a temporary directory of its own. Passing temp_dir at
either production site therefore kept all 17 tests green while the attach
uploaded nothing and the clear deleted nothing.

That is not a hypothetical wrong turn. temp_dir is where this job puts
every other artifact, and fast_test attaches these same two dumps from
there - correctly, because its runner command prefixes cd {temp_dir},
while this job's does not. The sibling precedent points at the wrong
constant here, so the asymmetry is the invariant and it was unpinned from
both ends.

The new test asserts both halves, since either alone is defeatable: that
main makes exactly two collect_stacktrace_logs calls and each names
Utils.cwd(), and that no clickhouse-test command string in the module
changes directory. Adding a cd defeats the first half alone; changing an
argument defeats the second alone.

Verified with five mutation arms, each reddening this test alone with a
diagnostic naming the mechanism: the attach or the clear pointed at
temp_dir, a cd added to either clickhouse-test command with the arguments
left untouched, and a spurious third call.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 gate rounds over the
branch, 5 findings total; plus my own cold review of the resulting code each round).

# Sev Finding Verdict Evidence / action
1 ⚠️ The SQL dump can be attempted where the pre-check previously short-circuited, so the abort path must stay bounded and non-raising (tests/clickhouse-test:1246) AGREE, fixed @ 5169c6c Kept the collector's timeout=30 load-bearing and asserted it: a closed socket yields no artifact, no traceback, one bounded line; a socket that accepts and never answers stays under the bound, with the accepted-connection count asserted so the test cannot silently degenerate into the connection-refused case.
2 ⚠️ Collected but never attached: the dumps land at the harness cwd, outside the server log directory the job globs, so nothing uploads them (ci/jobs/functional_tests.py) AGREE, fixed @ 5eb3d51 Added collect_stacktrace_logs plus the attach into debug_files, and pinned both halves: what the collector returns, and that its result reaches the uploaded list before the result is built.
3 ⚠️ A dump left by a previous job in the same workspace would be attached to a green run as if it had aborted AGREE, fixed @ 961902d The paths are gitignored, so git clean -ffd keeps them and clickhouse-test appends. Added a clear on TEST-stage entry, asserted to precede the first test run.
4 ⚠️ The clear sits under a guard that a setup failure skips, while the attach does not, so exactly those runs upload an unrelated job's dump AGREE, fixed @ 9b995bc Moved the clear outside that guard and asserted the guard it now runs under, reading the function as a tree rather than as text so the assertion is positional.
5 ⚠️ Nothing asserted which directory the clear and the attach scan, so pointing either at the job's temp directory kept every test green while the attach uploaded nothing AGREE, fixed @ 507c6cf This one had real pull: the sibling fast test attaches these same two files from its temp directory, correctly, because its runner command changes directory first and this job's does not. The asymmetry is the invariant and it was unpinned from both ends. Now asserted from both: the directory each call names, and the absence of a directory change in either test command. Verified with five mutation arms, each reddening the new test alone.
6 ⚠️ Follow-up on 5: redirecting the subprocess through the runner's own cwd parameter would move the dumps while both collectors still scan the harness cwd, and the new test would stay green DISAGREE The mechanism is possible; the harm is not. It is fail-closed twice. The command passes a relative --queries ./tests/queries, which under that redirect resolves inside the job temp directory, where it does not exist; because --queries is given explicitly, the search-path fallbacks are skipped and clickhouse-test aborts at once with a message naming the missing directory. The same redirect would also strand every client core dump, since client_core_path is set from the same cwd three lines earlier for exactly this reason. And the parameter appears nowhere in ci/: the repo's chdir idiom is a context manager used only by the release scripts. A test earns its keep by catching what would otherwise ship silently; this cannot ship at all. Its proposed remedy would also require adding that parameter to production to assert a property the code already has by default.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260803-052000

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and not probabilistic at all: the defect is a state the availability gate mishandles by construction. Point the runner's http_port at a closed port while args.client keeps the live TCP port, then call print_sql_stacktraces. Reproduces in under 1 second, every time.
b Root cause explained? Yes. print_sql_stacktraces gated a native-TCP collector (args.client --port=<tcp_port>, default 9000) behind an HTTP probe (check_server_liveness to clickhouse_execute_http on http_port, default 8123). Different listeners, different ports. A server alive but not answering HTTP failed the gate, so the collector never ran; and the hung-check abort site called only print_c_stacktraces, which returns early on every ASan build to keep ptrace away from LeakSanitizer. The refusal was therefore total.
c Fix matches root cause? Yes: the mismatched gate is removed in the function that owns it, so every caller gets a gate that predicts its own collector. Two weaker designs were rejected first. Sending SIGTSTP for a server self-dump writes <Fatal> lines, and check_fatal_messages_in_logs turns any of those into a merge-blocking failure, so the diagnostic would manufacture a blocker. Adding the calls without touching the gate collects nothing on this failure, because the collector's own pre-check re-runs the probe that just failed. No widened bound, no no-random-* tag, no defensive check over an upstream bug.
d Test intent preserved / new tests added? Yes. All four pre-existing tests in ci/tests/test_print_stacktraces.py pass unchanged; fourteen were added, for 18 total. Every oracle keys on the artifact sql_stacktraces.log and its thread_name / query_id columns, on per-site call order, on the placement of the clear and the attach, or on the job's collected file list. That is deliberate: the unfixed code, the rejected band-aid, and print_c_stacktraces all print lines, so an oracle keyed on stdout would pass in all of them and measure nothing. Four oracles that could have gone vacuous were hardened: the abort-site selector now keys on nesting depth and pins the selected condition, the server-log test asserts its fixture exists instead of iterating an empty glob, the wedged-socket test asserts a connection was accepted rather than only that it finished fast, and the upload assertion gained the arm it turned out never to have had. One earlier oracle asserted the attach sat inside the collect-logs stage, which encoded the mode-dependence defect below, so it was retargeted rather than deleted. A last oracle pins the directory the clear and the attach scan, an axis every other test in the file is blind to: one matches the attach by call shape without reading its arguments, another calls the collector with a temporary directory of its own. It asserts both halves of that invariant, since either alone is defeatable: that both calls name the harness cwd, and that no clickhouse-test command string changes directory, which is what makes the harness cwd the right answer here and temp_dir the right one in fast_test.
e Both directions demonstrated? Yes, on a live server, same command, only the file version differing. With HTTP dead and TCP live, master prints Skipping system.stack_trace query: server is unreachable. and writes no artifact; this branch writes a 357 KB sql_stacktraces.log carrying thread_name and query_id. Twenty-five mutation arms each redden their own test for its own reason: restoring the pre-check, reverting each abort site independently (two arms), dropping the 30 s bound (300 s observed), swapping the dump order, dropping the "collected nothing" line, moving an abort site, hiding the server logs, dropping the upload guard, blanking the collector, renaming one dump, making the blackhole refuse to connect, deleting the stale-dump clear, relocating that clear past the run it protects, putting it back under the res guard, deleting the attach, attaching to a list nothing uploads, putting the attach back inside the collect-logs stage, moving it after the result that uploads it, dropping debug_files from that result, pointing the attach at temp_dir instead of the harness cwd, pointing the clear there, adding a cd to each of the two clickhouse-test command strings (two arms, which redden the no-cd leg with the argument left untouched), and adding a third collect_stacktrace_logs call. One further arm is deliberately green: inserting a no-op statement inside an abort block must not change which statement the selector picks.
f Fix is general across code paths? Yes. Fixed at the owning function, so all four callers benefit at once; both abort sites that had only the C path get the dump (hung check, SERVER_DIED). The two callers that already had it were measured rather than assumed. Collecting is only half a diagnostic, so the job that runs this check now attaches the dump to its result as fast_test already did, and clears any dump a previous job left in the same workspace: the writes append, and the paths are gitignored so git clean -ffd keeps them, which would otherwise attach a stale dump to a green run. Both ends of that lifecycle are bound to stage membership alone, not to the happy path they were first written against: the clear was inside if res and JobStages.TEST in stages: while the attach has no res conjunct, so a setup failure skipped the clear and still reached the attach and uploaded an unrelated job's dump as this run's; and the attach was inside JobStages.COLLECT_LOGS, a stage that per-test-coverage jobs (8 in production) and local runs remove outright, so those runs could never upload a dump at all. Keying the clear on the test stage rather than on res also keeps a deliberate --param collect_logs resume from deleting the dump it was resumed to collect. The startup-failure site is deliberately left alone, since a server that never served a query cannot answer on TCP either, and spending 30 s to print nothing would be the only effect.
g Fix generalizes across inputs? Yes for this diff's input space, which is transport state rather than data: {live, closed, wedged} across HTTP and TCP, five reachable combinations, each measured in both code versions. The collector's three query branches were enumerated, and the branch this job takes was identified from the CI option table: distributed plan maps to --distributed-plan, a settings flag, so replicated_database and shared_catalog are both false and the non-cluster branch runs. No types, columns, or settings are involved.
h Backward compatible? Yes, trivially. No setting, no serialization format, no protocol, no user-visible behavior; SettingsChangesHistory.cpp is not involved. The only behavior change is inside a CI harness diagnostic on abort paths.
i Invariants and contracts preserved? Yes. An abort path must never raise and must stay bounded. Nothing raised in any measured invocation, including both wedged-socket arms, and the 30 s bound holds, which the mutation arm proves is actually asserted. The if bt: guard still gates the write, so nothing is claimed when nothing was collected. The intent behind the original pre-check, not emitting garbage against a dead socket, is preserved by shell_get_output's bounded one-line failure path: measured 2 stderr lines and no traceback on both a closed and a wedged socket. One further invariant now holds explicitly: a green run attaches no stacktrace artifact, so an uploaded dump always means this run aborted.

No 50/50 randomized run: this diff touches no query path and no file under tests/queries/, so settings randomization has nothing to perturb in it and a green sweep would carry no information. Substituted with 4 serial suite runs and 4 concurrent copies on the final tree, all 18 tests green in each, plus the twenty-six mutation arms.

Session id: cron:clickhouse-impl-slot-45:20260803-000700

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? On an ASan build the hung-check abort recorded no server stack at all: the C dump declines to attach a debugger there, and the SQL dump gated a native-TCP collector behind an HTTP probe, so the one signature that matters (alive, not answering HTTP, TCP still serving) failed a gate that could not predict it. This drops the mismatched gate, adds the dump to the two abort sites that had only the C path, and makes the stateless job attach the dump as fast_test already does.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d16049]

Summary: ✅


AI Review

Summary

This PR extends print_sql_stacktraces to the remaining abort paths and makes the CI jobs attach the resulting dump artifacts, which addresses the HTTP-vs-TCP mismatch at the core of the original report. That part looks directionally right, but one correctness gap is still open: the SQL dump still inherits the current test database from the client session, so it can silently stop working in exactly the abort scenarios this PR is trying to improve.

Findings

⚠️ Majors

  • [tests/clickhouse-test:1333-1339] print_sql_stacktraces is not actually its own liveness test once a test has dropped CLICKHOUSE_DATABASE. args.client inherits --database from the environment at tests/clickhouse-test:7149-7152, get_additional_client_options can add another one at tests/clickhouse-test:6431-6438, and get_stacktraces_from_clickhouse reuses both unchanged at tests/clickhouse-test:1088-1129. The HTTP helper already hard-codes database=system for this exact “test may have removed its DB” case at tests/clickhouse-test:650-652. As a result, a hung-check or SERVER_DIED / LIVENESS_CHECK_FAILED abort after DROP DATABASE {CLICKHOUSE_DATABASE} can still return “Collected no stacks” with TCP healthy, losing the only dump that carries query_id. Suggested fix: force this collector onto the system database after composing its client options, or strip inherited --database from both carriers before issuing the query, and add a focused regression for the dropped-database case.
Final Verdict

Needs one more fix before merge: make the SQL stacktrace collector independent of the current test database, not just of the HTTP liveness probe.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 3, 2026
Comment thread tests/clickhouse-test Resolved
`check_server_started` probes HTTP (`clickhouse_execute` ->
`clickhouse_execute_http` on `http_port`), while `print_sql_stacktraces`
collects over native TCP through `args.client`. So its failure branch had the
same transport mismatch this PR removes from the other two abort sites: it
printed only `print_c_stacktraces`, which self-skips on ASan builds, leaving
an `amd_asan_ubsan` startup failure with no server stack at all.

The job's own earlier TCP probe does not cover this. `ClickHouseProc.wait_ready`
runs `clickhouse-client ... "select 1"` inside the START stage, whereas
`clickhouse-test` is launched later, in the TEST stage. It therefore proves TCP
was alive at an earlier instant, not that TCP is dead when the HTTP probe later
fails; an HTTP-only wedge in between reaches this branch with TCP still serving.

The call is safe here: `args.client` is assigned before `main` runs, and
`get_stacktraces_from_clickhouse` is bounded (`timeout=30`) and never raises,
because `shell_get_output` returns "" on both `CalledProcessError` and any
other exception. Same bounded-cost argument as the two existing sites.

Verified both directions with mutation arms: reverting this one line, or
swapping the two collectors at this site, reddens the new test alone; reverting
the hung-check site reddens only its own test.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 3, 2026
…races-on-hung-check-abort

# Conflicts:
#	ci/tests/test_print_stacktraces.py
…races-on-hung-check-abort

Resolved one conflict in ci/jobs/functional_tests.py. Master gained an inline
attach of sql_stacktraces.log / c_stacktraces.log to debug_files (azat,
c57b5d8, ClickHouse#114143) at the same point where this branch attaches them via
collect_stacktrace_logs(). The two blocks resolve to an identical file set from
the same directory, so keeping both would attach each dump twice. Kept this
branch's helper, which is the tested form (ci/tests/test_print_stacktraces.py
pins the call count, the scanned directory and the attach position) and which
also clears stale dumps on TEST entry; dropped the duplicate inline block.

Master's own changes to the file are unaffected: allow_oversubscription,
attach_post_verdict_artifacts, the seaweedfs rename, the failure allowance and
the llvm-profdata-22 detection are all present.
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d160494b with master ecc01ef26 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8f281591c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.35 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

The test proved print_sql_stacktraces appends nothing to the server log by
globbing clickhouse-server*.log out of ci/tmp/var/log/clickhouse-server and
comparing sizes. That directory is emptied mid-session: test_e2e's
test_fuzzer and test_stress rename ci/tmp to ci/tmp_backup, run a praktika
sub-job and restore it in a finally block, but the sub-job's
Runner._pre_run runs `git clean -ffd`, and ci/tmp_backup, unlike ci/tmp, is
not gitignored. The backup is deleted and the restore silently no-ops. The
server survives holding its deleted log files open, so the other tests kept
passing while the glob was empty -- and once the emptiness was asserted
rather than skipped, CI Tests went red.

Watching the server's log files cannot be made reliable here. The CI fixture
copies programs/server/config.d wholesale, including log_to_console.xml,
which removes logger.log and logger.errorlog, so the server reports no file
sink; the harness directory it writes into instead is the one that gets
deleted; and after the rename its descriptors keep writing to the unlinked
inodes, so no reachable path sees its output.

Record what the collector itself does instead: every path it opens for
writing, and every process it signals. The write set must be exactly its own
artifact, and it must signal nothing, since signalling the server makes
BaseDaemon dump <Fatal> records from its own process where no in-process
check could see them. Both are properties of the collector rather than of
the environment, so they hold however the fixture is configured, and they
are stricter than the size comparison: a write to any path fails, including
one no glob would have covered.

Verified against a server started the way ClickHouseService starts one,
including log_to_console.xml. The file passes with the log directory intact,
emptied, and with ci/tmp renamed away. Mutants writing to the server log
directory, to stderr.log, to an unrelated path, putting <Fatal> in the
artifact, sending SIGTSTP to the server, calling killpg, and making the
collector a no-op each fail a distinct assertion.
Comment thread ci/jobs/functional_tests.py Resolved
The stateless job clears sql_stacktraces.log and c_stacktraces.log on TEST
entry so an aborted earlier run cannot have its dump uploaded as this run's.
fast_test attaches the same two files from the same persistent ci/tmp and had
no equivalent clear, so the invariant held for only one of the two
clickhouse-test jobs.

clickhouse-test appends to these files, and ci/tmp is gitignored, so the
git clean -ffd in Runner._pre_run keeps whatever a previous run left there.
Verified in a scratch repo: the clean removes an unignored sibling but keeps
both dumps under ci/tmp. attach_debug is set True when CH.start() or
CH.wait_ready() fails, which is upstream of the only CH.run_test call, so
that path reaches the attach having written no dump of its own and uploads
the stale one. The clear therefore sits outside the res guard, like the
stateless job's.

Both sites now iterate one module-level tuple rather than repeating the
literal, so they cannot drift apart and leave the clear deleting something
the attach does not upload.

Three tests read fast_test.main as a tree: the clear exists and precedes the
test run, it is guarded by stage membership and not by res, and both sites
iterate the same tuple and join it against the same directory. Each fails on
unfixed code, and mutants that move the clear after the test run, put it
under res, point it at the repo root, revert the attach to a literal tuple,
or drop a name from the tuple each redden one test and leave the others
green.
Comment thread tests/clickhouse-test Outdated
callers honest: they can invoke this from any context (per-test
timeout, end-of-run hung-check) without first checking whether the
server still responds.
No availability pre-check: this query goes over native TCP, so an HTTP

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.

print_sql_stacktraces is still not actually its own liveness test when the current test database has been dropped. get_stacktraces_from_clickhouse builds the native-client command from args.client plus get_additional_client_options(args), and both can carry --database=$CLICKHOUSE_DATABASE. The HTTP-side infrastructure query path already hard-codes database=system for hung-checks (tests/clickhouse-test:642-645) for exactly this reason.

That means a test that does DROP DATABASE {CLICKHOUSE_DATABASE} and then wedges HTTP or trips SERVER_DIED still reaches this new caller with TCP healthy but no usable current database, so clickhouse-client exits before it can read system.stack_trace. Please force this collector onto system (or strip inherited --database from the extra client options too) and add a regression around a dropped current database.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b512cec

CI is fully finished on this commit with no failing checks, so there is nothing to own.

Check / test Reason Owner / fixing PR
(none failing) - -
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260813-233000

Resolves a modify/delete conflict on ci/tests/test_print_stacktraces.py by
taking master's deletion.

That file was removed from master in ClickHouse#114675 ("Remove unit tests for CI
scripts"), which deleted 71 files under ci/tests/ on the grounds that they are
not run automatically, and added to .claude/CLAUDE.md that committed CI-script
tests are not wanted. Across six restore rounds in that PR, 46 suites were
restored as live safety or merge-gate coverage; this one was not. Re-adding it
here would partially revert a merged decision, so master's side stands.

Nothing retained in master references the file, and it only imported from
tests/clickhouse-test, never the reverse, so the deletion is self-contained.

The fix itself is unaffected: it lives entirely in ci/jobs/fast_test.py,
ci/jobs/functional_tests.py and tests/clickhouse-test, and master still carries
the HTTP pre-check this PR removes plus none of the three added abort sites.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict, and took master's side on the one conflicting file.

ci/tests/test_print_stacktraces.py was deleted from master in #114675, which removed 71 suites under ci/tests/ as not automatically run, and added to .claude/CLAUDE.md that such CI-script tests need not be committed. Of those 71, 46 were restored during that review as live safety or merge-gate coverage; this one was not. Re-adding it here would partially revert a merged decision, so it stays deleted. Nothing in master references the file, and it only imported from tests/clickhouse-test, never the reverse.

The fix is unaffected: it is entirely in ci/jobs/fast_test.py, ci/jobs/functional_tests.py and tests/clickhouse-test, and this is now a 3-file, +53/-15 change. Master still carries the HTTP pre-check this removes and none of the three added abort sites, so nothing here is superseded.

Since the deleted suite is what used to pin the behaviour, I re-verified the three mechanisms against the merged head (debug build 26.8.1.1, Build ID 09e3d57a4bbe30cdd47e636647d1e612a3935da6; server TCP live, port 20798 confirmed closed and used as the dead HTTP endpoint; helper loaded via runpy without __main__, i.e. the macOS-spawn import condition):

Case master this branch
HTTP down, TCP live Skipping system.stack_trace query: server is unreachable., no artifact sql_stacktraces.log, 351843 bytes, with thread_name and query_id
collector aimed at a closed port - one line Collected no stacks from system.stack_trace., no exception, 0.1 s (bound is 30 s)
stale-clear and attach - cleared outside the res guard in both jobs; exactly one attach path per job, so #114143 cannot double-attach

Coverage loss from the deletion is real: those three cases are no longer pinned by a committed test. I have not restored the suite, per the policy above, but say the word and I will.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 83188f6

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Code Review infra - gh auth login returns HTTP 401 Bad credentials for both robot tokens, so the job's own 3-attempt rotation is exhausted in 11s (the 401 is intentionally non-retryable in _GH_AUTH_RETRY_ERRORS) a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
CH Inc sync private CH Inc sync (private, not actionable by us)

Coverage is real, verified with the praktika DROPPED-token test rather than the skip ratio:
result_pr.json reports 0 DROPPED, 57 leaves OK with real durations, 119 SKIPPED, 1 FAIL.
CIDB corroborates on this exact head: ~370k test rows across 84 checks, zero FAIL/ERROR.

Not PR-caused: the diff is ci/jobs/fast_test.py, ci/jobs/functional_tests.py and
tests/clickhouse-test only, none of which the Code Review job's authentication path reads.
Breadth in the same window is 18 distinct PRs, against 203 distinct PRs where the same check
passed, so the credential failure is fleet-wide and intermittent rather than specific to this PR.

Note this head has two run attempts: Code Review passed on attempt 1 at 13:33Z and failed on
attempt 2 at 17:59Z, so the per-attempt result differs for the same commit.

Session id: cron:our-pr-ci-monitor:20260817-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Code Review gh-auth 401 failure created: #115232

The 401 came from one permanently dead robot token, and the Codex backend never used the token it was authenticating: enable_gh_auth=True already mints the app credential the agent runs on. #115232 removes that login from the Codex attempt.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
master split FailureReason.SERVER_DIED into SERVER_DIED and
LIVENESS_CHECK_FAILED (ClickHouse#115080), and re-routed three of the four former
SERVER_DIED sites to the new reason. The condition this branch covered
through the SERVER_DIED abort site now arrives as LIVENESS_CHECK_FAILED,
so the SQL dump is added at that site too; a textual union merge would
have left the new path collecting C stacks only, silently dropping the
query_id mapping this branch exists to provide.

Both abort sites claim the stop cause before collecting, per master's
ordering invariant: collection can block ~30s per server process, and a
cause claimed afterwards loses to any cause claimed during it.

Kept this branch's removal of the liveness pre-check in
print_sql_stacktraces. The pre-check probes HTTP while the dump runs over
native TCP, so a failed probe does not predict whether the dump can run,
and get_stacktraces_from_clickhouse is bounded and never raises. Adopted
master's "liveness check failed" wording, which names the observation
rather than diagnosing a death.
The merge resolution had reflowed two of master's claim-before-collect
comments and added two comments restating the HTTP-vs-TCP asymmetry that
print_sql_stacktraces already documents at its definition. Neither is a
local invariant a reader needs at the call site, and rewording an
untouched comment is churn in a diff a maintainer has to approve a
workflow run for.
…check path

These tests replace print_c_stacktraces because the real collection blocks up
to 30s per server process. The SQL dump now runs at the same abort sites and
needs a live server, so leaving it unstubbed made seven of them fail in
get_stacktraces_from_clickhouse against the test's own Args stub.

Where a test observes the collection window to prove the stop cause is claimed
before it opens, the stub is moved onto the SQL dump rather than added
alongside: it is the first collector called, so an observable bound to the
C dump would only see the tail of the window and would stop failing if a claim
were moved between the two.

The end-to-end hung-check test now also asserts the SQL marker. Without it
that test passes with the dump absent from the path it exists to cover, which
is the regression this branch is about.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (ecc01ef26beb45d5) to clear the conflict. Pushed 83188f6442a4f2d -> 5d160494bd7dc54; mergeable is back to MERGEABLE, scope 4 files +91/-23.

The conflict was not textual. #115080 split FailureReason.SERVER_DIED into SERVER_DIED and LIVENESS_CHECK_FAILED and re-routed three of the four former sites, so the condition this branch covered through the SERVER_DIED abort site now arrives as LIVENESS_CHECK_FAILED:

merge base : :3371 SERVER_DIED  :3382 SERVER_DIED  :3856 SERVER_DIED  :3999 SERVER_DIED
master     : :3385 SERVER_DIED  :3395 LIVENESS...  :3869 LIVENESS...  :4012 LIVENESS...

Taking either side textually would have left the new path collecting C stacks only, dropping the query_id mapping this branch exists to provide. The dump is therefore added at that site too, after the try_claim_stop_cause call so master's claim-before-collect ordering still holds. Master's own comments at those sites are kept byte-for-byte. Description updated: it said three abort sites, it is now four.

This also fixes seven ci/tests/test_hung_check_exit_code.py failures the merge introduced. The SQL dump needs a live server, and the tests stub print_c_stacktraces precisely because collection is expensive, so leaving the SQL collector unstubbed made them fail inside get_stacktraces_from_clickhouse on the test's own Args stub. Where a test observes the collection window to prove the cause is claimed before it opens, the stub is moved onto the SQL dump rather than added beside the C one: it is the first collector called, so an observable bound to the C dump would see only the tail of the window and would stop failing if a claim were moved between the two. The end-to-end hung-check test now asserts the SQL marker as well, which it previously passed without.

Verified on the merged head, not inherited from the pre-merge run:

Arm clickhouse-test result
base master, pre-check present skipped, 0 bytes
fixed this head 356517 bytes, thread_name and query_id present

with HTTP pointed at a closed port and TCP live. Aimed at a dead socket the collector returns at once, writes nothing and raises nothing, which is what makes dropping the pre-check safe. Suite result matches the pristine-master control exactly: 33 passed, the same 10 end-to-end failures in both arms, 0 new. Both repaired oracles were mutation-checked and still fail on a real assertion when the claim is moved after the collection, and when the dump is removed.

Not squashed despite 14 commits: 5 review threads are anchored to 507c6cf5b7cc, 09f8dbe24ce6 and b512cec7e1e4, and the excess over 10 is master merges rather than fixup commits.

Session id: cron:clickhouse-maint-slot-16:20260822-114502

pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Aug 24, 2026
The Code Review job died on `gh auth login` for 10 pull requests in the 24 h to
2026-08-17, losing the automated review for those heads:

    ERROR: Codex review failed after 3 attempts: CalledProcessError:
           Command '['gh', 'auth', 'login', '--with-token']' returned non-zero exit status 1.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113059&sha=83188f6442a4f2d7e4376efe54c2bf3bad32dd50&name_0=PR&name_1=Code%20Review
https://s3.amazonaws.com/clickhouse-test-reports/PRs/113059/83188f6442a4f2d7e4376efe54c2bf3bad32dd50/code_review/job.log
ClickHouse#113059

_run_codex_once authenticated a robot token before every attempt, under
check=True, so any rejection raised before the agent started. The Codex backend
does not use that token. The job sets enable_gh_auth=True, so the runner mints a
GitHub App token into the ambient gh config before the script runs, and the
prompt has the agent prefix every gh call with GH_PREFIX = "env -u
GH_CONFIG_DIR", discarding the scoped robot directory. Over all 25 job logs that
reached the agent, 246 of 246 executed gh calls unset it and none used the robot
directory, and every HTTP 401 in those logs belongs to the robot login rather
than to an agent call. So that login could only ever fail the job.

/ci/robot-ch-test-poll-copilot has answered HTTP 401: Bad credentials on 27 of 27
observed attempts, with no success, since 2026-08-03, while
/ci/robot-ch-test-poll-1-copilot never returned a 401: one dead credential, not a
window-wide outage. Two robots over three attempts rotate as [X, Y, X], so the
healthy robot gets one attempt of three when the shuffle puts the dead one first,
and a single transient GraphQL 503 on that attempt then fails the job. The
rotation had been silently absorbing a permanently broken credential for two
weeks.

Remove the login and its temporary GH_CONFIG_DIR from the Codex attempt, so it
runs on the app identity it was already using and the retry budget is spent on
agent failures. _run_copilot_once keeps its login: the Copilot CLI authenticates
to GitHub with that token directly. Rotating the dead token remains an
operational matter, which the Codex path no longer depends on.

The new test file covers both: five cases fail on the previous code with the
error above, and two pin behaviour that must not change, each verified by
mutating the code it pins. One of those pins is the enable_gh_auth flag the
Codex path now depends on, which lives in ci/defs/job_configs.py rather than in
the job, so nothing else in the suite would notice its removal.
@alexey-milovidov alexey-milovidov self-assigned this Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit 24cba4c Aug 29, 2026
178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 29, 2026
…e sweep

The conflict offered master's copy of the parent monitor loop against this
branch's post-loop comment, but the merge had already placed this branch's
restructured loop above it - wrapped in `try`/`finally` and reaping through
`quiesce_workers_and_reap` instead of the inline terminate/join/kill. Dropped
that duplicate body and kept this branch's structure.

The one master-side change inside the region is the SQL stacktrace sweep added to
the hung-check path in ClickHouse#113059, which this branch predates; re-applied it before
`print_c_stacktraces`.

Verified by running `ci/tests/test_abort_path_reaps_test_groups.py` and
`ci/tests/test_hung_check_exit_code.py` before and after the merge: no test fails
after it that did not already fail on this branch's head, and
`test_new_reason_is_matched_by_a_failure_pattern` now passes. The rest are this
environment's Python 3.14 `multiprocessing` forkserver failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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.

4 participants