Skip to content

Do not let one bad file stop a FileLog table - #123595

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:filelog-one-bad-file-does-not-stop-table
Oct 3, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:filelog-one-bad-file-does-not-stop-table

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123368

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):

A FileLog file that cannot be opened (removed, a symlink whose target was removed, not readable by the server) no longer stops the table: the other files keep being consumed, and it is skipped, logged once and retried until it can be opened while the table is loaded, unless the directory reports that it was removed, renamed or replaced. With the default handle_error_mode, a record that cannot be parsed is now logged and skipped while the table streams into materialized views, instead of failing the whole insert together with the rows read from the other files; a direct SELECT still throws.

Description

On 26.8.10.6 and 26.3.33.24, one file of a FileLog directory that cannot be opened makes every read fail with CANNOT_READ_ALL_DATA, and a table that streams into materialized views inserts nothing for any file, even after that file is removed. With the default handle_error_mode, one line that does not parse fails the whole insert, so the rows read from the other files are lost.

Root cause: openFilesAndSetPos throws for the whole table when one file cannot be opened, and in the materialized view path it runs before updateFileInfos consumes the watcher events, so the file's removal is never applied. FileLogSource turns the parse error of one record into an exception for the whole insert.

Change:

  • A file that cannot be opened for a reason of its own (ENOENT, EACCES, EPERM, ELOOP) is logged once, skipped and retried on every round, and read from its start if it was missing. A regular file of a watched directory that is gone or replaced is left to the directory events, which keep a renamed file's offset. While a file is retried, a directory table polls with the existing backoff, because restoring a symlink target or a permission produces no directory event. Other errors (EMFILE) still fail the round.
  • While streaming to views, a record with a parse error is skipped and logged once per file per chunk; the rest of the file is read at once. No new setting.
  • A view created while the background task checked for views no longer leaves existing files unread until a directory event.

Validation: new test 05318_file_log_one_bad_file fails on master and each of seventeen mutations turns it red; 100 randomized runs and the 19 FileLog tests pass. With items 1a (#123395) and 1b (#123404), a .gz moved into the directory no longer stops the table.


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

Version info

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

groeneai and others added 8 commits October 2, 2026 03:15
A FileLog table opened every changed file in openFilesAndSetPos() and threw
CANNOT_READ_ALL_DATA "Stream is in bad state" for the whole table when one of
them could not be opened (removed after the watcher event, a dangling symlink,
not readable by the server). In the materialized view path that call runs
before updateFileInfos(), the only place where watcher events are consumed, so
even the REMOVED event of that file was never applied: every later round threw
at the same file and the table stopped for all files until it was re-attached.
Now a file that cannot be opened for a reason of its own (ENOENT, EACCES, EPERM,
ELOOP) is logged once, skipped and retried on every round. While such a file
exists, a directory table polls with the existing backoff instead of waiting
for a directory event, because fixing a permission or restoring a symlink target
produces none. Other open errors (EMFILE, ENFILE, ...) fail the round as before.

With the default handle_error_mode, one record that does not parse failed the
whole insert of the round in the materialized view path, so the rows already
read from the other files and the good rows of the same batch were not inserted.
While streaming to views, such a record (a parse error, isParseError()) is now
skipped and one error per file per chunk is logged; other exceptions still fail
the round. A call that only skipped records while the files still have data
returns a chunk without rows instead of finishing the source, so the remaining
records are read in the same round. A direct SELECT still throws.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…opened file

A call of FileLogSource::generate() that only skipped broken records used to
return a chunk without rows to keep reading in the same round. Every view runs
its query on every block it receives, so a view whose query gives a row on
empty input (an aggregate without GROUP BY, such as SELECT count()) wrote a
fake row for each such chunk. Now such a call closes the stream as before and
tells the storage that its files still have data; streamToViews() then reports
the round as not stalled and threadFunc() starts the next round at once, from
the offset close() stored, instead of waiting for a directory event. Each such
round consumes at least one record, so this terminates.

While a file could not be opened, its path may start to point to another file
(the target of a symlink is created again). openFilesAndSetPos() kept the old
inode and its offset, so the new file was read from the old file's offset and
its meta was stored under the old inode; after a reload the table did not find
that inode and read the file again. A reopened file whose inode changed now
drops the old meta (in memory and on disk) and is read from the start.

The engine documentation now says which files are retried: a symlink is read
only if its target exists when the table finds it, which is unchanged.

The test gains a count() view (no zero rows), a direct SELECT table (a removed
symlink target logged once, the new target read once across DETACH/ATTACH, a
parse error still fails the query) and exact log counts for the skipped records.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The direct `SELECT` arm of `05318_file_log_one_bad_file` used a `FileLog`
table on a directory. On macOS the directory watcher keeps a watch opened
through the symlink, so removing its target makes it report `link.jsonl` as
REMOVED; the first direct `SELECT` consumed that event in `updateFileInfos`
before `openFilesAndSetPos`, the file was dropped without an open attempt, and
the `Cannot open file` log count was 0 instead of 1. Linux has no event for a
target outside the watched directory, so it passed there.

The arm now uses a table on the single file `link.jsonl`, which has no
directory watcher: every direct `SELECT` opens the file on both platforms. The
record that does not parse is appended to the same file, so no second file and
no extra reload are needed.

The skipped-record summaries are now also checked to count at most 10 records
each (one `generate` call stops after 10 failed polls), so a single summary for
the whole file no longer passes.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ld inode

A file that a round saw missing (`ENOENT`, `ELOOP`) is now read from its
start when it can be opened again, even if the new file has the old inode
number, which ext4 gives to the next file created after a removal. Before,
only a changed inode number reset the offset in `openFilesAndSetPos`, so such
a file was read from the old offset: its first bytes were skipped, or, if it
was shorter, the shrink check failed the round. The new `path_missing` flag of
`FileContext` records the missing path until the file is opened again; it is
cleared after `getInode`, so a file that vanishes again before the `stat` is
still treated as new in the next round.

The test's direct `SELECT` arm now recreates its target with the same inode
after it was read.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a round finds the path of a file missing (`ENOENT`, `ELOOP`), its
saved offset is now reset to 0 at once, in memory and in the meta file.
Before, only an in-memory flag recorded it, so after `DETACH`/`ATTACH` or a
server restart a file created again with the old inode number before the
next read was read from the old offset and its first bytes were lost. The
`path_missing` flag is removed; a reopened file whose path now leads to
another inode is still re-keyed.

The test's direct `SELECT` arm reloads the table before it reads the
recreated target, and recreates it once more with a new inode to check that
it is not read again after a reload.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…directory events

A regular file of a watched directory whose path is gone (`ENOENT`) or
holds another inode when it is opened is now left to the pending directory
events, which drop it or give its offset to the new name. Before, the
restart from offset 0 of a missing path also hit a file renamed inside the
directory, so it was read again from its start, and the reopen of a file
that could not be opened before took over the offset of a file moved over
it (and, in a debug build, failed the `meta_by_inode` size assertion). The
restart and the re-key stay for single-file tables and symlinks, whose
target changes produce no directory event.

Two test arms: a file renamed after a partial read, and a file moved over a
symlink that cannot be opened.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…file fails the round

The flag that makes a directory table retry a file that could not be
opened on a timer (`has_files_to_reopen`) is now set as soon as the file
fails in `openFilesAndSetPos`, so an exception from a later file of the
same round no longer turns the retry into a wait for a directory event.

A test arm checks that skipped records are reported per file when one
read covers two files. The test waits 60 s instead of 120 s per step. The
documentation says the retry holds while the table is loaded.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop two comments that restate the read_more_after_skipped_records field doc and the isTrackedByDirectoryEvents doc; shorten the inode-change comment.

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 Oct 2, 2026
@groeneai

groeneai commented Oct 2, 2026 •

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

Pre-publication review by an independent model (engine: codex; 16 findings over six rounds) plus my own review (14 findings). Bounce cap reached: published as-is after round 6, the final round. Its fix commit 173f57a74098 was checked by my review and the recorded test evidence, not by a new second-model run. Residual findings are listed below as noted, none blocking.

# Sev Finding Verdict Evidence / action
1 ⚠️ A zero-row chunk after a stretch of skipped records reaches every view, so a view with an aggregate and no GROUP BY writes a 0 row AGREE, fixed in 5723c0d61448 The source closes as before and the next round starts at once; the count() view gets no 0 rows
2 ❌ A reopened file whose path now points to another file keeps the old inode and offset AGREE, fixed in 5723c0d61448 Re-keyed to the new inode at offset 0; not read again after DETACH/ATTACH
3 ❌ A symlink dangling when the table finds it is never retried AGREE (wording), 5723c0d61448 Discovery unchanged (same as master, never stops the table); docs and changelog no longer promise it
4 ⚠️ No test that a direct SELECT still throws on a parse error AGREE, fixed in 5723c0d61448 Direct SELECT arm
5 ⚠️ Log checks were presence-only, then still passed one summary for the whole file AGREE, fixed in 2e3066985d4d Exactly one Cannot open file line; skipped counts sum to 50 with at most 10 per line
6 ⚠️ On macOS the watcher reports a symlink whose target was removed as REMOVED, so the direct-SELECT arm never opened the file and its log count was 0 AGREE, fixed in 2e3066985d4d The arm uses a single-file table, which has no directory watcher
7 ❌ A file removed and created again with the same inode number (ext4 reuses it every time) resumes at the old offset AGREE, fixed in 92dc0808d49a A path that led to no file is treated as a new file when it opens again; the test recreates the target with the same inode
8 ⚠️ A second --send_logs_level is rejected by the client DISAGREE clickhouse-test always passes --allow_repeated_settings (tests/clickhouse-test:2735); 13 existing tests use the same form
9 ⚠️ Needs no-parallel like older FileLog view tests DISAGREE Isolated paths and database; 120 s per wait vs 5-15 s measured in 100 parallel runs; the watch loop no longer holds a schedule-pool slot
10 💡 DECLARE doc string without inline code AGREE, fixed in 5723c0d61448 Backticks added
11 💡 A retry round busy-polls each idle stream for poll_timeout_ms noted Existing pollBatch behaviour for a stream with no changed file; bounded by the backoff
12 ❌ The missing-path state of round 3 lived only in memory, so a reload before the file came back resumed the old offset AGREE, fixed in 360374c655d2 The offset is reset to 0 in the meta file as soon as the path is found missing; the test reloads the table before it reads the recreated file
13 💡 While a file cannot be opened, the other files of a directory table are read on the backoff timer, up to poll_directory_watch_events_backoff_max, not on their directory events noted The table stops completely on master in this state; no row is lost
14 ❌ The reset of row 12 also hit a file renamed inside the watched directory: the view's round opens the old name before it applies the rename, so the new name inherited offset 0 and was read again (also found in my own review) AGREE, fixed in 4ad3994358f6 A regular file of a watched directory whose path is gone is left to the directory events; the reset stays for single-file tables and symlinks; test: partial direct read, rename, then a view
15 ❌ My review: the reopen of a file that could not be opened took over the offset of a file moved over it, and a debug build failed the meta_by_inode size assertion AGREE, fixed in 4ad3994358f6 A regular file of a watched directory whose path now holds another inode is left to the directory events; test: a file moved over a dangling symlink
16 ⚠️ The retry flag was published only after the open loop, so another file throwing later in the same round turned the timed retry of an unopenable file into a wait for a directory event AGREE, fixed in 173f57a74098 The flag is set as soon as a file fails; checked by hand (an unreadable file plus a shrunk file: 24 timed retries in 12 s instead of 2)
17 ⚠️ The skipped-records log was checked for one file only, so attributing a whole chunk to its first file would pass AGREE, fixed in 173f57a74098 Test arm with two files of broken lines read in one call; per-file totals 3 and 4; a mutation that reports all of them under one name turns it red
18 ⚠️ Only ENOENT is tested of the four errno values AGREE, checked for 173f57a74098 CI runs the server as root, so EACCES cannot be a test; EACCES and ELOOP checked by hand on a non-root server, each red on a build without that errno
19 💡 "Retried until it can be opened" does not hold across a restart while a single-file path is missing (also in my review) AGREE, fixed in 173f57a74098 Docs and changelog say "while the table is loaded"; loading such a table fails as on master
20 💡 My review: with the two arms of round 5 the test exceeded the 600 s per-test timeout on master AGREE, fixed in 173f57a74098 Waits are 60 s; the test fails on master in 440 s with output instead of Timeout!
21 ❌ Second-model run on f04cc3839f87 (fix for the flaky check): a readable file atomically replaced after a partial read is read from the old offset, then again from 0 DISAGREE Same duplicate rows on master ef48c8b1 (3 of 3 runs); this PR re-checks the inode only after a failed open, so that path is master's and out of scope here
22 ⚠️ Same run: the test does not force a view to attach between the two view checks DISAGREE Forcing it needs a new server-wide failpoint and a no-parallel test; a build with a 400 ms sleep between the checks fails 6 of 6 runs without the fix and passes 6 of 6 with it

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261002-172600

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05318_file_log_one_bad_file fails on master on every run (nothing reaches the target table) and passes with the fix.
b Root cause explained? openFilesAndSetPos throws for the whole table when one file cannot be opened, and in the materialized view path it runs before updateFileInfos, so the removal of that file is never applied and every round throws again. In default mode FileLogSource turns one record's parse error into an exception for the whole insert, losing the rows of the other files read in that round.
c Fix matches root cause? Yes. The open loop confines a file-local open failure (ENOENT/EACCES/EPERM/ELOOP) to that file and retries it on a timer, also when a later file of the same round throws; the source's error callback skips a parse error while streaming to views. Nothing is widened or tagged.
d Test intent preserved / new tests added? New regression test with one phase per mechanism plus a direct SELECT arm on a single-file table (no directory watcher, so it behaves the same on Linux and macOS), two directory arms for a file renamed after a partial read and a file moved over a symlink that cannot be opened, and an arm with two files of broken lines read in one call; seventeen mutations of the fix each turn it red, including one that logs a single summary for the whole file and one that reports all skipped records under one file name. The existing FileLog tests are unchanged and pass.
e Both directions demonstrated? Yes, on Build-ID verified binaries: master FAIL (nothing inserted), fix OK. Also measured on 26.8.10.6 and 26.3.33.24 (same stop and row loss).
f Fix is general across code paths? Both read paths (materialized views and direct SELECT) go through the fixed open loop. The consumer and the meta handling already tolerate a file without a reader. Single-file tables already poll on a timer.
g Fix generalizes across inputs (params/datatypes/wrappers)? Any format (parse errors via isParseError); other exceptions and other open errors (EMFILE, ...) still fail the round. Covered: a run of broken lines longer than one read call, a file of only broken lines, a symlink target recreated with the same inode across a reload, and with a new inode, an aggregate view without GROUP BY, handle_error_mode = 'stream' unchanged, direct SELECT unchanged.
h Backward compatible? (maintainer-approved exception only) No setting or format change. In the materialized view path a broken record is now skipped and logged instead of failing the insert; this is the per-file behaviour the issue asks for, and it is documented.
i Invariants and contracts preserved? Offsets: a file that cannot be opened but still exists (EACCES, EPERM) keeps its offset, a skipped record is consumed like a parsed one. A call that only skipped records ends the stream as before (no empty block reaches the views) and makes the next round start at once from the stored offset; each such round consumes at least one record. For a single-file table or a symlink, a path found missing resets the file's saved offset to 0 at once, also in the meta file, and a reopened file with another inode is re-keyed; a regular file of a watched directory that is gone or replaced is left to the directory events, which keep a renamed file's offset and the one-to-one file_names/meta_by_inode mapping. The new flags read by the background thread are atomic.

Session id: cron:clickhouse-impl-slot-5:20261002-164503

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f04cc38]

Summary: ✅


AI Review

Summary

This PR hardens FileLog so one unreadable file no longer stops the whole table, and it changes the materialized-view path to skip parse errors under the default handle_error_mode while keeping direct SELECT strict. The implementation and tests cover most of that surface well, but one retry-scheduling bug is still present: when an unreadable file and a long run of skipped parse errors happen in the same round, the current head still bypasses the configured reopen backoff and can spin inside one background task for up to MAX_THREAD_WORK_DURATION_MS.

Findings

⚠️ Majors

  • [src/Storages/FileLog/StorageFileLog.cpp:889] streamToViews still returns stalled && !read_more_after_skipped_records, so a stream that stopped after skipping broken records forces an immediate next round even when openFilesAndSetPos has already set has_files_to_reopen for another file. In that mixed case the unreadable file is retried immediately until the skipped-record run is drained or the 60 s work cap fires, instead of honoring poll_directory_watch_events_backoff_*. That breaks the retry contract this PR is adding for unreadable files and can monopolize the background task.
  • Suggested fix: make the backoff path win whenever has_files_to_reopen is set, and use the immediate round only for the pure "skipped records, no reopen pending" case.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required: preserve the configured reopen backoff when has_files_to_reopen and read_more_after_skipped_records are both true.

LLVM Coverage Report

Measured on commit f04cc38.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 131/133 (98.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 2, 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 2, 2026

return updateFileInfos();
bool stalled = updateFileInfos();
return stalled && !read_more_after_skipped_records;

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.

read_more_after_skipped_records overrides the stalled return unconditionally here, so it also bypasses the new backoff path for has_files_to_reopen. If one file is still failing to open and another file hits a long run of parse errors, streamToViews keeps returning false, the outer loop stays inside the same background task, and the unreadable file is retried immediately until MAX_THREAD_WORK_DURATION_MS expires instead of on poll_directory_watch_events_backoff_*.

That breaks the retry contract this PR is adding for ENOENT/EACCES/EPERM and can monopolize the background thread for up to 60 s. I think the stalled/backoff path still needs to win whenever has_files_to_reopen is set, even if another stream asked for one more immediate round to drain skipped records.

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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 ⚠️

10 object files changed (-903.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/FrequencyHolder.cpp.o 1.12 MiB 207.93 KiB -943.97 KiB (-81.95%)
src/CMakeFiles/dbms.dir/Storages/FileLog/FileLogSource.cpp.o 108.90 KiB 129.45 KiB +20.55 KiB (+18.87%)

720 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.

Compile time of recompiled translation units

11 translation units recompiled, 30 s compile time in total, 11 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.11 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.7 s (+14%) in total before that adjustment.

Job report

`threadFunc` counts the attached views twice: once to decide whether to
stream, and again at the end to choose between a timed reschedule and
waiting for a directory event. Both calls take the global
`databases_mutex`. When a materialized view is created between the two
calls, the first one sees no view and nothing is read, the second one
sees the view, and the task waits for a directory event. Files that
were already in the directory are then not read until one of them
changes, or forever in a directory that does not change.

Under parallel DDL the second call can wait for the mutex long enough
for this to happen. All 5 failures of the new test in its flaky check
(100 runs) were this: 3 tables started their first round 203 to 371 s
after `CREATE MATERIALIZED VIEW`, when another file was moved into the
directory, and 2 never started; every other table started within about
a second.

When the first check finds no view, reschedule after the backoff, as is
already done when the second check finds none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov 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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into ClickHouse:master with commit 6cfa14c Oct 3, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 4, 2026
…hanged

The early return of `streamToViews` added for globs skipped the read when every
file had `NO_CHANGE` status. A file that could not be opened (ClickHouse#123595) keeps
`NO_CHANGE` status with `open_failed` set and is retried only by
`openFilesAndSetPos`, so after the merge with master it would not be retried
until another file changed.

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). 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