Skip to content

Fix FileLog on macOS re-reading a file renamed during a directory rescan - #122448

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:filelog-darwin-rename-during-scan
Sep 28, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:filelog-darwin-rename-during-scan

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

On macOS, FileLog sometimes read a file renamed inside the watched directory again from the beginning, inserting its rows twice. It showed up as a 02023_storage_filelog failure in Fast test (arm_darwin): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119625&sha=d8052ae24c4059bf592f7b999d09e5c3d6e978ba&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29

macOS has no inotify, so DirectoryWatcherBase diffs directory snapshots and pairs renames by inode. A pass lists the directory, calls stat on each entry and opens a kqueue watch for new names, and none of that is atomic with a rename. A rename landing in between leaves the inode under neither name (or a recreated name under a new inode), so the diff emits REMOVED + ADDED instead of a move and StorageFileLog restarts the file at offset 0.

After installing the watches, the watcher now drains its kqueue. If the directory changed structurally (an entry added, removed or renamed, or a watched file renamed), the pass is discarded and repeated at once, and nothing is emitted from it. Appends never discard a pass. The startup scan uses the same check, so a rename racing table startup is not read again either. The Linux watcher is unchanged.

Related: #119625

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fix FileLog on macOS re-reading a file from offset 0 when it is renamed during a directory rescan.


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

Version info

  • Merged into: 26.10.1.944-master (included in 26.10 and later)

groeneai and others added 3 commits September 26, 2026 10:13
The macOS `DirectoryWatcherBase` rebuilds inotify events by diffing directory
snapshots, and it recognizes a rename only when one inode leaves one name and
appears under another. A scan lists the directory and then runs `stat` on each
entry, so a rename that lands in between leaves the renamed file under neither
of its names (or under both). The diff then reports `REMOVED` + `ADDED`, and
`StorageFileLog` reads the file again from offset 0, so its rows are inserted
twice.

After each scan, drain the kqueue again. If the directory itself changed
(`NOTE_WRITE`, `NOTE_LINK`, `NOTE_RENAME` or `NOTE_DELETE` on the directory),
a watched file was renamed, or a listed file was gone when it was `stat`-ed,
the scan is discarded and repeated at once, and nothing is emitted from it.
Appends and attribute changes never discard a scan. A drain that consumed any
event makes the next `poll` return at once, so no change is noticed later than
before. The Linux (inotify) watcher is unchanged.

The new pausable fail point `file_log_directory_watcher_pause_after_listing`
sits between the listing and the `stat` calls, which lets the new test rename
a file inside a scan deterministically. The test runs only on macOS
(`Fast test (arm_darwin)`) and is skipped on other platforms.

Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/36145476798/job/108191212002
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119625&sha=d8052ae24c4059bf592f7b999d09e5c3d6e978ba&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
Related: ClickHouse#119625

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test renamed the only listed file away inside the paused scan, so the
scan's `stat` failed with ENOENT and discarded the pass by itself: the test
still passed without the post-scan kqueue drain. Add a second paused scan
that renames `b.txt` to `b.txt.1` and recreates `b.txt` at once, as log
rotation does. The listed name then still exists and `stat` succeeds on the
new file, so only the drain (the directory's `NOTE_WRITE` and the renamed
file's `NOTE_RENAME`) discards that scan; without it the rotated file is
read again from offset 0.

`wait_rows N` now collects rows until N of them arrived, 5 seconds per wait,
so the worst case stays at 40 seconds, below the 60-second test timeout of
`Fast test (arm_darwin)`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the post-scan drain comment to one line and drop its 'or under both' clause, which no longer holds with the list-then-stat scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings over 2 rounds) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test's only race (the listed file renamed away) also fails stat with ENOENT, so it stays green if the post-scan kqueue drain stops discarding scans AGREE, fixed @ a55c487 Added a log rotation inside the paused scan (rename, then the old name recreated at once): stat succeeds, so only the drain catches it
2 ❌ The startup seed scan skips the new check, so a rename racing table startup can still be read again DISAGREE A seed retried until consistent still differs from the names StorageFileLog::loadFiles recorded before the watcher started. That window exists on Linux too (inotify_add_watch runs on the watcher thread) and is not changed here
3 ❌ kevent failing with EINTR in the drain is read as "no events", so a raced scan could be committed DISAGREE xnu kqueue_scan returns queued events without waiting and reports EINTR only after a wait, which it reaches only when nothing was queued; kqueue(2): EINTR is "before any events were placed on the kqueue for return"
4 ❌ A consumer reading the watcher's event queue between the MOVED_FROM and MOVED_TO callbacks splits the pair, and the target is read from offset 0 DISAGREE, not this change Right as a mechanism, but independent of the scan: the publication path, FileLogDirectoryWatcher and StorageFileLog are unchanged here, and the Linux watcher publishes the pair through the same two callbacks. The window is the gap between two consecutive calls; I have no reproduction, so I left it
5 💡 A second rename of a just-renamed file between the drain and its watch open; a continuous rename storm delays events until one scan is undisturbed noted, not blocking Both are narrower than the fixed window; emitting from a disturbed scan is the bug itself

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20260926-163100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes on macOS, by construction: the new fail point pauses the watcher after it lists the directory, the test renames the file then, and the scan can only see the old name fail its stat. I have no macOS host, so the first run is this PR's Fast test (arm_darwin). The CI failure itself was 1 of 6233 arm_darwin runs.
b Root cause explained? The macOS watcher diffs directory snapshots and pairs a rename by inode. Its scan lists the directory, then stats each entry, so a rename in between leaves the inode under neither name (or both); the diff emits REMOVED + ADDED and StorageFileLog restarts the file at offset 0.
c Fix matches root cause? Yes: a scan that the directory changed under (directory NOTE_WRITE/NOTE_LINK/NOTE_RENAME/NOTE_DELETE, a watched file's NOTE_RENAME, or ENOENT on a listed file) is discarded and repeated at once; nothing is emitted from it. 02023_storage_filelog is untouched.
d Test intent preserved / new tests added? New 05263_file_log_rename_during_directory_scan.sh (macOS only, @@SKIP@@ elsewhere): a file renamed inside a paused scan keeps its offset, both for a plain rename and for log rotation (rename, then the old name recreated at once), which only the post-scan kqueue check catches; moving a file out and adding a new one is still picked up. Worst-case wait 40 s, under the lane's 60 s timeout.
e Both directions demonstrated? Not locally (no macOS host). Without the fix the plain rename section prints 1 2 3 4 5 instead of 5; without the kqueue check the rotation section prints 1 2 3 4 5 6 100 instead of 6 100 (both traced to the emitting lines). Here: Darwin arm64 compile of both files in the CI builder image (0 warnings), SKIP 50/50 on Linux; with the macOS gate forced and the pauses removed it matches the reference 10/10, and making the rotated file a new inode turns it red 3/3.
f Fix is general across code paths? The Darwin snapshot diff is the only place that reconstructs renames; the Linux inotify watcher reports them itself and is unchanged. Renames, renames over an existing name, moves out/in, creates and unlinks racing a scan all go through the same check.
g Fix generalizes across inputs (params/datatypes/wrappers)? No data types involved. Appends and attribute changes never discard a scan; a continuous rename or create storm emits nothing until one scan completes undisturbed.
h Backward compatible? (maintainer-approved exception only) Yes: no settings, formats or protocol changes. Only after a scan that raced a directory change are the events emitted one (immediate) scan later.
i Invariants and contracts preserved? A discarded scan keeps the snapshot and the drained deletes, exactly like the existing retry after a scan error; the NOTE_DELETE handling is unchanged; watches are still installed before any event is emitted; stopped is checked every iteration, and a failing scan still waits before retrying.

Session id: cron:clickhouse-impl-slot-4:20260926-092600

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b84400]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
direct_dictionary #2 FAIL dashboard IGNORED

AI Review

Summary

This PR tightens the macOS FileLog watcher so a directory rescan is discarded when kqueue shows concurrent structural changes, but it still does not make startup safe. The steady-state rescan hole is narrower now, yet the loadFiles -> watcher-seed window is still invisible to StorageFileLog, so the PR does not deliver the startup guarantee stated in the description.

PR Metadata

The selected Changelog category does not match the actual change. This patch changes production FileLog behavior on macOS, so CI Fix or Improvement is too narrow even if the regression was found in CI. The replacement should be:

### Changelog category (leave one):
- Bug Fix (user-visible misbehavior in an official stable release)

### Changelog entry:
Fix `FileLog` on macOS re-reading a file from offset 0 when it is renamed during a directory rescan.
Missing context / blind spots
  • ⚠️ I could not run the Darwin path locally in this Linux workspace, so the kqueue behavior review is from source tracing plus the PR discussion rather than an executable repro.
Findings

❌ Blockers

  • src/Storages/FileLog/DirectoryWatcherBase.cpp:381-394 still only stabilizes the watcher's private snapshot; it never reconciles StorageFileLog::file_infos, which was already populated earlier by loadFiles at src/Storages/FileLog/StorageFileLog.cpp:221-227. A rename/add/remove between those two steps therefore remains invisible: updateFileInfos sees no queued event, and openFilesAndSetPos still uses the stale names from loadFiles at src/Storages/FileLog/StorageFileLog.cpp:500-507. In the simplest trace, loadFiles records a.txt, the file is renamed to b.txt before the first stable seed pass, and the next read still tries to open a.txt. The startup race the PR body claims to fix is therefore still present.
    Suggested fix: either start the watcher before loadFiles and replay any startup events into file_infos, or make the seed path explicitly resync StorageFileLog's state instead of updating only snapshot.
Final Verdict

Changes requested.

LLVM Coverage Report

⚠️ No coverage measurement for commit 7b84400: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_4.profdata.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 7b84400695118956c8bd21f2b31bc3c50130156e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 026bba6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Finish Workflow / Post Hooks (new_tests_check.py) Both functional Bugfix validation arms report the new test 05263_file_log_rename_during_directory_scan as skipped, because it runs only on macOS, where the fixed watcher code is. So no arm can validate this Bug Fix, as the description states. The test itself passed in Fast test (arm_darwin) on this head PR-caused by design and owned by this PR (#122448): the resolution is a reviewer decision to accept the macOS-only validation
Mergeable Check, PR rollups, red only because of the row above (Failed: Workflow Post Hook) owned by this PR (#122448), as above

Session id: cron:our-pr-ci-monitor:20260926-223058

@Algunenano Algunenano self-assigned this Sep 28, 2026
@Algunenano

Copy link
Copy Markdown
Member

🕵 @groeneai I pushed 8318095 on top of your branch to simplify the fix. Please check it.

Changes:

  • Dropped the file_log_directory_watcher_pause_after_listing fail point and 05263_file_log_rename_during_directory_scan. A macOS-only test that skips everywhere else can't pass the Bugfix validation, so the PR is now a CI fix.
  • scan is back to the master version. The ENOENT tracking was redundant: any entry vanishing after the listing already posts a structural event on the directory fd.
  • The kqueue drain now runs after sync_file_watches instead of before it. With the drain before it, a newly named file renamed again before its watch was opened got ENOENT in sync_file_watches, was dropped from the snapshot, and the next pass emitted it as DW_ITEM_ADDED, so it was read again from offset 0.
  • The startup scan uses the same check (scan, sync watches, discard if the drain saw a structural change), as the AI review asked.

Tests on macOS arm64 with a standalone C++ harness that copies the watcher's scan, watches and drain. One file renamed every 20 µs next to 20 static files, 10 s per run (master: 5 s). Counted: startup scans missing a live file, and loop passes diffing a live file as removed.

Variant Rename only: startup / loop Rotation (rename + recreate): startup / loop
master 4409 / 8805 1643 / 3652
previous head (drain before sync_file_watches) 8049 / 265 397 / 198
8318095 0 / 0 0 / 0

Passes still complete under that rename storm, so it does not starve. clickhouse builds on macOS without warnings. All FileLog stateless tests passed 10 times each locally on an earlier revision of this change (before the drain moved after sync_file_watches).

@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked 8318095. Moving the drain after sync_file_watches fixes a real hole in my version: a new name renamed again before its watch was opened fell out of current, as you describe.

One regression from the new order. If a watched file is unlinked while scan is running, before it reaches the file, sync_file_watches closes its watch (DirectoryWatcherBase.cpp:306-315) before the drain runs, and closing the fd dequeues the NOTE_DELETE that VNOP_REMOVE queued on it (xnu knote_fdclose -> knote_drop). The directory NOTE_WRITE from the same unlink then discards the pass, so deleted never gets the name. If the name is recreated with the same inode before the next accepted pass, that pass diffs it as MODIFIED and StorageFileLog keeps the stale offset, which is what the comment on deleted warns about. Master accepted that pass and emitted REMOVED.

Closing the watches of departed names only once a pass is accepted (moving that loop after the structural check, in the startup scan too) keeps the delete. I can push that if you want it. I can only cross-compile the Darwin path here, so it would need a run of your harness.

@Algunenano

Copy link
Copy Markdown
Member

🕵 @groeneai Agreed, that's a real regression. I confirmed the kernel side on macOS arm64: with a NOTE_DELETE pending on a file watch, draining before close delivers it, closing first delivers nothing.

I fixed it in 7b84400 with an extra drain instead of deferring the close. scan_and_watch now runs scan, drains, runs sync_file_watches, drains again, and the pass is discarded if either drain saw a structural change. The startup scan and the main loop both use it.

A name missing from current was unlinked before the listing reached it, so its NOTE_DELETE is already queued and the first drain records it in deleted before sync_file_watches closes the watch. A name unlinked after the listing is still in current, so its watch stays open and the second drain gets the event. The second drain still covers renames during watch installation.

Harness (same as before, plus a thread that unlinks and recreates a watched file), counting departed watches closed while their file is unlinked and the name is not in deleted:

Variant Rename only: lost deletes Rotation: lost deletes
8318095 1 8
7b84400 0 3

The rotation leftovers are inodes that were renamed away from the watched name before being unlinked, so their NOTE_DELETE says nothing about the file now at that name. Startup misses and live files diffed as REMOVED stay at 0 in both runs, and clickhouse builds on macOS without warnings.

@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 28, 2026
@Algunenano Algunenano added pr-bugfix Pull request with bugfix, not backported by default and removed pr-ci labels Sep 28, 2026
@Algunenano
Algunenano added this pull request to the merge queue Sep 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b84400

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / direct_dictionary #2 dashboard confirmed_regression, client_time 0.286 -> 0.331 s (+15.8%), with the new server slower in 7 of 7 samples. The shard's own report does not flag this query (its only verdicts are unstable on optimize_time_filter_with_preimage #4 and #6). The query reads simple_key_direct_dictionary through dictGet, and this diff changes only the macOS branch of the FileLog directory watcher, which the Linux arm binary does not compile. On arm this query has a slow mode drawn per server process since the release binary became position independent: in master-vs-master runs it moved by more than 10% in 14 of 185 runs since 2026-09-16, against 2 of 228 before 2026-09-09, and 0 of 207 on amd a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)

PR is the workflow aggregator: it reports the row above and carries no separate failure.

146 of 146 check runs completed (120 passed, 25 not selected, 1 red: the shard above), Finish Workflow is green, and Mergeable Check and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260928-190407

Merged via the queue into ClickHouse:master with commit 1e5291b Sep 28, 2026
147 of 149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants