Skip to content

Use a lock-free queue for asynchronous logging - #107363

Merged
nikitamikhaylov merged 14 commits into
masterfrom
async-logging-vyukov-queue
Jul 29, 2026
Merged

nikitamikhaylov merged 14 commits into
masterfrom
async-logging-vyukov-queue

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

Replace the mutex + condition_variable + deque based AsyncLogMessageQueue with the lock-free Vyukov queue from NonblockingBoundedQueue.h, and remove the wrapper class entirely: threads writing log messages just tryPush (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.

Changelog category (leave one):

  • Performance Improvement

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.

Version info

  • Merged into: 26.8.1.354 (included in 26.8 and later)

nikitamikhaylov and others added 2 commits June 12, 2026 19:35
Use `NonblockingBoundedQueue` (a lock-free bounded MPMC queue) instead of
the mutex + condition_variable + deque combination in `AsyncLogMessageQueue`.
Since the queue serves the logging subsystem and is expected to be non-empty
most of the time, the consumer thread does not use futex-based waiting: when
there is nothing to dequeue, it sleeps in a loop for a bit (10 ms per
iteration). Pushing a message never blocks and never wakes anyone up, so
producers do not pay for an empty or contended queue.

Details:
- `wakeUp` is removed: the consumer threads wake up from the sleep on their
  own, so `OwnAsyncSplitChannel::close` simply joins them, and
  `flushTextLogs` only sets the `request_flush` flag.
- `getCurrentQueueAndClear` is replaced with `dequeueMessage`: a flush pops
  and logs messages one by one (bounded by the queue size at the start of
  the flush), so the messages which were not processed yet are not lost if
  logging one of them throws, and a fully enqueued message cannot be skipped
  behind a slot which a concurrent producer has claimed but not finished
  writing yet.
- The dropped-messages counter is atomic now, and the warning about dropped
  messages is enqueued only after a successful push of a real message, so
  under sustained overflow the warnings cannot displace real messages by
  stealing the slots freed by the consumer.
- The half-full `request_flush` trigger is removed: it existed to let the
  consumer bulk-drain the queue under one mutex acquisition, which is
  meaningless for a lock-free queue.
- The queue capacity is rounded up to a power of two and the slots (one
  cache line each) are preallocated for the lifetime of the channel.
- `NonblockingBoundedQueue.h` now includes `Common/CacheLine.h`, which it
  needs for `CH_CACHE_LINE_SIZE` (before, it relied on the includer to
  provide it).

Co-Authored-By: Claude Fable 5 <[email protected]>
Dissolve the `AsyncLogMessageQueue` wrapper class: `OwnAsyncSplitChannel`
now holds the `NonblockingBoundedQueue` for each channel directly (in a
small data-only `LogQueue` struct together with the per-queue drop
accounting), and the waiting moved into the main loops of `runChannel` and
`runTextLog`: try to pop a message, log it if there is one, otherwise sleep
for a bit and check again.

Details:
- Producers push via `enqueueMessage`, which only counts and drops on
  overflow; they no longer construct the dropped-messages warning.
- The warning about dropped messages is now generated by the consumer and
  logged directly to the channel (or to the system.text_log queue), bypassing
  the bounded queue, so it can never displace a real message. It is reported
  only when the consumer has fully drained the queue, which coalesces all
  drops of one overflow episode into a single warning, keeps the warning
  behind the messages enqueued before it, and never eats into the consumer
  throughput while it is behind. Whatever remains unreported is reported by
  the final flush on close.
- The flush handshake flag moved from the queue to the channel
  (`text_log_flush_requested`).
- The no-op `dynamic_cast` in the consumers (a leftover from the times when
  the queue held generic notifications) is gone.
- The logger source of the warning message changed from
  `AsyncLogMessageQueue` to `AsyncLogger`.

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

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9963601]

Summary: ✅


AI Review

Summary

This PR replaces the mutex-backed async logging queues with NonblockingBoundedQueue, adds exact text-log flush boundaries, and stops async logging threads around remapExecutable. The queue-ordering and flush-barrier issues raised earlier look addressed in the current code, but startup can still continue with async logging partially or fully dead if the post-remap restart throws, so I do not think the PR is ready to merge as-is.

Findings

⚠️ Majors

  • [programs/server/Server.cpp:1310] [dismissed by author -- https://github.com/Use a lock-free queue for asynchronous logging #107363#discussion_r3629950079] startAsyncLoggingThreads runs only under SCOPE_EXIT_SAFE, so a failure in OwnAsyncSplitChannel::open is logged and ignored even on the normal post-remapExecutable path. open starts workers one by one; if Poco::Thread::start throws partway through, startup keeps going with is_open == true but one or more queues permanently undrained, and later log messages for those channels are silently dropped once the bounded queue fills. Suggested fix: restart async logging normally after a successful remapExecutable(), and keep a guarded best-effort restart only for the exception-unwind path.
Tests
  • ⚠️ There is still no focused regression for remap_executable = 1 with async logging enabled, even though this PR already regressed that startup path once in CI. A minimal startup/integration test that exercises stopAsyncLoggingThreads() around remapExecutable() would make this class of failure much harder to reintroduce.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 12, 2026
Comment thread src/Loggers/OwnSplitChannel.cpp Resolved
Comment thread src/Loggers/OwnSplitChannel.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

Release-transition baseline: compared against the last 26.7 master because no 26.8 master baseline exists at or before the trusted base-commit anchor.

This PR rewrites the async logging channel to a lock-free bounded queue and fixes remapExecutable PIE handling plus logging thread stop/start around it — none of which touches query execution. The flagged ClickBench deltas (Q8 +12.6%, Q33 -16.4%, Q34 -8.4%) therefore cannot plausibly be caused by the change and all sit on thin baselines, so they are downgraded to not_sure. Q15 (-14.9%) and Q31 (+12.3%) both fall within master's current variance band. Net: no real performance impact expected from this change.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 8 not_sure 317 357 +12.6% <0.0001 This PR only rewrites the async logging channel; it does not touch Q8's scan/aggregate path, so the +12.6% on a thin 2-group baseline reads as run-to-run variance.
⚠️ 31 not_sure 366 411 +12.3% <0.0001 The +12.3% is within master's normal band and unrelated to a logging-only change, so not_sure stands.
⚠️ 33 not_sure 1645 1375 -16.4% <0.0001 A -16.4% improvement can't come from an async-logging thread rewrite that leaves the SELECT execution path untouched; the 9-sample baseline makes this variance.
⚠️ 34 not_sure 1512 1386 -8.4% <0.0001 The -8.4% is off-path for a logging-only change and rests on a thin baseline, so it is not a real PR effect.

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

🟢 No significant changes

Debug info
  • StressHouse run: e8b07074-0702-4a7a-bb60-d1457786b7a7
  • MIRAI run: 97f652c2-7bdc-4dec-9820-c99b8c444f2a
  • PR check IDs:
    • clickbench_705883_1785262785
    • clickbench_705889_1785262787
    • clickbench_705896_1785262786
    • tpch_adapted_1_official_705912_1785262786
    • tpch_adapted_1_official_705925_1785262786
    • tpch_adapted_1_official_705952_1785262787

Comment thread src/Loggers/OwnSplitChannel.cpp Resolved
Comment thread src/Loggers/OwnSplitChannel.h Resolved
@Algunenano Algunenano self-assigned this Jun 14, 2026
…v-queue

Conflict resolution:

* src/Loggers/OwnSplitChannel.cpp: master changed the old condvar-based
  AsyncLogMessageQueue::enqueueMessage to notify_all only when the queue
  was empty. This PR removes AsyncLogMessageQueue entirely (replaced by
  the lock-free NonblockingBoundedQueue), so master's tweak applies to
  deleted code. Kept the lock-free rewrite (ours) and dropped the tweak.

* src/Common/NonblockingBoundedQueue.h: master changed tryPush(T &&) to
  tryPush(T &) (review comment c04554b; Keeper callers now pass
  lvalues). Kept master's signature and adapted the logging caller from
  tryPush(std::move(message)) to tryPush(message). The value is still
  moved out only on success, so overflow handling is unchanged.
dequeueMessageForFlush waited 1ms for an in-progress producer slot; make
it 10ms to match the empty-queue poll interval. Also shorten the verbose
comments in OwnSplitChannel.{cpp,h} (no behavioral change).
Comment thread src/Loggers/OwnSplitChannel.cpp Resolved

@Algunenano Algunenano 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.

The performance report is broken, most likely by the changes in this PR breaking executable remmaping (the remap_executable setting). Also please have a look at the bot comments

@Algunenano Algunenano 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.

The problem with remapExecutable is that the threads cannot be doing anything while that happens. They used to be waiting (so no issue), now they are polling. I think we can simply join them, remap, then start them again

Algunenano and others added 2 commits July 9, 2026 12:54
remapExecutable copies the code segment to a scratch mapping and runs
from there, relocating internal callee addresses with
`address + (scratch - begin)`. That is only correct when the address is
materialized as an absolute value (non-PIE). In a PIE build the address
is RIP-relative, so once the code executes from the scratch copy the
reference already resolves into scratch and adding the offset again
double-counts, jumping into unmapped memory (SIGSEGV, silent death at
startup with remap_executable=1).

Capture the two callee addresses (`our_syscall`, relocated into scratch,
and `remapToHugeStep3`, at its original place) in `remapToHugeStep1`,
which still runs from the original mapping, and pass them into
`remapToHugeStep2` as arguments instead of recomputing them RIP-relative
from the scratch copy. Behavior is identical for non-PIE builds; PIE
builds now remap correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ress review feedback

The lock-free async logging consumers poll (sleep + `tryPop`) rather than
blocking, so they execute code continuously. `remapExecutable` requires
that no other thread runs code while it rewrites the code segment; a
polling thread faulting on the momentarily-unmapped code dies silently
and takes the server down at startup with remap_executable=1. Join the
async logging threads before `remapExecutable` and restart them
afterwards via new `Loggers::stopAsyncLoggingThreads` /
`startAsyncLoggingThreads` (no-ops for synchronous logging).

Also address review feedback on the async logging path:
- Report the dropped-message warning before clearing the text_log flush
  flag, so `SYSTEM FLUSH LOGS` / shutdown cannot miss that record.
- Only warn about dropped messages once the queue is observably empty
  (`size() == 0`); `tryPop` returning false does not prove emptiness while
  a producer holds an unpublished slot, so the warning could otherwise
  overtake real messages.
- Use an exact positional flush boundary (`enqueuePosition()` captured
  with acquire, drained until `dequeuePosition()` reaches it) instead of
  the imprecise `size()`, so a manual flush cannot miss records.
- Document that `logger.async_queue_max_size` is rounded up to the next
  power of two.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/Server.cpp Resolved

@Algunenano Algunenano 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.

I've recovered the PR and fixed remapExecutable for PIC builds (otherwise I couldn't test the fix locally). Let's see what the CI and perf tests say no

Comment thread programs/server/Server.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Your PR was poisoned by the test 02346_text_index_bug108519_qcc_skip_index. It is fixed in master. Please update the branch.

Algunenano and others added 2 commits July 20, 2026 14:39
Arm startAsyncLoggingThreads with SCOPE_EXIT_SAFE so the async logger is
always restarted after the in-place remap, otherwise an exception from
remapExecutable would leave the logger stopped and the startup exception
would be logged into a queue no consumer is draining.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Loggers/OwnSplitChannel.cpp Resolved
… stopped

`flushTextLogs` hands a flush request to the async text-log thread and waits
for it to clear the flag. That thread is not running while logging is stopped
around `remapExecutable` (the only caller then is the fatal signal handler; the
server is not accepting connections yet) nor after shutdown, so the wait would
block forever. Return early when the channel is not open; anything queued
meanwhile is drained when the thread (re)starts.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/Server.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 120/166 (72.29%) · Uncovered code

Full report · Diff report

@Algunenano Algunenano 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.

The performance improvements can be observed but are insignificant: going from 89.53 µs to 62.43 µs is nice (30%), but in a query of 150 ms that's improving 30% of 0.0574% of the query, so approximately a 0.01% change.

@nikitamikhaylov I'll leave to you to decide if this is worth it. If not I'll extract the remap fixes into a different PR

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@Algunenano I expected to see more improvement under the load. This PR fully deserves being merged.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 29, 2026
Merged via the queue into master with commit cfc1fd2 Jul 29, 2026
179 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the async-logging-vyukov-queue branch July 29, 2026 13:05
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @nikitamikhaylov @Algunenano — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body thoroughly explains the lock-free queue change but does not mention the remapExecutable PIE-addressing fix or why the async logging threads must be stopped around remapExecutable.

  • Suggested addition:

    Also fixes remapExecutable: in PIE builds, remapToHugeStep2 recomputed the our_syscall/remapToHugeStep3 addresses while running from the scratch copy, double-applying the scratch offset. Callee addresses are now captured in remapToHugeStep1 (from the original mapping) and passed in as plain pointers. The async logging threads are joined for the duration of remapExecutable (and restarted via SCOPE_EXIT_SAFE) because they poll and would fault while the code segment is being rewritten.

Ignore this if the current title/body is intentional.

alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
`already_handled` matched the revert branch by its exact name, so it only saw
the reverts this job and `.github/workflows/revert_broken_prs.yml` create. A
revert somebody started with the `Revert` button on GitHub lands on
`revert-<pull request>-<head branch>` instead, and until it is merged neither
the history nor an exact branch name says anything about it.

It now takes the pull request number rather than a branch name, and asks four
things: whether the revert is on `master`, whether a branch named
`revert-<pull request>` or `revert-<pull request>-*` is pushed, whether a pull
request exists on such a branch, and whether one carries the
`Reverts <repo>#<pull request>` marker - the line the `Revert` button writes
into the body, and the one this job writes as well, which finds a revert
however its branch was named.

A GitHub search matches a prefix and stops at no boundary, so both searches
are filtered against what a revert of *this* pull request can look like: the
revert of #1123456 must not stand down the revert of #112345.

Both searches were verified against the real data: the revert of #107363 is
found by its branch and by its marker, and neither matches a number that only
shares a prefix with it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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