Repository navigation
Fix a deadlock when one query reads system.stack_trace twice - #120216
Conversation
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]>
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260915-142000 |
|
Workflow [PR], commit [4966ba5] Summary: ✅
AI ReviewSummaryThe PR fixes the self-deadlock when a query reads Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested; normal CI checks remain pending. |
CI finish ledger - 173eb06Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260915-213215 |
…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]>
Related: #115706
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A query that reads
system.stack_tracemore than once, for example throughmerge('system', ...), aUNION ALLor 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 ownsystem.processes JOIN system.stack_tracedump was issued five times, blocked every time and outlived its +60 s cancellation, sohung_check.logheld 28,659 dots and no rows. CI report.StackTraceSourcetook the file-global, non-recursivestd::mutexin its constructor, insideReadFromSystemStackTrace::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 ALLovermerge('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 andKILL 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_httpretries on any exception, so 5 x 120 s of socket timeout plus 9 s of sleep is 609 s against a 600 shung_check.wait.Where every blocked query was parked, captured live (abridged)
Identical to the
trace_logsamples 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 = 5hangs indefinitely before this change and returns1,1in 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
INsubquery, threeUNION ALLreads and the dump query.Between-block interleaving is safe: the handler and
wait()both test a notification against thecurrent
sequence_num, which only increases, so a late answer from a thread abandoned at itspipe_read_timeout_msis rejected and drained, not misread. That already happens within asingle 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_msfrom 100 ms to 2000 msdoes 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
26.11.1.730-master(included in26.11and later)