Skip to content

Replace per-table FileLog watch threads with a single shared reactor - #125794

Merged
mu-soliman merged 24 commits into
ClickHouse:masterfrom
mu-soliman:file_log_threading
Nov 11, 2026
Merged

mu-soliman merged 24 commits into
ClickHouse:masterfrom
mu-soliman:file_log_threading

Conversation

@mu-soliman

@mu-soliman mu-soliman commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

For FileLog tables use the reactor design pattern to use one thread to watch all files changes and multiplex the changes to watchers, where each table has a single watcher.

Closes: #116688

Changelog category :

  • Improvement

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

Instead of having one thread per FileLog table to watch files changes, use a single thread to watch file changes for all tables. This should eliminate thread starvation bugs that happens when we have too many FileLog tables.
...


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

Version info

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

Use the reactor design pattern to use one thread to wacth all files
changes and multiplex the changes to watchers.
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3757575]

Summary: ✅


AI Review

Summary

This PR replaces per-table FileLog watch threads with a shared DirectoryWatchReactor. A lot of the tricky rename ordering and macOS bookkeeping has improved, but I still see two new reactor-level failure-mode bugs in the current code, and two previously discussed correctness problems still remain unresolved by design: Linux overflow still continues after dropped events, and the macOS scan path can still suppress a later unnotified append after an earlier notified write.

Findings

❌ Blockers

  • [src/Storages/FileLog/DirectoryWatchReactor.cpp:464] [dismissed by author -- https://github.com/Replace per-table FileLog watch threads with a single shared reactor #125794#discussion_r4282595983] Pooling watchers into eight inotify queues lowers the odds of IN_Q_OVERFLOW, but the Linux path still only logs and continues. Once a pooled queue overflows, dropped creates/renames are never reconciled, so files can remain permanently invisible until reattachment. Suggested fix: after overflow, either reconcile the affected watchers' directory state or fail those tables visibly instead of ingesting with incomplete state.
  • [src/Storages/FileLog/DirectoryWatcherBase.cpp:684] [dismissed by author -- https://github.com/Replace per-table FileLog watch threads with a single shared reactor #125794#discussion_r4524023429] reported_modifications is keyed only by inode, so an earlier notified append suppresses a later scan-only append to the same file. After setSnapshot advances the fingerprint, that second append disappears until another change happens. Suggested fix: remember the exact fingerprint already covered by a notification, or let the scan emit DW_ITEM_MODIFIED when the fingerprint has advanced beyond the last reported state.

⚠️ Majors

  • [src/Storages/FileLog/DirectoryWatchReactor.cpp:83] wakeUp ignores all write failures. If ::write returns EINTR before it enqueues a byte, submit() still waits on result.get() while epoll/kevent can sleep forever because no wake-up was actually queued. Suggested fix: mirror WakeupFd::notify here — retry EINTR, accept only EAGAIN/EWOULDBLOCK as benign, and treat anything else as fatal.
  • [src/Storages/FileLog/DirectoryWatchReactor.cpp:96] When runLoop throws, the shared reactor thread stops without failing or detaching the already-registered watchers. Existing FileLog tables then silently stop seeing new directory changes, and later remove() failures are swallowed until ~DirectoryWatchReactor() hits chassert(registrations.empty()). Suggested fix: actively fail or detach all current registrations here and surface a per-watcher error before the thread exits.
  • [src/Storages/FileLog/DirectoryWatcherBase.cpp:448] [dismissed by author -- https://github.com/Replace per-table FileLog watch threads with a single shared reactor #125794#discussion_r4513924223] scanFilesAndUpdateWatches still retries based on whether the shared kqueue drained globally, not on whether this watcher's own state is still ambiguous. A hot unrelated directory can therefore keep an otherwise quiet watcher from ever committing its add/rename/remove scan. Suggested fix: make the retry decision watcher-local, or bound the shared drain and remember whether this watcher itself saw post-scan events.
Final Verdict

❌ Request changes — the shared reactor architecture is promising, but the current revision still has unresolved data-loss paths and two new reactor failure-mode bugs.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 14, 2026
@mu-soliman mu-soliman added the can be tested Allows running workflows for external contributors label Oct 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Oct 14, 2026
Don't open one inotify per table, instead use only one inotify for all
tables.
close kqueue_fd if the DirectoryWatcherReactor constructor throws.
@antaljanosbenjamin antaljanosbenjamin self-assigned this Oct 16, 2026
Don't log anything except error messages to prevent logged lines from
breaking the test.
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 37575757b with master 9e17b5d05 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

135 object files changed (+122.64 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/FileLog/DirectoryWatchReactor.cpp.o new 133.30 KiB +133.30 KiB
src/CMakeFiles/dbms.dir/Storages/FileLog/DirectoryWatcherBase.cpp.o 107.15 KiB 86.75 KiB -20.40 KiB (-19.04%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.63 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 11.0 s +7.2 s (+194%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.5 s +5.4 s (+251%)
Compile time of recompiled translation units

1482 translation units recompiled, 9622 s compile time in total, 1480 of them have a recent master baseline.

Job report

@CLAassistant

CLAassistant commented Oct 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Interpreters/Context.h Resolved

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

Last comment from me, because I missed that point from the AI before. If you want, I am okay merging this as is and fixing this in an upcoming PR, but please don't forget it :)

@mu-soliman
mu-soliman added this pull request to the merge queue Nov 11, 2026
@mu-soliman
mu-soliman removed this pull request from the merge queue due to a manual request Nov 11, 2026
void DirectoryWatchReactor::wakeUp()
{
/// EAGAIN means that the pipe is full of wake-ups the reactor thread has not read yet, which is as good as this one.
[[maybe_unused]] auto res = ::write(control_pipe.fds_rw[1], "\0", 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ If ::write is interrupted before it enqueues a byte (EINTR), this helper still returns as though the reactor had been woken. The caller then blocks in submit().result.get() or stop().join() while epoll/kevent can sleep indefinitely because no wake-up was actually queued.

Please mirror WakeupFd::notify here: retry EINTR, treat EAGAIN/EWOULDBLOCK as “wake-up already pending”, and surface any other error instead of silently losing the signal.

}
catch (...)
{
/// The loop fails only if `epoll` itself does, and there is nothing to continue with then. Do not leave the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ When runLoop() throws, this catch only marks the reactor stopped and rejects future commands. Existing watchers stay registered and are never told that the shared thread died, so every FileLog table behind this reactor silently stops seeing new directory changes. Later DirectoryWatcherBase::~DirectoryWatcherBase suppresses the failing remove(), leaving registrations non-empty until ~DirectoryWatchReactor() hits its chassert.

Please actively fail or detach the current registrations here (and surface an error to their owners) before letting the thread exit.

@mu-soliman
mu-soliman enabled auto-merge November 11, 2026 13:20
@mu-soliman
mu-soliman added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit 510c703 Nov 11, 2026
187 checks passed
@mu-soliman
mu-soliman deleted the file_log_threading branch November 11, 2026 17:40
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 11, 2026
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 15, 2026
The test compared the server-wide `GlobalThread` metric before and after
creating 200 FileLog tables and required a growth below 100. That metric also
counts the threads of unrelated, lazily growing pools. In the failing master
runs (4a88506, fc8a491, 149b9fa) a background merge of the wide
`system.metric_log` table on the `cached_s3` disk grew the threadpool remote-FS
reader by 119-163 threads inside the CREATE window, while the CREATEs added
about one. Only the DatabaseReplicated lane failed: each CREATE there goes
through Keeper, so the window is ~18 s instead of ~1 s.

Count the shared watch thread itself: rows of `system.stack_trace` named
`FileLogWatch`. There is one reactor per server and `DirectoryWatchReactor::add`
waits for its thread, so after the CREATEs the count is 1 whatever else runs on
the server. It reads 0 on 26.10, which still has a thread per table. Reading
only `thread_name` sends no signals to other threads.

Related: ClickHouse#125794

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Nov 24, 2026
05319_file_log_rename_in_reused_inode timed out in Fast test (arm_darwin) of ClickHouse#117738:
one macOS scan saw a.csv gone and b.csv, moved in from a hard link outside the
directory, with the same inode, diffed them as MOVED_FROM a.csv + MOVED_TO b.csv,
and StorageFileLog kept a.csv's offset, skipping rows of b.csv.

ClickHouse#123593 made is_rename refuse a name in deleted_files as a rename source. Before
ClickHouse#125794 every NOTE_DELETE of a watched descriptor put its name there; ClickHouse#125794
(4d75ef8) returns early while the file still has links, because kqueue reports
an unlink of any name to every descriptor of the file and the scan has to find
which name went away (hidden excluded aliases of 05316_file_log_globs). When the
remaining link is outside the directory, nothing recorded the unlink any more.

Record the inode in that branch (unlinked_inodes), and in is_rename refuse the pair
when the inode's current name matches the path: the scan lists every matching name
and is_rename requires one listed name per side, so such a name was not a link of the
file at the last scan and the file came back, i.e. it is new here, as on Linux (an
IN_MOVED_TO without its IN_MOVED_FROM is ADDED). An excluded current name can be a
hidden alias and keeps ClickHouse#125794's behaviour. The set lives next to deleted_files: kept
across discarded and failed passes, cleared after a committed one, the first snapshot
included (its listing already reflects every unlink recorded before it, and it pairs
nothing). The unlink is drained before the diff (scanFilesAndUpdateWatches drains
before syncFileWatches closes descriptors), so the decision does not depend on scan
timing.

The test gains the same steps in one process so a macOS scan sees the unlink and
the move-in together; the new content is longer than c.csv's offset, so a carried-
over offset gives wrong rows (checked on Linux with a same-inode rename, which keeps
the offset: only 110 is read).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-improvement Pull request with some product 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.

Replace per-table FileLog watch threads with a single shared reactor

4 participants