Repository navigation
Revert "Revert "Use a lock-free queue for asynchronous logging"" - #112803
alexey-milovidov merged 37 commits into
Conversation
|
Workflow [PR], commit [6c60e5e] Summary: ✅
AI ReviewSummaryThis PR reintroduces the lock-free asynchronous logging queue from Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 256/308 (83.12%) · Uncovered code |
`clickhouse-local` never stopped the asynchronous logging threads (one `AsyncLogger` per log channel plus `AsyncTextLog`) started by `Loggers::buildLoggers`. Unlike the server, where `~BaseDaemon` calls `stopLogging`, `LocalServer` had no such call, so `OwnAsyncSplitChannel::close` never ran and the threads were still consuming the log queues while `exit` ran static destructors. Under ThreadSanitizer the unjoined threads surface at exit as a `thread leak` report on `AsyncLogger`, and since sanitizers run with `abort_on_error=1` the report aborts `clickhouse-local`. That made the `Scraping system tables` CI step report every `system.*_log` dump of an affected run as failed. The `amd_msan` `use-of-uninitialized-value` in `OwnPatternFormatter::formatExtended` is the same shutdown race caught in the act: the `AsyncLogger` thread was still formatting a message using Poco's static priority-name strings after `exit` had destroyed them. The fix mirrors `BaseDaemon`: `~LocalServer` stops and joins the asynchronous logging threads (`OwnAsyncSplitChannel::close` flushes the queues before joining), so they never overlap with static destruction. Originally submitted as #112753 against the first version of this change. Folded in here because that version was reverted in #112793 and is reintroduced by this pull request, so the fix must land together with it. Closes: #110816
|
Approved in #112753 |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR only changes signal handling, async logging thread lifecycle, and the startup remapExecutable quiescing sequence — none of which sit on the query execution path, so per-query timing shifts here are not plausibly caused by the change. The moderate ClickBench improvements (Q13/16/17/18/30/33/34, ~6-24%) and the marginal Q28 regression (+5.0%) are downgraded as run-to-run variance. Four large, clean deltas — ClickBench Q23 (×2.3 faster) and Q31 (-25.6%), and TPC-H Q7 (×8.2 faster) and Q8 (×2.2 faster) — are locked by the trust math and left as improvements, but none has a code-path explanation in this diff; the TPC-H pair ran co-located (a known variance source) and Q23 has a noisy history, so treat their magnitude with caution. clickbench🟢 2 improved · Flagged queries (10 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 2 improved Flagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 123/169 (72.78%) · Uncovered code |
…t-107363-async-logging-vyukov-queue
Address review: stopping the asynchronous logging threads around `remapExecutable` was not enough. `BaseDaemon::initializeTerminationAndSignalProcessing` installs the signal handlers and starts `signal_listener_thread` before `Server::main` runs, so a signal delivered while the code segment is being rewritten would execute a handler whose code is unmapped, and would then wake `SignalListener::run`, which is also unmapped at that moment. Block the asynchronously delivered handled signals (`SIGINT`, `SIGQUIT`, `SIGTERM`, `SIGHUP`, `SIGCHLD`, `SIGTSTP`) in the thread doing the remap, and start `signal_listener_thread` with the same signals already blocked so it inherits the mask instead of setting it in `SignalListener::run`, which would leave a window right after the thread starts. The deadly signals (`SIGSEGV`, `SIGBUS`, ...) are raised synchronously by the faulting instruction and cannot be usefully blocked, but a fault inside the remap is fatal in any case. With both threads masked, and no other thread created yet at that point, no handler can run while the code is unmapped. Nothing is lost either: a signal sent in that window stays pending for the process and is delivered as soon as the mask is restored.
|
🕵 Status of the three red jobs on
@groeneai, please investigate the last one — The branch has been merged with |
|
🕵 On the AI review's remaining note (⚠ no focused before/after measurement for the changed path itself): here is one for the producer side, which is what this change is about. Microbenchmark of the producer cost only: the old
Reading it honestly:
No regression at any point, and a large win in the single-producer case. The benchmark is a throwaway (it reimplements the old queue to compare against), so I have not added it to the tree; say the word if you would rather have it as a |
|
The fix is already merged: #111017 (merged 2026-08-01 23:19 UTC, merge commit Why Root cause, for the record: You are right that no issue existed for it. All 5 CIDB hits for |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units53 translation units recompiled, 336 s compile time in total, 53 of them have a recent master baseline. |
…t-107363-async-logging-vyukov-queue
Two findings from the AI review on the previous commit: 1. The `SYSTEM FLUSH LOGS` boundary was not exact. Replace the `text_log_flush_requested` boolean handshake with request/completed sequence counters: a flusher takes a request number, and the text log thread loads the request counter *before* sampling the queue's enqueue position, so read-write coherence guarantees the drain target covers every record enqueued before a served request. The counters also fix a race the boolean could not express: a second concurrent flusher could pass the "wait out prior flush" gate before the first one set the flag, then be released by the completion of a drain whose boundary was sampled before its records were pushed. The final drain and `close` publish the handshake too, so a flusher racing with shutdown is released instead of waiting forever. Also rewrite the comment on `NonblockingBoundedQueue::enqueuePosition`: the acquire load does not synchronize with the producers' relaxed CAS; the exactness comes from the happens-before established by the flush handshake. 2. Logger restart after `remapExecutable` no longer swallows failures. `OwnAsyncSplitChannel::open` now tears the partially opened channel back down and rethrows if a thread fails to start (resetting the never-started `Poco::Thread` first, since joining one would wait forever), instead of leaving queues that no consumer drains. `Server::main` restarts the logging threads outside the signal-blocking scope and lets a restart failure propagate instead of suppressing it with `SCOPE_EXIT_SAFE`; a `remapExecutable` exception is stashed and rethrown after the logger is running again, so it is still logged. Smoke-tested: server with `remap_executable = true` starts, remaps, serves exact `SYSTEM FLUSH LOGS` (marker visible in `system.text_log` right after each flush, 8 concurrent flushers), handles `SIGHUP`, and exits cleanly on `SIGTERM`. #112803 Co-Authored-By: Claude Fable 5 <[email protected]>
…t-107363-async-logging-vyukov-queue
Blocking the asynchronously delivered handled signals is not enough to quiesce the signal path: a signal that landed just before the mask was set can already have written a record into the signal pipe, and `SignalListener::run` could execute the corresponding callback while `remapExecutable` is rewriting the text segment. Factor the listener start/stop into `BaseDaemon::startSignalListener` / `BaseDaemon::stopSignalListener` and stop/join the thread around the remap: the stop request is ordered in the pipe after every record queued so far, so the thread drains them while the code is still mapped, and then exits. After the remap the listener is restarted; records from pending signals delivered when the mask is restored wait in the pipe until then, so nothing is lost. `stopSignalListener` is idempotent so that the `BaseDaemon` destructor does not join an already-joined thread if a restart failed mid-way.
…t-107363-async-logging-vyukov-queue
…utable` `Jemalloc::setup` in `BaseDaemon::initialize` starts jemalloc background threads before `Server::main` reaches the remap block (they are enabled by default), so stopping only the signal listener and the async logging threads did not make the process single-threaded: a background thread could execute allocator code from the text segment, or take a handled signal, while `remapExecutable` rewrites that segment. Disable the `background_thread` mallctl inside the quiesce window (it stops and joins every background thread before returning) and re-enable it after the remap, outside the signal-blocking scope, so the restarted threads get the pre-remap signal mask. Also add the integration test `test_remap_executable`: server startup with `remap_executable = 1` under the default `jemalloc_enable_background_threads = 1`, signal handling by the restarted listener thread, and the restart of the jemalloc background threads. #112803
|
🕵 Status of the red jobs on
The new commit 311cd7e addresses the AI review blocker (jemalloc background threads are now quiesced around |
…t-107363-async-logging-vyukov-queue # Conflicts: # src/Daemon/BaseDaemon.cpp
|
🕵 Status on The conflict. The four stress reds, all unrelated:
On the AI Review verdict. The sole Major is the same |
…t-107363-async-logging-vyukov-queue
Make each `OwnAsyncSplitChannel` consumer wait for in-flight producers before sampling its final queue boundary, so shutdown cannot leave a late enqueue stranded.
…c-logging-vyukov-queue' into continue-pr-112803-retry
Reintroduces #107363, reverted in #112793, together with the fix for the shutdown race it exposed.
Related: #107363
Related: #112793
Related: #112753
Closes: #110816
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Asynchronous logging now uses a bounded lock-free queue: threads writing log messages never block on a mutex or wake up the logging threads.
Description
Replace the mutex +
condition_variable+ deque basedAsyncLogMessageQueuewith the lock-free Vyukov queue fromNonblockingBoundedQueue.h, and remove the wrapper class entirely: threads writing log messages justtryPush(dropping on overflow), and the consumer threads poll their queues, sleeping for 10 ms when there is nothing to dequeue, so producers never block on a mutex or pay for a futex wake. The warning about messages dropped on overflow is now generated by the consumer after it has drained the queue, so it coalesces per overflow episode and cannot displace real messages.What is different from the reverted version
The second commit folds in the fix originally submitted as #112753, which must land together with this change rather than after it.
clickhouse-localnever stopped the asynchronous logging threads (oneAsyncLoggerper log channel plusAsyncTextLog) started byLoggers::buildLoggers. Unlike the server, where~BaseDaemoncallsstopLogging,LocalServerhad no such call, soOwnAsyncSplitChannel::closenever ran and the threads were still consuming the log queues whileexitran static destructors. That was a pre-existing defect, but the previous consumers blocked incondition_variable::waitforever, so at process exit ThreadSanitizer saw them as still running and ignored them. The polling consumers introduced here reach the finished state instead, and ThreadSanitizer reports finished but unjoined threads as leaks:Since sanitizers run with
abort_on_error=1, the report abortsclickhouse-local. TheScraping system tablesCI step dumps everysystem.*_logtable with a separateclickhouse-localinvocation, so an affected run reports those dumps as failed. Theamd_msanuse-of-uninitialized-valueinOwnPatternFormatter::formatExtendedis the same shutdown race caught in the act: theAsyncLoggerthread was still formatting a message using Poco's static priority-name strings afterexithad destroyed them.The fix mirrors
BaseDaemon:~LocalServerstops and joins the asynchronous logging threads (OwnAsyncSplitChannel::closeflushes the queues before joining), so they never overlap with static destruction. Exit codes are unchanged on both the success and the error path.The folded diff is byte-identical to #112753, which was green on a base that already contained #107363, so the combination in this pull request is the one that was tested there.
Documentation entry for user-facing changes