Repository navigation
Fix stale metadata in FileLog when a file is deleted and recreated - #101408
Conversation
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]>
|
Workflow [PR], commit [b92209c] Summary: ✅ AI ReviewSummaryThis 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 Findings
Tests
Final Verdict
|
|
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.
`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]>
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: |
There was a problem hiding this comment.
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:
- Batch 1 contains only
MOVED_FROM(a)-> this branch marksaasREMOVED, and cleanup erasesmeta_by_inode[old_inode]+ the meta file. - Batch 2 contains
MOVED_TO(b)for the same inode -> we recreate metadata forbwith offset0.
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).
There was a problem hiding this comment.
This does make sense, but let's do it separately
LLVM Coverage Report
Changed lines: 91.67% (66/72) | lost baseline coverage: 2 line(s) · Uncovered code |
|
Hi — could this be a backport candidate for Affected code: 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 |
`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]>
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]>
Fix stale metadata in FileLog when a file is deleted and recreated
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]>
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]>
Changelog category (leave one):
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
26.5.1.885