Repository navigation
Do not dereference the global context in the crash handler - #116245
Conversation
…exists SignalListener::onFault called Context::getGlobalContextInstance()->handleCrash() without checking the result. The deadly signal handlers and the signal listener are installed before the global context is created, so a fault or a SIGTSTP arriving in that window reaches this call with a null pointer: clickhouse-server BaseDaemon.cpp:473/:492 -> Server.cpp:1549 clickhouse-keeper BaseDaemon.cpp:473/:492 -> Keeper.cpp:433 clickhouse-local ClientApplicationBase.cpp:258-281 -> LocalServer.cpp:1363 Context::handleCrash() takes a lock on mutex_shared_context, a non-static member, so the first action on a null this is a mutex operation on a wild address rather than the intended no-op that the !shared check at Context.cpp:6736 provides. On a sanitizer build UBSan reports the member call on the null pointer and aborts. The added test parks clickhouse-local in that window by pointing --logger.log at a FIFO nobody reads, then sends SIGTSTP, which the handler treats as non-crashing so the manner of the exit is the oracle. Without the guard the process dies from a signal and, on a sanitizer build, prints the null dereference; with it the handler returns. Reported for src/Common/SignalHandlers.cpp:750 by the arm_asan_ubsan targeted stateless check.
…aded The crash handler builds a crash report from a daemon, and the report includes the server UUID, which it reads with ServerUUID::get(). That accessor asks the global context for the application type, so it cannot be used from a caller that runs before the global context exists: clickhouse-server BaseDaemon.cpp:473/:492 -> Server.cpp:1549 clickhouse-keeper BaseDaemon.cpp:473/:492 -> Keeper.cpp:433 The signal listener is running across those spans, so a fault arriving there reaches the report with a null global context, and the two dereferences inside the condition are member calls on a null pointer. The dereferences are also reached with the UUID still unset but the context already up, between Server.cpp:1549 and Server.cpp:1930, where get() throws instead and sendError discards the report along with the exception. The condition exists to assert initialization order for the callers that require a UUID, so it stays as it is. The crash handler is not one of those callers: it already omits the field when the value is Nil. Give it a non-throwing accessor that reads the stored value and needs no context at all, so the report no longer depends on initialization order in either direction. The remaining 22 callers of get() are unchanged. The added test parks keeper before its global context exists by pointing the UUID path at a FIFO nobody writes to, and answers the crash report from a local listener so the report is built rather than abandoned while connecting. Found by widening the startup window and faulting inside it, after the guard added for src/Common/SignalHandlers.cpp:750 made this second site reachable.
The test could pass with the crash-report fix reverted on any build without a sanitizer runtime: nothing read the process exit, the readiness probe never asserted the endpoint came up, and the report check was satisfied by a log line that precedes the connect, so all three oracles were reachable without the report path ever completing. The endpoint now publishes its kernel-assigned port by rename and records that a request arrived, and the test fails if either does not happen, so the report check means the report reached the endpoint rather than that one was about to be attempted. Termination is now read as well, which is the part of the outcome every build reports. The keeper client port is omitted and the raft port is left to the kernel, since the test never connects to the keeper and the previously derived ports covered most of the ephemeral range. The test now skips instead of failing on a build configured without the keeper mode. The tryGet() comment claimed the UUID is loaded after the global context is created. Keeper loads it before, so the comment is replaced with the property it was there to state.
…line The test separated a handler that survives the absent global context from one that faults inside it by how long the process took to die: a surviving handler exits in about a second, a faulting one sits for about 300s waiting for a report that can no longer arrive. Both paths are bounded by the same wait, though. SignalHandlers.cpp waits 300x1s for fatal_error_printed, which is set at the very end of onFault, after the crash report, so the healthy time is however long symbolization takes plus 3s. That was measured at 4.1s idle and 27.1s under load against a 30s deadline, and the comment on that loop records 101s for symbolization under MemorySanitizer. No constant separates the two. The report itself carries an exact signal instead. It is sent with chunked transfer encoding, and the zero-length chunk that terminates the body is written only when the writer finalizes, which is downstream of the part under test, so its presence means the report was written in full rather than abandoned inside it. The sink now records that chunk and the test asserts it, with no deadline involved. Two details worth recording. The terminator is matched against the body rather than the whole request because the header block ends in a digit followed by two CRLF pairs of its own, so matching the whole request marks every run that merely opened the connection as complete, including the runs this is meant to catch. And the sink is now launched in a subshell, like the keeper already was: it is killed at the end of every run, and a shell reports the death of its own background job on its own stderr, which the runner reads as a failure. That was an 8% failure rate on a correct build under load. The remaining wait only has to outlast the handler's own, since a run that reports leaves on the marker and a run that faults leaves when the process dies. Co-Authored-By: Claude Opus 5 <[email protected]>
The crash report reads the server UUID through a non-throwing accessor, which returns Nil until the UUID has been loaded, and the report omits the field for Nil. Every test in this change parks the process before that load, so all of them necessarily see Nil and none of them can tell a working accessor from one that always returns Nil - which would silently drop the field that identifies the crashing instance from every normal crash report. test_send_crash_reports already receives a real report from a fully started server, and already decoded the request body only to throw it away. Keep the body, and assert the reported UUID equals what serverUUID() returns before the crash. Verified live by making the accessor return a constant Nil: the test then fails on that assertion while the report is still delivered. The body is written before the file the test polls on, so a reader that sees the completion marker is guaranteed a complete payload.
The report is built without a UUID to name in two states, and the test covered one of them. A keeper reads its UUID before it creates the global context, so the state it parks in is "no context". A server reads it after, so it also has a state the keeper never has: the context exists and the UUID is still unset. That second state is the one where the accessor this change replaced threw, which the report path catches and then abandons the whole report in, so an implementation that only tested the context pointer would pass every existing arm while sending nothing for the length of the server's own startup. Parking a server in it is the same fixture as the keeper arm, pointed at the other daemon. A server not attached to a terminal keeps running as the child of a watchdog that does not forward this signal, so the arm disables that fork to make the process it starts the process that parks. The state is bounded by the status file, which is written after the context is created and immediately before the UUID is read, rather than by the line the same code logs: logging is asynchronous, so that line can still be queued once the process is already parked, and waiting for it loses the race and reports a state the process has left.
Internal second-model reviewAn independent cold review plus a second model reviewed this change over four rounds before it Accepted and fixed (the substantive ones)
Rejected, with evidence
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-11:20260825-040800 |
|
Workflow [PR], commit [a29752d] Summary: ✅
AI ReviewSummaryThis PR fixes the startup crash path in two places: Findings
Final Verdict
LLVM Coverage ReportMeasured on commit a29752d.
Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code |
|
One adjacent thing I left alone. |
|
cc @pamarcos @vitlibar, could you review this? The deadly signal handlers are installed before the global context exists, so a fatal signal during startup ran |
| if (daemon) | ||
| daemon->flushTextLogs(); | ||
| Context::getGlobalContextInstance()->handleCrash(); | ||
| /// These handlers are installed before the global context is created, so it can still be absent during startup. |
There was a problem hiding this comment.
SIGTSTP is intentionally the one handled signal that returns to the process, but onFault still runs the crash-only epilogue for it and sets fatal_error_printed at the end. After one debug stack dump, the next real fatal signal enters signalHandler() with that flag already set and skips the 300 s wait at line 175, so slow stack symbolization or CrashWriter work can be cut off after the unconditional 3-second tail sleep. It also still inserts system.crash_log rows and sends crash reports for a non-crashing debugging signal.
Can we branch out of the crash-only part (collectCrashLog, CrashWriter::onSignal, fatal_error_printed) for SIGTSTP once the stack trace has been logged?
There was a problem hiding this comment.
Confirmed. onFault (SignalHandlers.cpp:579-793) has no SIGTSTP branch, so collectCrashLog (:736), CrashWriter::onSignal (:757), thread_ptr->onFatalError() (:791) and fatal_error_printed.test_and_set() (:793) all run for it. That flag has exactly two references in the tree, set at :793 and read at :175, and nothing clears it, so one debug dump does leave a later real fault with only the unconditional 3 s tail at :183.
I am not changing it in this PR. This is a two-line null check on the crash path, asked for as a separate minimal fix, and branching the epilogue changes documented behaviour: SIGTSTP would stop producing system.crash_log rows and stop sending crash reports. I have no observed case of that hurting anyone, so I cannot size the risk, and I do not want an unverified behaviour change riding on a mechanical fix. That is why I raised it as a question in the PR rather than as a diff. If a reviewer wants it, it belongs in its own PR with its own test.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units30 translation units recompiled, 190 s compile time in total, 30 of them have a recent master baseline. |
CI finish ledger - c700ab4CI is fully finished on this head. Every failure below has an owner.
Not caused by this PR. The diff touches the crash handler, I checked the nearest recorded owner before opening a new one and it does not apply. That earlier Worth recording for whoever picks this up: the memory tracker was already rejecting allocations The two
Session id: cron:our-pr-ci-monitor:20260825-103000 |
|
Fixing PR for the |
…ash-handler-null-global-context
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes crash-handler startup safety (ServerUUID::tryGet, a null-guarded global context in the signal handler) plus crash-report tests; none of it runs on the query-execution hot path. The two flagged ClickBench queries (Q28 -5.7%, Q34 -5.6%) were correctly suppressed as within-baseline-envelope: both deltas fall inside master's current-era variance band, and CPU time is essentially unchanged (Q28 15632.7 vs 15554.6 ms, Q34 16770.2 vs 16703.3 ms), consistent with run-to-run variance rather than any PR effect. No action needed; the deterministic verdicts are sound. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…reports test_send_segfault kills the server with SIGSEGV and then reads the fake Sentry server's result and payload files with `docker exec`. The node has no stay_alive, so its container exits together with the server, and a read that lands after that fails with `container ... is not running`. When the server dies follows from the signal handler: starting at the signal, it checks once per second whether the crash report has been handled, then sleeps 3 s and re-raises the signal. In the failing amd_cfi run the report was written 6.30 s after the signal, the fourth poll (+10.17 s) still read OK, the payload read started at +10.25 s and the container stopped at +10.26 s. A report that lands just after a poll can make the poll itself hit a stopped container in the same way. The fake server now writes both files into /var/log/clickhouse-server, which every instance mounts from the host, and the test reads them from node.logs_dir, so nothing is read through the container after the crash. stay_alive=True would also keep the container up, but it runs the server with --daemon, which chdirs to <path>/cores, so the SIGSEGV core would land in the host-mounted database directory that CI uploads in logs.tar.gz when the suite fails. With CI's amd_cfi binary, waiting for the container to stop before the payload read (or before the first poll) fails the old test with the CI error and passes with this change. Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/36373749054/job/108786682402 Related: ClickHouse#116245 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #110105
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash inside the crash handler itself when a fatal signal arrives during startup of
clickhouse-server,clickhouse-keeperorclickhouse-local. The handler dereferenced the global context, which does not exist yet at that point, so right after logging the stack trace it took a second fault, hung for about five minutes, and never sent the configured crash report.Description
The deadly signal handlers and the signal listener are installed before the global context is created (
BaseDaemon.cpp:473/:492beforeServer.cpp:1549andKeeper.cpp:433, and the same order inclickhouse-local), so a fatal signal arriving in between reaches the crash handler with no global context.Two places on that path used it unconditionally.
SignalHandlers.cpp:750calledContext::handleCrash(), whose first action takes a lock on a non-static member, so a nullthisis a mutex operation on a wild address instead of the no-op that function's own!sharedcheck gives. On a daemon the report path then reachedServerUUID::get()fromCrashWriter.cpp:121, which asks the context for the application type.The tree already guards this path at the point of use in
ProxyConfigurationResolverProvider.cpp:152andDateLUT.cpp:183; these two were the omissions. The first now tests the pointer the same way. The second uses a non-throwing accessor that reads the stored value and needs no context, which suits a report that already omits the UUID when unset, and also covers the span where the context exists but the UUID is not loaded.ServerUUID::get()is unchanged, keeping its initialization-order assertion for its 22 other callers.Each window gets a test that parks a process in it using only documented options, and fails without its fix.
Reported for
SignalHandlers.cpp:750byStateless tests (arm_asan_ubsan, targeted). What delivered the signal there is not established: that test ran in 1.47 s so the harness timeout path was not involved, and the job's logs show no crash. This rests on the ordering above, not on that run. The context pointer and the stored UUID are both read here without synchronization; both pre-date this change, which takes the UUID read from two to one, and neither is addressed.Workflow [PR]
Sync PR [sync-upstream/pr/116245]
Version info
26.9.1.1537(included in26.9and later)