Skip to content

Add system.filelog_files with the read state of each FileLog file - #123542

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/system-filelog-files
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/system-filelog-files

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123368

Changelog category (leave one):

  • New Feature

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

Added the system.filelog_files table with one row per file of each FileLog table: the read offset, the current file size (so the unread part), the number of records read, the last poll time, the last exception and whether the table is consuming the file or is stuck on it.

Description

Item "Stalls are silent - add observability" of #123368: when a FileLog table stops ingesting, the only trace today is the server log. The new table has one row per (table, file): path, inode, current_offset, the live file_size (file_size - current_offset is the lag), num_records_read, last_poll_time, last_exception with its time, and state (consuming / stuck). Rows are shown only for tables with SHOW TABLES, as in system.kafka_consumers; temporary tables are not shown, and databases of external engines (MySQL, PostgreSQL) are not read.

StorageFileLog keeps a per-inode snapshot under its own mutex, since a background round holds file_infos_mutex for its whole duration and the direct SELECT readers change file_infos without it. A failed round marks every file it read, and every file with unread bytes (a round can fail before it reads, e.g. on a destination that rejects inserts), as stuck, since on master one error fails the round's whole insert; the next successful round that includes the file clears it. A file that cannot be opened (every round retries it) is stuck with that error until it opens. A file recreated with a reused inode starts over, one recreated with a new inode gets a new row, and a file truncated in place shows offset 0, since it is read again from its start.

On the issue's partial-last-line repro the row shows state = stuck, CANNOT_READ_ALL_DATA and 52 unread bytes.

Tests: 05316 (direct SELECT: offsets, sizes, counters, added/removed/renamed/recreated/truncated files, a file that cannot be opened, a reload, access, temporary tables, a lazy_load_tables table), 05317 (materialized view: stuck on a failed read, on a round failing before it, also after a truncation, and on a file that cannot be opened, then consuming again) and 05318 (an unreachable MySQL database). All fail on master (UNKNOWN_TABLE) and passed 50/50 randomized runs.


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

groeneai and others added 6 commits October 2, 2026 02:20
A stalled FileLog table (a partial last line, an unreadable file, any
read or insert error) leaves a trace only in the server log. The new
table has one row per file of each FileLog table: path, inode, the read
offset, the live file size (so the unread part), the number of records
read, the last poll time, the last exception and its time, and whether
the table is consuming the file or is stuck on it.

The state cannot be read from `file_infos`: a background round holds
`file_infos_mutex` for its whole duration, and the direct SELECT readers
mutate `file_infos` without it. So StorageFileLog keeps a small snapshot
under its own mutex, written where that state already changes: the file
set (constructor and `updateFileInfos`, which also restarts the
statistics of a re-added inode, as the meta is restarted at offset 0),
the stored offsets (`storeMetas`, `closeFilesAndStoreMeta`), the start
of a read of a changed file (`openFilesAndSetPos`), the record counter
(`FileLogConsumer::readNewRecords`), and the outcome of each background
round. A failed round marks every file it read as stuck, because on
master one error fails the round's whole insert pipeline; a later
successful round that includes the file marks it consuming again.

Rows are shown only for tables with `SHOW TABLES`, as in
`system.kafka_consumers`.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`threadFunc` records the round's exception from inside its catch
handler, where the memory tracker may still throw: a
MEMORY_LIMIT_EXCEEDED escaping a BackgroundSchedulePool task aborts
debug builds and skips the reschedule in release. Block it for the copy,
as `KeeperHandlingConsumer::rollbackToCommittedOffsetsNoThrow` does.

A table of a `lazy_load_tables` database is attached as a
`StorageTableProxy`, so the system table never showed it, even after
the stand-in was loaded and its FileLog was ingesting. Unwrap a proxy
that is already loaded; a stand-in that is not loaded has no read
state and is still skipped, without loading it.

05316 now also checks that `file_size` is NULL for a renamed file whose
name was reused before the table processed the rename, and the lazy
table case.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`CREATE TEMPORARY TABLE ... ENGINE = FileLog` is accepted, and the
temporary tables of every session live in the one shared
`_temporary_and_external_tables` database, so a user with `SHOW TABLES`
saw the paths, offsets and exception texts of other sessions' temporary
FileLog tables. Skip that database, as `system.tables`,
`system.columns` and the other per-table system tables do.

05316 now also processes the rename of a file whose name was reused and
checks that the renamed file keeps its offset and counters under its
new name while the new file starts from zero, and that a temporary
table is not shown.

Drop unused column includes.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`fillData` called `getTablesIterator` on every database, including
remote ones such as `MySQL` and `PostgreSQL`, which cannot hold a
FileLog table. Listing the tables of a `MySQL` database connects to the
remote server and throws `ALL_CONNECTION_TRIES_FAILED` when it is
unreachable, so every `SELECT` from `system.filelog_files` failed, even
with a filter on `database` (the filter is not pushed into `fillData`);
a `PostgreSQL` database cost one remote fetch per table on every
`SELECT`. Skip databases with `isExternal()`, as `system.mutations`,
`system.replicas` and the other engine-specific system tables do.

05318 attaches a `MySQL` database pointing at a closed port and checks
that the table can still be read.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`current_offset` of a loaded table comes from the stored metadata, while
`num_records_read`, `last_poll_time`, `last_exception` and `state` start
over. No test reloaded a table with a nonzero stored offset: the lazy
arm reads before it looks, and every other offset assertion follows a
read, after which the offset is overwritten anyway. So a load that did
not copy the stored offset passed every test while showing the whole
file as unread after each restart.

05316 now detaches and attaches the table after the processed rename
and checks that every file keeps its offset with zero records read.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A file that was read to its end is `NO_CHANGE`, and the watcher event of
a later append is applied only by `updateFileInfos()` at the end of
`streamToViews()`. So when a round fails before it reads, for example
because building the sink of a view's destination throws, the file is
not part of the round: the catch in `threadFunc()` marked nothing, the
queued event was never applied, and the file stayed `consuming` with an
empty `last_exception` while its new bytes were never read.

`setFilesException()` now also marks every tracked file that still has
unread bytes on disk (same inode, size above the stored offset), so such
a stall shows as `stuck` with the exception. Files of the round are
marked as before. The descriptions of `last_exception` and `state` and
the table documentation say so.

05317 swaps the destination of a view for a `Merge` table, which rejects
inserts while the insert is built, after the first record is consumed,
appends a record and checks that the file becomes `stuck` with
`NOT_IMPLEMENTED` and 8 unread bytes.

Related: ClickHouse#123368

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: my own cold review in each of seven rounds, plus an independent model (engine: codex) in five of them; 13 findings. Bounce cap reached - published as-is; residual findings listed below (rows 7, 8 and 13, all nits). The last round's change (row 9) was checked by my own review and its test, without a new second-model run.

# Sev Finding Verdict Evidence / action
1 ⚠️ setFilesException allocates inside the threadFunc catch handler, where the memory tracker can still throw; an escape skips the reschedule of a BackgroundSchedulePool task AGREE, fixed @ aaef15f LockMemoryExceptionInThread, as in KeeperHandlingConsumer::rollbackToCommittedOffsetsNoThrow
2 ⚠️ The file_size inode check (a renamed file whose name is reused) was untested AGREE, fixed @ aaef15f new arm in 05316; dropping the check turns it red
3 ⚠️ A table of a lazy_load_tables database had no rows (the stand-in is not a StorageFileLog) AGREE, fixed @ aaef15f a loaded stand-in is unwrapped without loading it; a not-loaded one has no read state and is not shown (documented); new arm in 05316
4 ⚠️ 05317 does not exercise the partial-last-line CANNOT_READ_ALL_DATA path DISAGREE every round failure, reader or downstream, reaches the same catch in threadFunc, covered by 05317; the partial-line row was checked by hand (it is the docs example), and a reference would pin the wedge that item 1 of #123368 fixes
5 ⚠️ Temporary FileLog tables of other sessions were listed: every session's temporary tables share one internal database AGREE, fixed @ bee5aa4 that database is skipped, as system.tables and system.columns do; documented; new arm in 05316
6 ⚠️ The rename arm never let the table process the rename, so a renamed file keeping its row and statistics was untested AGREE, fixed @ bee5aa4 05316 now processes it: the renamed file keeps its offset and record count, the new file starts from zero
7 💡 After a downstream failure the batch is skipped, yet state stays stuck until a later round reads the file AGREE, noted, not blocking matches the documented definition; skipped vs retried belongs to per-file isolation
8 💡 Files of one failed round share one exception text that does not name the file AGREE, noted, not blocking the round is the unit of failure on master; per-file attribution comes with per-file isolation
9 ⚠️ A round that fails before it reads (the views' insert cannot be built, e.g. a destination that rejects inserts) left a stalled file consuming with no exception: the appended file is not part of that round yet, and the next wake-up repeats it AGREE, fixed @ d334a60 a failed round also marks every file with unread bytes; new arm in 05317 (the view's destination is replaced by a Merge table, then a record is appended); reverting it turns the arm red
10 💡 Unused column includes in the system table source AGREE, fixed @ bee5aa4 removed
11 ⚠️ The table read every database, including MySQL/PostgreSQL ones that cannot hold a FileLog table: an unreachable MySQL server made every SELECT from it fail, and PostgreSQL cost one remote fetch per table AGREE, fixed @ 3b22be8 databases of external engines are skipped, as in system.mutations and system.replicas; new test with an unreachable MySQL database
12 ⚠️ No test reloaded a table with a nonzero stored offset, so an offset not restored at load (the whole file shown as unread after a restart) went unnoticed AGREE, fixed @ 5cfa577 05316 detaches and attaches the table after reading: the stored offsets are shown, the counters start over; dropping the offset copy at load turns it red
13 💡 With the destination of the only view dropped, no round runs, so the file stays consuming AGREE, noted, not blocking no round fails, so nothing is stuck; the stall shows as a growing file_size - current_offset and an old last_poll_time

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

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

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Feature, not a bug: on master system.filelog_files does not exist (UNKNOWN_TABLE, all three new tests fail). Each hook has a deletion mutation that turns the named test red.
b Root cause explained? The engine exposes no per-file state. It cannot be read from file_infos: a background round holds file_infos_mutex for its whole duration, and direct SELECT readers change file_infos without it. So a separately locked per-inode snapshot is written where that state already changes.
c Fix matches root cause? One snapshot plus 1-3 line hooks (file set, stored offsets, start of a read, record counter, round outcome). Reading itself is unchanged.
d Test intent preserved / new tests added? 05316: direct SELECT, offsets, live size and lag, counters, poll time, added/removed/renamed/recreated files (a processed rename keeps the file's offset and counters under its new name), a reload (stored offsets kept, counters start over), SHOW TABLES filter, temporary tables not shown, a loaded lazy_load_tables table. 05317: a materialized view failure gives stuck with the exception, and the next good read gives consuming; a round that fails before it reads (a destination that rejects inserts) gives stuck with the unread bytes. 05318: an unreachable MySQL database does not make the table fail.
e Both directions demonstrated? Master fails all three tests. The fixed build passes them, and 50/50 randomized runs each. Each of 17 mutations (every hook, the stored offset copied at load, the file_size inode check, the lazy_load_tables unwrap, the temporary and external database skips, resetting or not renaming a renamed file's row, marking only the round's files after a failed round) fails a test.
f Fix is general across code paths? Both read paths share openFilesAndSetPos, readNewRecords, storeMetas and closeFilesAndStoreMeta. Every file-set change (startup scan, add, re-add with a reused inode, rename, remove) goes through the same sync. A loaded lazy_load_tables stand-in is unwrapped; one not loaded is skipped without loading it. Temporary tables are skipped like in system.tables, since all sessions share the database that holds them. Databases of external engines (MySQL, PostgreSQL), which cannot hold a FileLog table, are not read, as in system.mutations and system.replicas. A failed round marks the files it read and also every file with unread bytes, since a round that fails before it reads (while building the insert) has not added them yet.
g Fix generalizes across inputs (params/datatypes/wrappers)? No data types are involved. Directory and single-file tables both work, an empty directory has no rows, and a renamed file keeps its row (keyed by inode). A removed file not yet processed has file_size NULL.
h Backward compatible? (maintainer-approved exception only) Yes: a new read-only system table, with no setting and no metadata or on-disk format change.
i Invariants and contracts preserved? Rows are inserted only for tracked inodes, and the sync runs only under file_infos_mutex with no read in progress. Lock order is always file_infos_mutex then the new mutex, which is held only for map updates and copies, plus one stat per tracked file outside the round after a failed round. The system table never waits for a read round: measured at 63-210 ms during a 9.8 s round. The round's exception is recorded with the memory tracker's throw blocked, so nothing can escape the background task's catch handler.

Session id: cron:clickhouse-impl-slot-41:20261002-125900

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1d91fc7]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05339_parquet_prewhere_subcolumn_read_through_column FAIL cidb
05339_parquet_prewhere_subcolumn_read_through_column FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05210_lightweight_update_materialized_cte_in_ignore FAIL cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb

AI Review

Summary

This PR adds system.filelog_files to expose per-file FileLog progress, lag, and failure state. Most of the observability plumbing and test coverage look solid, but I do not think it is ready to merge yet: the DW_ITEM_MOVED_TO path still conflates inode reuse with a true rename, so an atomic rename of a large staged file can inherit stale offsets and counters from a deleted watched file and silently skip the beginning of the new file.

Findings

❌ Blockers

  • [src/Storages/FileLog/StorageFileLog.cpp:1419] DW_ITEM_MOVED_TO still treats any existing meta_by_inode entry as proof that the arriving file is the old watched file under a new name. If a watched file is deleted, its inode is recycled for a staged file, and that staged file is then renamed into the watched directory, this branch reuses the old last_writen_position and num_records_read instead of resetting them. When the new file is larger than the stale offset, openFilesAndSetPos seeks to that stale offset and silently drops the beginning of the file.
    Suggested fix: preserve metadata and statistics only for a positively paired rename (for example, a matching watcher cookie from a tracked source name). Otherwise handle this DW_ITEM_MOVED_TO case like DW_ITEM_ADDED: drop the stale meta/statistics entry for that inode and restart from offset 0.
Final Verdict

❌ Changes requested. The reused-inode DW_ITEM_MOVED_TO case can still skip data, so this needs one more fix before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 2, 2026
it->second = FileMeta{.file_name = file_name};
else
file_infos.meta_by_inode.emplace(inode, FileMeta{.file_name = file_name});
eraseFileStatistics(inode);

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.

This only resets the per-inode snapshot for DW_ITEM_ADDED. DW_ITEM_MOVED_TO is also a "new file" path when producers write in a staging directory and then rename into the watched directory. If the deleted watched file's inode has already been recycled for that staging file, the meta_by_inode hit in the DW_ITEM_MOVED_TO branch treats it as a rename, keeps the old last_writen_position and num_records_read, and can seek past the beginning of the new file.

Please reset or positively pair true renames there as well (for example by plumbing a rename cookie through the watcher), and add a focused test for the atomic-rename case.

@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
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1d91fc7c2 with master 8575850ba (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

7 object files changed (+234.35 KiB total), 1 added.

Object file Master PR Δ
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemFileLogFiles.cpp.o new 195.46 KiB +195.46 KiB
src/CMakeFiles/dbms.dir/Storages/FileLog/StorageFileLog.cpp.o 743.61 KiB 770.82 KiB +27.21 KiB (+3.66%)

719 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

13 translation units recompiled, 63 s compile time in total, 12 of them have a recent master baseline.

Job report

alexey-milovidov and others added 4 commits October 10, 2026 18:20
The new storage_casts style rule requires castStorage for engines that
can be deferred. DeferredTable::Skip keeps the previous behaviour: a
lazily loaded FileLog table is shown once loaded, and the listing never
loads one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since a file that cannot be opened is skipped and retried instead of
failing the round, such a file showed `consuming` with no exception.
Record the open error and show the file as `stuck` until it opens.

A single-file table (or a symlink) whose file was recreated with a new
inode kept the old inode's row with a NULL size and frozen counters, as
`updateFileInfos` never resyncs the statistics of a single-file table.
Move the row to the new inode when the file is reopened.

A file truncated in place is read again from its start, so show 0 as
its offset until then instead of an offset past its end.

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

A file that could not be opened is retried by every round, so it belongs
to the files of the round: a successful round now clears its `stuck`
state like that of any other file it read. And a round that fails
before reading now also marks a file truncated in place, which is read
again from its start.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1d91fc7

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (it changes FileLog only; 130 of 130 reruns pass): UNKNOWN_TABLE for the initiator-local _materialized_cte_c_* table when a reused MATERIALIZED CTE is read through parallel replicas with a local plan. 90 PRs and 16 master commits show it since 2026-10-08 #123121 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR: the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 60 PRs and 20 master commits show it since 2026-10-10 21:55Z #125121 (external, merged 00:36Z), the revert of my #124685 that added this test. The tested merge commit predates it, so the next master merge picks it up
Mergeable Check, PR praktika rollups of the rows above #123121 (mine, open), #125121 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261011-043008

This branch has not been deployed

No deployments
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-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants