Skip to content

Fix stale metadata in FileLog when a file is deleted and recreated - #101408

Merged
Avogar merged 12 commits into
ClickHouse:masterfrom
azat:file_log-metadata-fix
May 20, 2026
Merged

Avogar merged 12 commits into
ClickHouse:masterfrom
azat:file_log-metadata-fix

Conversation

@azat

@azat azat commented Mar 31, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

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

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

Fix stale metadata in FileLog when a file is deleted and recreated

Fixes: #101309
Logs: https://pastila.nl/?001e16c3/87f28c9a4bf3a4d07a0c4c2542aa0d66#enidC1MvnOjGpouTJ8dH5A==GCM

Version info

  • Merged into: 26.5.1.885

azat and others added 2 commits March 31, 2026 17:35
When a watched file is deleted and recreated with the same name,
`DW_ITEM_REMOVED` marks the context as REMOVED, but the immediately
following `DW_ITEM_ADDED` overwrites it to OPEN with the new inode.
The cleanup loop only removes entries with REMOVED status, so the
old inode's `meta_by_inode` entry (carrying the accumulated read
position) is never cleaned up. This leaves two `meta_by_inode`
entries pointing to the same on-disk meta file, and `serialize`
throws a logical exception when it reads the stale position from
disk for the new entry.

Fix by explicitly erasing the old inode's `meta_by_inode` entry and
removing the stale on-disk meta file in `DW_ITEM_ADDED` and
`DW_ITEM_MOVED_TO` handlers when the inode changes. The on-disk meta
is immediately rewritten by `serialize` in `openFilesAndSetPos`.

Logs: https://pastila.nl/?001e16c3/87f28c9a4bf3a4d07a0c4c2542aa0d66#enidC1MvnOjGpouTJ8dH5A==GCM

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b92209c]

Summary: ✅


AI Review

Summary

This PR replaces per-name watcher aggregation with chronological event processing and fixes the stale-metadata behavior for delete+recreate / rename+recreate in the same drained batch. One correctness gap is still live: rename handling remains destructively batch-local, so when DW_ITEM_MOVED_FROM and DW_ITEM_MOVED_TO are split across watcher drains, persisted offsets can still be dropped and the renamed file can be reread from offset 0.

Findings
  • ⚠️ Majors
  • [src/Storages/FileLog/StorageFileLog.cpp:1015] DW_ITEM_MOVED_FROM is marked as REMOVED, and cleanup erases inode/meta in the same updateFileInfos pass. Because DirectoryWatcherBase wakes storage after each read, rename pairs can be split across getEventsAndReset batches under queue pressure. In that split, batch 1 can erase metadata on MOVED_FROM(a), and batch 2 then recreates MOVED_TO(b) metadata with zero offset, causing duplicate reads.
  • Suggested fix: correlate rename pairs via inotify cookie or defer destructive cleanup of move-out entries until unmatched moves are known final.
Tests
  • ⚠️ Add a focused regression that forces a rename pair to be applied across two getEventsAndReset batches (or unit-test equivalent around event application) and verifies offset continuity for the renamed file.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Make rename handling resilient when DW_ITEM_MOVED_FROM/DW_ITEM_MOVED_TO arrive in different batches.
  2. Add regression coverage for that cross-batch rename path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 31, 2026
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
@Avogar Avogar self-assigned this Apr 1, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

Addresses review feedback on the new cleanup added in `DW_ITEM_ADDED`
and `DW_ITEM_MOVED_TO`: the unguarded `meta_by_inode.erase(old_inode)`
can drop the meta tracking a *different* file when events from a rename
are processed in the same batch.

Concrete sequence flagged by the reviewer:
1. `a.log` (inode 42) is renamed to `b.log` (`DW_ITEM_MOVED_TO`
   processed first); meta_by_inode[42].file_name becomes "b.log".
2. A new `a.log` is created with inode 77 in the same batch
   (`DW_ITEM_ADDED`); context_by_name["a.log"] still holds inode 42,
   so the cleanup would erase meta_by_inode[42] — losing `b.log`'s
   offsets.

Mirror the guard used in the removal path: only erase the old inode's
meta and the on-disk meta file when meta_by_inode[old_inode].file_name
equals the current event's file_name.
Exercises the scenario fixed in this PR: a file in a `FileLog`
directory is fully read, then deleted and recreated under the same
name with new content (which gets a fresh inode). Before the fix, the
stale `meta_by_inode` entry and on-disk meta file for the previous
inode could trip the
`Last stored last_written_position ... is bigger than current` check
in `StorageFileLog::checkOffsetIsValid` (see issue ClickHouse#101309) or
otherwise mis-track the new file's offsets.

The test inserts an initial set of rows via the FileLog -> MV path,
deletes the source file, recreates it with new content, and verifies
the new rows flow through to the destination table.

Tagged `no-parallel` for the same reason as `02968_file_log_multiple_read`:
under heavy parallel load `BackgroundSchedulePool` scheduling latency
can push the FileLog -> MV detection past the wait window.
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
`StorageFileLog::updateFileInfos` returned early without consuming the
directory watcher's queue when `file_infos.file_names` was empty. In the
delete-and-recreate scenario the cleanup loop empties `file_names` after
the `DW_ITEM_REMOVED` for the only watched file, so the subsequent
`DW_ITEM_ADDED`/`DW_ITEM_MODIFIED` for the recreated file would sit in
the watcher queue forever. `streamToViews` reports the table as idle in
a tight loop, and the new content is never read.

Move the empty-`file_names` guard into the `!directory_watch` branch so
the directory-watching path always drains the event queue.

Reproduces with the test added in this PR (`04242_file_log_delete_recreate`).

CI failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101408&sha=efc87889180b7383177cbc404f1558135265022d&name_0=PR&name_1=Fast%20test
PR: ClickHouse#101408

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
alexey-milovidov and others added 5 commits May 19, 2026 11:19
In `StorageFileLog::updateFileInfos`, the directory-watcher handlers for
`DW_ITEM_ADDED` and `DW_ITEM_MOVED_TO` unconditionally pushed
`file_name` to `file_infos.file_names`, then reconciled an existing
`context_by_name` entry by overwriting it. If a single watcher batch
delivers `DW_ITEM_REMOVED(a.csv)` followed by `DW_ITEM_ADDED(a.csv)`,
the `REMOVED` handler only flips status to `REMOVED` (it does not touch
`file_names`), and the `ADDED` handler then sees the still-present
`a.csv` entry and reuses it - but `file_names` had already been
appended with a second `a.csv`. In debug builds this can trigger the
final size invariant `file_names.size() == meta_by_inode.size() ==
context_by_name.size()`; in release builds it leaves duplicate slots
and duplicate reads.

Only push the name into `file_names` when emplacing a fresh
`context_by_name` entry. For the same-batch remove+add path the entry
is reused, so the existing `file_names` slot is preserved unchanged.

Addresses review comment on
ClickHouse#101408.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The `DW_ITEM_ADDED` and `DW_ITEM_MOVED_TO` branches of
`StorageFileLog::updateFileInfos` shared a non-trivial context-update +
meta cleanup block (lookup `context_by_name`, perform inode-replacement
cleanup guarded by filename ownership, either reset the existing
context entry or push a fresh slot to `file_names`).

Pull this into a single private method `StorageFileLog::onFileAppeared`
so the two branches only differ where they genuinely differ — the
`meta_by_inode` insertion vs. rename-from-old-name logic — and so the
ownership-guarded cleanup lives in one place.

No behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`FileLogDirectoryWatcher::Events` was a `std::unordered_map<name,
file_events>`, so `StorageFileLog::updateFileInfos` walked events in
hash order over file names. Within each name the per-file vector
preserved chronology, but cross-name order was lost.

That breaks the rename-plus-recreate case where, in one watcher batch,
file `a` (inode 42) is renamed to `b` and a fresh `a` (inode 99) is
created. Inotify emits, in order: `DW_ITEM_MOVED_FROM(a)`,
`DW_ITEM_MOVED_TO(b)`, `DW_ITEM_ADDED(a)`. With the per-name map:

- key `a`: [`MOVED_FROM`, `ADDED`]
- key `b`: [`MOVED_TO`]

If hash iteration picks `a` first, `ADDED(a)` looks up
`meta_by_inode[42]` — whose `file_name` is still `"a"` because the
rename pair for `b` has not been observed yet. The filename-ownership
guard introduced in the previous fix passes, so we erase
`meta_by_inode[42]` and `a.bin`. Then `MOVED_TO(b)` runs, finds no
entry for inode 42, and creates a fresh meta with zero offsets,
losing `b`'s persisted progress and causing duplicate reads of `b`.

Make the cleanup order-independent by switching `Events` to a flat
`std::vector<pair<name, EventInfo>>` populated in the order the
callbacks fire. The MODIFY-event dedup that previously lived inside
the per-name `FileEvents` struct is preserved as a side
`std::unordered_set<name>` cleared together with `events` on
`getEventsAndReset`. `updateFileInfos` now walks a single flat loop
and so observes rename pairs before any subsequent `ADDED` on the
source name; `onFileAppeared`'s ownership guard sees the post-rename
`file_name` in `meta_by_inode` and skips the destructive cleanup as
intended.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Exercises the cross-name event-ordering hazard described in the
previous commit: within one watcher backoff window, rename `a.csv` to
`b.csv` and immediately recreate `a.csv` with a fresh inode. Inotify
emits `IN_MOVED_FROM(a)`, `IN_MOVED_TO(b)`, `IN_CREATE(a)` in that
order; with the previous per-name-aggregation map, iterating in hash
order over `a` first caused the ownership-guarded cleanup to erase
the inode-42 meta (still claimed by `a` at that point) and drop
`a.bin`, then the later `MOVED_TO(b)` rebuilt the meta with zero
offsets and `b.csv` was re-read from the start — yielding duplicate
emissions of `1, 2, 3` and a final row count of 9 instead of 6.

After the fix, events are walked in chronological order and the
ownership guard sees the post-rename `file_name`, so each row is
emitted exactly once.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
case DirectoryWatcherBase::DW_ITEM_MOVED_TO:
case DirectoryWatcherBase::DW_ITEM_REMOVED:
/// The file **left** the directory
case DirectoryWatcherBase::DW_ITEM_MOVED_FROM:

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.

DW_ITEM_MOVED_FROM is treated as immediately REMOVED, and cleanup in the same updateFileInfos pass can still be order-dependent across getEventsAndReset batches.

DirectoryWatcherBase calls wakeUp after each read, so a rename pair can be split if one read ends at a queue boundary under load. Concrete trace:

  1. Batch 1 contains only MOVED_FROM(a) -> this branch marks a as REMOVED, and cleanup erases meta_by_inode[old_inode] + the meta file.
  2. Batch 2 contains MOVED_TO(b) for the same inode -> we recreate metadata for b with offset 0.

That drops persisted progress for the renamed file and can re-read old rows. Please make rename handling resilient across batches (for example, pair IN_MOVED_FROM/IN_MOVED_TO by cookie, or defer destructive cleanup until unmatched moves are known final).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This does make sense, but let's do it separately

@clickhouse-gh

clickhouse-gh Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 91.67% (66/72) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@azat
azat requested a review from Avogar May 20, 2026 08:49
@Avogar
Avogar added this pull request to the merge queue May 20, 2026
Merged via the queue into ClickHouse:master with commit 359b70b May 20, 2026
165 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: StorageFileLog::updateFileInfos and FileLogDirectoryWatcher::getEventsAndReset — core code present in all supported branches.

Why this might apply: The bug affects FileLog storage which has existed since ClickHouse v22.3. The LOGICAL_ERROR exception ('Last stored last_written_position in meta file is bigger than current last_written_pos') can crash server in debug builds and indicates data integrity issues. The fix is low-risk (changes event storage order and adds cleanup logic) and addresses a user-reported stress test failure.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
`StorageFileLog::updateFileInfos` returned early without consuming the
directory watcher's queue when `file_infos.file_names` was empty. In the
delete-and-recreate scenario the cleanup loop empties `file_names` after
the `DW_ITEM_REMOVED` for the only watched file, so the subsequent
`DW_ITEM_ADDED`/`DW_ITEM_MODIFIED` for the recreated file would sit in
the watcher queue forever. `streamToViews` reports the table as idle in
a tight loop, and the new content is never read.

Move the empty-`file_names` guard into the `!directory_watch` branch so
the directory-watching path always drains the event queue.

Reproduces with the test added in this PR (`04242_file_log_delete_recreate`).

CI failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101408&sha=efc87889180b7383177cbc404f1558135265022d&name_0=PR&name_1=Fast%20test
PR: ClickHouse#101408

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
In `StorageFileLog::updateFileInfos`, the directory-watcher handlers for
`DW_ITEM_ADDED` and `DW_ITEM_MOVED_TO` unconditionally pushed
`file_name` to `file_infos.file_names`, then reconciled an existing
`context_by_name` entry by overwriting it. If a single watcher batch
delivers `DW_ITEM_REMOVED(a.csv)` followed by `DW_ITEM_ADDED(a.csv)`,
the `REMOVED` handler only flips status to `REMOVED` (it does not touch
`file_names`), and the `ADDED` handler then sees the still-present
`a.csv` entry and reuses it - but `file_names` had already been
appended with a second `a.csv`. In debug builds this can trigger the
final size invariant `file_names.size() == meta_by_inode.size() ==
context_by_name.size()`; in release builds it leaves duplicate slots
and duplicate reads.

Only push the name into `file_names` when emplacing a fresh
`context_by_name` entry. For the same-batch remove+add path the entry
is reused, so the existing `file_names` slot is preserved unchanged.

Addresses review comment on
ClickHouse#101408.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Fix stale metadata in FileLog when a file is deleted and recreated
pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Jun 25, 2026
StorageFileLog could abort with a LOGICAL_ERROR when a watched file was
deleted and recreated reusing the same inode within one directory-watcher
backoff window:

  Last stored last_written_position in meta file a.csv is bigger than
  current last_written_pos (N > 0)

When the DW_ITEM_REMOVED and DW_ITEM_ADDED events for the same name are
drained together, updateFileInfos() processes DW_ITEM_ADDED first: it flips
the file status back to OPEN (so the later REMOVED-cleanup loop skips it) and
resets the in-memory FileMeta for the inode to offset 0. onFileAppeared()
only cleans up the on-disk meta when the inode CHANGES, so on inode REUSE
the stale on-disk meta (with the old, larger offset) is left behind. The
next serialize() then reads that larger stored offset and trips
checkOffsetIsValid().

PR ClickHouse#101408 covered the inode-change case (a fresh inode). This covers inode
reuse, which is deterministic on filesystems that recycle freed inodes
(e.g. ext4) and is what surfaced under stress in CI. A freshly added file is
read from offset 0, so any on-disk meta under its name is stale; remove it in
the DW_ITEM_ADDED branch so the on-disk and in-memory metadata stay
consistent. The DW_ITEM_MOVED_TO (rename) branch is intentionally left
unchanged: it preserves the consumed offset, and the moved-out name's on-disk
meta is already removed by the REMOVED-cleanup loop before the new inode is
seen.

Regression test 04342_file_log_delete_recreate_same_inode reproduces the
crash on an unfixed server (delete + immediate recreate, high watch backoff)
and passes after the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
StorageFileLog could abort with a LOGICAL_ERROR when a watched file was
deleted and recreated reusing the same inode within one directory-watcher
backoff window:

  Last stored last_written_position in meta file a.csv is bigger than
  current last_written_pos (N > 0)

When the DW_ITEM_REMOVED and DW_ITEM_ADDED events for the same name are
drained together, updateFileInfos() processes DW_ITEM_ADDED first: it flips
the file status back to OPEN (so the later REMOVED-cleanup loop skips it) and
resets the in-memory FileMeta for the inode to offset 0. onFileAppeared()
only cleans up the on-disk meta when the inode CHANGES, so on inode REUSE
the stale on-disk meta (with the old, larger offset) is left behind. The
next serialize() then reads that larger stored offset and trips
checkOffsetIsValid().

PR ClickHouse#101408 covered the inode-change case (a fresh inode). This covers inode
reuse, which is deterministic on filesystems that recycle freed inodes
(e.g. ext4) and is what surfaced under stress in CI. A freshly added file is
read from offset 0, so any on-disk meta under its name is stale; remove it in
the DW_ITEM_ADDED branch so the on-disk and in-memory metadata stay
consistent. The DW_ITEM_MOVED_TO (rename) branch is intentionally left
unchanged: it preserves the consumed offset, and the moved-out name's on-disk
meta is already removed by the REMOVED-cleanup loop before the new inode is
seen.

Regression test 04342_file_log_delete_recreate_same_inode reproduces the
crash on an unfixed server (delete + immediate recreate, high watch backoff)
and passes after the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Logical error: Last stored last_written_position in meta file A is bigger than current last_written_pos (B > C) (STID: 3574-3d8d)

5 participants