Skip to content

Fix a deadlock when one query reads system.stack_trace twice - #120216

Merged
jkartseva merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-system-stack-trace-self-deadlock
Oct 24, 2026
Merged

jkartseva merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-system-stack-trace-self-deadlock

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115706

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

A query that reads system.stack_trace more than once, for example through merge('system', ...), a UNION ALL or a self join, deadlocked while its pipeline was built, could not be cancelled or killed, and left every later reader of that table blocked for the lifetime of the server.

Description

Reported by @ alexey-milovidov on #115706: the Stress test (arm_release) hung check produced no report. Its own system.processes JOIN system.stack_trace dump was issued five times, blocked every time and outlived its +60 s cancellation, so hung_check.log held 28,659 dots and no rows. CI report.

StackTraceSource took the file-global, non-recursive std::mutex in its constructor, inside ReadFromSystemStackTrace::initializePipeline: during pipeline build, on the query thread, held until the pipeline died. An AST-fuzzer query read the table twice in one plan, UNION ALL over merge('system', '.+'), so two sources were built back to back on one thread and the second waited on a mutex its own thread owned. std::mutex::lock() has no cancellation point, so it outlived its deadline and KILL QUERY, and the leaked lock parked the five dumps in the same frame.

The exclusion now covers one collected block instead of a whole query, taken in generate() in cancellable 50 ms chunks, plus one cancellation checkpoint in the sweep, so self-nesting is impossible rather than survivable.

16cbcf7 moved this lock into the constructor deliberately, to stop two readers sweeping at once after #54946 had left the mutex a per-source member that excluded nothing. That guarantee is kept: the lock spans all of generate(), so a collection still runs alone, and only "one query at a time" is dropped. Readers may interleave between blocks, which the signal protocol already tolerates.

The two cancellation lines, and overlap between two collections, have no deterministic oracle: both turn on machine timing, not on the query. Say the word and I will add a test-only failpoint and tests for them.

Not part of this fix: the harness reported nothing because clickhouse_execute_http retries on any exception, so 5 x 120 s of socket timeout plus 9 s of sleep is 609 s against a 600 s hung_check.wait.

Where every blocked query was parked, captured live (abridged)
__GI___lll_lock_wait
__pthread_mutex_lock
std::__1::mutex::lock()
DB::(anonymous namespace)::ReadFromSystemStackTrace::initializePipeline(...)
DB::QueryPlan::buildQueryPipeline(...)
DB::InterpreterSelectQueryAnalyzer::buildQueryPipeline()
DB::executeQueryImpl(...)
DB::TCPHandler::runImpl()

Identical to the trace_log samples of all five dump attempts, which differ only in entry point.
That run has zero samples inside StackTraceSource::generate(), so no attempt reached the sweep.

SELECT count(trace) > 0 FROM system.stack_trace UNION ALL SELECT count(trace) > 0 FROM system.stack_trace SETTINGS max_execution_time = 5 hangs indefinitely before this change and returns
1, 1 in 0.54 s after it. Once it has hung, a plain single read, which costs 0.27 s on a fresh server,
hangs forever too. Which columns are read does not matter: the deadlock is in the constructor, and the
column-free pair hangs identically and returns in 0.005 s. Both directions were measured the same way for
the fuzzer's own query, a self join, an IN subquery, three UNION ALL reads and the dump query.

Between-block interleaving is safe: the handler and wait() both test a notification against the
current sequence_num, which only increases, so a late answer from a thread abandoned at its
pipe_read_timeout_ms is rejected and drained, not misread. That already happens within a
single sweep, so this adds no new case.

Why those lines are untested: the lock is now held for one collection, 0.27 s for 453 threads on an
unloaded debug build. Raising storage_system_stack_trace_pipe_read_timeout_ms from 100 ms to 2000 ms
does not extend that, because threads blocking the signal are skipped rather than timed out. The cost is
set by how many threads miss that deadline, a property of the machine not the query, so there is no
deterministic oracle for a reader cancelled while it waits.


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

Version info

  • Merged into: 26.11.1.730-master (included in 26.11 and later)

StackTraceSource took the file-global, non-recursive mutex of
StorageSystemStackTrace.cpp in its constructor, that is inside
ReadFromSystemStackTrace::initializePipeline: during pipeline build, on the
query thread, and held it until the pipeline was destroyed. Any plan that reads
this table more than once therefore builds two such sources back to back on one
thread, and the second waits on a mutex its own thread already owns.
std::mutex::lock() has no cancellation point, so the wait survives
max_execution_time and KILL QUERY, and the lock is leaked for the lifetime of
the server: every later reader of system.stack_trace anywhere in that server
queues behind it in the same frame.

Found on Stress test (arm_release) of ClickHouse#115706 at e4e2318, where the post-run
hung check produced no report at all. The AST fuzzer had UNION ALL-duplicated
SELECT ... FROM merge('system', '.+') LIMIT 10, and merge('system', '.+')
expands to system.stack_trace, so that query wedged the table at 09:33 and
leaked the lock. The hung check's own diagnostic, SELECT p.*, ... FROM
system.processes p JOIN system.stack_trace s USING (query_id), was then issued
five times, blocked in exactly the same frame every time, was cancelled 60 s
after each start with no effect, and never returned or threw: hung_check.log
holds 28,659 progress dots and no rows. The run's trace_log has 1,748 samples in
ReadFromSystemStackTrace::initializePipeline, all 1,748 of them also in
__lll_lock_wait, and zero samples anywhere inside StackTraceSource::generate(),
so no attempt ever reached the per-thread sweep.

The exclusion this table needs is between collections, because the signal
handler answers through process-global state, and it must not be taken where no
cancellation can be observed. It is now a std::timed_mutex acquired as a local
at the top of generate(), in interruptible 50 ms chunks, and released by RAII on
every path out of the block, including the error and early-return ones. Two
sources of one plan therefore never contend, since no thread holds the lock
across two generate() calls, which makes self-nesting impossible rather than
merely survivable. One isCancelled() checkpoint in the per-thread sweep gives
the other half of the report, a collection already in progress, the same
property. Deadlock freedom: a holder is always a thread running its own
collection, which completes without waiting on any other pipeline element, so a
waiter always has a holder making independent progress, including with
max_threads = 1.

A recursive mutex was rejected: two sources would then both hold it from the
build thread while their generate() calls run on arbitrary executor threads that
own nothing, so two sweeps could interleave on the shared stack_trace and
sequence_num globals and return other threads' traces, trading a hang for wrong
results. Bounding the constructor acquisition instead was rejected because
try_lock_for against a mutex the calling thread already owns is undefined
behaviour, and the whole-pipeline hold would survive: a reader whose rows go to
a slow consumer would still lock every other reader out for as long as its own
query runs, which is the second case of the new test.

The constructor is where 16cbcf7 ("Prohibit parallel read from
system.stack_trace", 2023-12-07) deliberately put this acquisition, after ClickHouse#54946
had rewritten the table for max_block_size and left the mutex as a per-source
member that excluded nothing, so that two readers could no longer sweep at once.
That guarantee is kept and not dropped: the local lock spans the whole of
generate(), so exactly one collection still runs at a time. What is dropped is
only the stronger property that one QUERY held the table, which is what made a
plan with two reads deadlock. Interleaving between blocks of different queries
is safe by the protocol itself: the handler returns without writing anything
unless the signal payload it was queued with equals the current sequence_num,
wait() accepts only a notification whose value equals the current sequence_num
and drains any other, and sequence_num is only ever incremented, once per
signalled thread. A late answer from a thread abandoned at its
pipe_read_timeout_ms therefore carries a strictly smaller value than any later
signal and is rejected rather than misread. That case is not new either: the
increment happens in a SCOPE_EXIT around each per-thread wait, so it already
occurs within a single sweep whenever a thread is abandoned at the timeout and
its handler runs afterwards. Releasing the lock between blocks adds no
interleaving class that the protocol did not already have to tolerate.

strsignal is resolved once into a global, because the constructor-held lock used
to serialise it and no longer does. Its output is unchanged: the
"Thread {} ({}) blocks SIG{} signal" line prints SIGRT34 both before and after.

Both directions, on Build-ID-verified binaries. Without the change, SELECT
count(trace) > 0 FROM system.stack_trace UNION ALL SELECT count(trace) > 0 FROM
system.stack_trace never returns: it outlives its own max_execution_time (45 s
past a 5 s deadline when measured directly, and in the test's bounded form only
the outer timeout ends it), and afterwards a plain single read of the table
hangs forever too, because the lock is leaked. With the change the pair returns in
0.54 s, a single read in 0.27 s, and the harness's dump query returns symbolised
stacks in 0.44 s. Which columns are read does not matter, because the deadlock
is in the constructor: the column-free form of the same pair hangs identically
without the change and returns in 0.005 s with it. The fuzzer's own query, a
self join on thread_id, WHERE thread_id IN (SELECT thread_id FROM
system.stack_trace)
and three UNION ALL reads were each measured the same way, on a fresh server per
shape because the first hang wedges the server.

Sixteen query shapes pass with the fix, among them clusterAllReplicas, the
send_signal = false column set, the thread_name path, thread_id = 0 as an empty
result, max_block_size = 1 (580 single-row blocks, so 580 lock cycles, 0.07 s)
and max_threads = 1. Each read in the test collects one thread per block and
stops after five, so its cost does not scale with the server's thread count: the
pair is 0.007 s and the concurrent probe 0.005 s, against budgets of 50 s and
25 s. The new test passes 50 of 50 runs with randomization on, worst case
2.55 s, and the six existing tests that read this table pass 5 runs each
alongside it, 30 parallel and 5 sequential. Restoring the constructor lock makes
both of its lines flip; keeping the lock lazy but holding it across a source's
own blocks flips them too, with the concurrent reader failing its deadline at
25.1 s instead of waiting forever.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 15, 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), three passes, plus my own cold review of
the resulting code before each pass ran. 6 findings in round 1, 3 in round 2, 0 in the final pass.
The branch is a single amended commit, so every fix below is in the published head; the round column says
when each one landed.

# Sev Finding Verdict Evidence / action
1 ❌ The new test's budgets were calibrated on an unloaded debug build, where a full sweep is 0.27 s; the sanitizer lanes that will run it are 5-9 s for less work, and a fired timeout prints the same line as a regression (round 2) AGREE, fixed r2 CIDB 30 d for the no-parallel 02940_system_stacktrace_optimizations: amd_asan_ubsan p50 7910 ms / max 36800 ms, amd_tsan p50 5120-7310 ms, amd_msan p50 6630-6980 ms, against amd_debug p50 1100-1300 ms. Each read is now bounded to five single-thread blocks (LIMIT 5 SETTINGS max_block_size = 1), so its cost no longer depends on the server's thread count: measured Read 1 threads per block, 0.008 s for case 1 where the unbounded form was 0.583 s, and the budgets were raised on top
2 ⚠️ The test never sent a signal, so it never touched the process-global state the mutex protects (round 1) AGREE, fixed r1 send_signal is derived from the selected columns (StorageSystemStackTrace.cpp:432) and every read was column-free, so the planner picked the smallest column, thread_id. All three reads now name trace; measured Send signal to N threads (total) with N > 0 per read, against 0 before
3 ⚠️ The slow-consumer case could print its pass line when its holder query never started, or exited during the probe, leaving an uncontended mutex (rounds 1 and 2) AGREE, fixed r1+r2 The holder is asserted live in system.processes immediately before and immediately after the probe, and each diagnostic is absent from .reference. Both arms are two-armed negative controls: a holder killed before the probe and one killed 1 s into it each fail with a distinct line plus the holder's real error code, and deleting either guard makes that same broken run pass vacuously
4 ⚠️ The case-1 oracle was a substring test over merged stdout and stderr, so it reported success for a query that had failed (round 2 acceptance step) AGREE, fixed r2 On a build where the lock is held across blocks, case 1 fails with Code: 159 at 50 s and the server's error text contains a 1 1 substring, so grep -F '1 1' matched it. Now grep -E '^1 1 *$'. Safe to anchor: every log line this table emits is LOG_TRACE or LOG_DEBUG, below the runner's warning level, and clickhouse-test already fails any shell test whose stderr is non-empty
5 ⚠️ Reversing part of 16cbcf7 ("Prohibit parallel read from system.stack_trace") was not acknowledged anywhere (round 1) AGREE, fixed r1 The commit message and the description now cite it and #54946, state that the "one collection at a time" guarantee is kept because the lock spans all of generate(), and prove that between-block interleaving is safe by the signal protocol: the handler writes nothing unless the payload it was queued with equals the current sequence_num, wait() accepts only an equal value and drains any other, and sequence_num only increases
6 ⚠️ The two cancellation lines (the bounded try_lock_for wait and the sweep checkpoint) have no oracle that would fail if they were removed (round 1) DISAGREE True, and stated in the description, which offers a failpoint. No SQL-only lever exists: a 580-thread collection costs 0.06-0.29 s, and raising storage_system_stack_trace_pipe_read_timeout_ms from 100 ms to 2000 ms leaves it at 0.29 s, because signal-blocked threads are skipped rather than waited for. On a build where the lock is held ~20 s, a waiting reader did honour its deadline (Code: 159, elapsed 5012.873 ms). A test-only failpoint is the only remaining lever and I did not add one unilaterally
7 ⚠️ The slow-consumer case would also pass if the exclusion were deleted outright, so it does not pin collection overlap (round 2) DISAGREE Overlap is observable only as a rate change in lost signal responses: a handler that loses the signal_latch CAS returns without writing, the row still gets a non-NULL default trace, and the resulting Cannot obtain a stack trace for thread line is documented as normal in 02940. Any assertion on it is a content-race assertion of the kind 03565 and 05175 carry retry loops to avoid. The property is also pre-existing and never had a test. Covered by the same failpoint offer instead
8 💡 break on cancellation returned a 0-row chunk that still carried columns, which does not finish the source (round 1) AGREE, fixed r1 Chunk::empty() is !hasRows() && !hasColumns(), so that chunk is truthy; now return {}, matching RemoteSource and StorageSystemJemallocSampledAllocations
9 💡 The file-header note and the generate() comment state the same property twice (round 1) AGREE, fixed r1 The generate() comment is down to two lines and the motivation moved to the commit message. One clause still overlaps, which I am leaving deliberately: both surviving comments say why a non-obvious property holds, rather than narrating the fix
10 💡 A case-1 failure reaches the report as the flipped reference line only, without an error code or elapsed time, because the client's stderr is consumed by the oracle (round 3) noted, not fixed Diagnostic-only, on a path this fix makes unreachable, and the reference diff still names which case failed. Recorded rather than changed at this stage

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:20260915-142000

@clickhouse-gh clickhouse-gh Bot closed this Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4966ba5]

Summary: ✅


AI Review

Summary

The PR fixes the self-deadlock when a query reads system.stack_trace multiple times by holding the global mutex only during each collected block. It also makes mutex contention and the thread sweep cancellable. No actionable findings in the current diff at 4966ba5608e9b6588be15d69262dbde31b3edf10.

Missing context / blind spots
  • ⚠️ Current-head functional and sanitizer CI results are still pending, and no local build was available. Earlier regression evidence includes 50 successful TSan runs of the new test; current-head CI completion would close the remaining runtime-validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; normal CI checks remain pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@clickhouse-gh clickhouse-gh Bot added the comp-system-table system.* tables (introspection, system metadata, performance visibility). label Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 173eb06

Every failure below has an owner: a fixing PR (mine 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
Build profile diff job-level RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes, raised in has_pr_data at ci/jobs/build_profile_diff_job.py:723: the readiness probe collapses every non-ok response into a bare False, so a transient CI logs cluster refusal is fatal and the job prints a single opaque line. Not reachable from this diff: the job only reads binary_sizes on the logs cluster. Measured 137 red heads across 123 distinct pull requests since 13:14Z today and 204 error rows in 7 days; the job runs on pull requests only, so there is no master arm #120121 (mine, open)
Stress test (arm_asan_ubsan, s3) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 2270-38be) a column of AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) states serializes to zero bytes because the resample range is empty (end below begin), so the reader cannot recover the row count and pushes a chunk carrying only the key column: ISource::prepare then trips the port assertion at src/Processors/Port.h:431. Not reachable from a system.stack_trace locking diff. Trunk defect with onset 2026-08-16: 224 rows across 146 distinct pull requests and 11 true-master rows in 30 days, still red on master this week #119700 (mine, open)

Mergeable Check and PR are the two praktika aggregators of the rows above, not independent
failures. CH Inc sync is green on this head.

Session id: cron:our-pr-ci-monitor:20260915-213215

pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 26, 2026
…ness's own queries

After a clean fuzz run (`Fuzzer exit code is 143`), the post-fuzz liveness
probe `clickhouse-client --handshake_timeout_ms=30000 --receive_timeout=5
--query 'SELECT 1'` sometimes never returns. status.tsv is then never
written, praktika kills the job at its 18000 s timeout before any artifact
is uploaded, and the job reports a bare ERROR with no server log. Five such
runs in 45 days: PR ClickHouse#112304 (2026-08-18), PR ClickHouse#98670 (2026-08-19), PR ClickHouse#115530
(2026-08-20), true master 9816d0a `AST fuzzer (amd_release, oracle)`
(2026-09-24) and PR ClickHouse#119237 `AST fuzzer (amd_debug, targeted,
old_compatibility)` (2026-09-25). Only the last one printed the `1`.

Two harness defects make the probe unbounded.

(a) The probe is itself fuzzed on the server. query-fuzzer-tweaks-users.xml
sets ast_fuzzer_runs=5 and ast_fuzzer_any_query=true on the `default`
profile, and no harness-owned client call opted out. The server runs the
mutated copies in a query-finish callback, and TCPHandler calls
io.onFinish() after sending the data and before EndOfStream, so a fuzzed
follow-up that does not finish holds the reply open after the `1` was
printed. The same pin was part of ClickHouse#113248, which was closed as already
integrated, but its run-fuzzer.sh half never reached master. The stress
harness (ClickHouse#114127), the log export (ClickHouse#117996) and tests/clickhouse-test
already pin it.

(b) --receive_timeout does not bound the probe either. On a receive
timeout ClientBase::receiveResult only records TIMEOUT_EXCEEDED and cancels
the query; from then on it polls the connection until the server sends a
packet, with no bound. A server whose connection thread never gets back to
the socket holds the probe forever, which is what the four runs that
printed nothing show.

Pin --ast_fuzzer_runs=0 on every harness-owned client call through one
variable; the fuzzer's own client stays unpinned. Run the two post-fuzz
probes (the restart liveness check and the probe loop) under
`timeout --signal TERM --kill-after=10 60`. A probe killed by timeout
(rc 124, or 137 after the kill) is counted like the client's own
"Timeout exceeded while", so a server that stops answering reaches the
existing "treating server as hung" verdict after 12 retries (about
14 minutes) and the job keeps its logs. 60 s covers the probe's own worst
case (30 s handshake, 5 s receive timeout, the cancel round trip) with room
for a slow sanitizer server. The fallback branch now prints the probe's
exit code instead of the last grep's.

The pre-fuzz probes are not wrapped: the check after attaching gdb waits
for gdb to load debug info on purpose, and the server is fresh there.

One server-side hang the fuzzer produces, a self-deadlock when one query
builds two system.stack_trace sources, is fixed separately in ClickHouse#120216.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jkartseva jkartseva self-assigned this Oct 24, 2026

@jkartseva jkartseva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@jkartseva
jkartseva added this pull request to the merge queue Oct 24, 2026
Merged via the queue into ClickHouse:master with commit b866a0a Oct 24, 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 Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-system-table system.* tables (introspection, system metadata, performance visibility). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants