Skip to content

Do not fail FileLog reads on a last line that is still being written - #123404

Merged
antaljanosbenjamin merged 4 commits into
ClickHouse:masterfrom
groeneai:filelog-partial-last-line
Nov 2, 2026
Merged

antaljanosbenjamin merged 4 commits into
ClickHouse:masterfrom
groeneai:filelog-partial-last-line

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

FileLog no longer fails with CANNOT_READ_ALL_DATA (Stream is in bad state) when a file ends with a line that has no newline yet: the complete lines are read, and the last line is read from its start once it is completed. Related to #123368.

Description

On 26.8 (and 26.3), reading a FileLog table fails with CANNOT_READ_ALL_DATA (Stream is in bad state) whenever a file ends with a line that has no newline yet, such as a log line that is still being written, so none of that file's rows can be read until the line is completed (item 1 of #123368; measured on the official 26.8.10.6 and 26.3.33.24 images).

FileLogConsumer::readNewRecords splits files into records with std::getline. On a last line without \n it stops at EOF and sets eofbit, and the next stream check threw before the offset was stored. This happens before any parser runs, so handle_error_mode = 'stream' cannot catch it.

Now an unterminated last line is not emitted: the reader goes back to the start of that line, the offset is stored there, and the file is done for this read. The line is read whole once it is completed (directory tables through the watcher's modify event, single-file tables on the next poll). The "reached the end" check becomes >=, so a line completed while it is being read no longer makes the read spin for about three poll_timeout_ms (15.5 s vs 0.5 s with poll_timeout_ms = 5000).

Behavior note: a file whose last line never gets a newline keeps that line unread, instead of failing every read of the file.

The table staying stuck after such an error (Another select query is running on this table) is the other half of item 1 and goes in a separate PR.

Validation: the new test fails on master with this error and passes with the fix (50/50 randomized, also with -j 10); the issue's materialized-view repro now ingests /a1 /a2 /a3 2 s after the line is completed; all existing FileLog tests pass.


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

Version info

  • Merged into: 26.11.1.1108-master (included in 26.11 and later)

groeneai and others added 2 commits October 2, 2026 01:47
`FileLogConsumer::readNewRecords` splits every file into records with
`std::getline`. When the bytes before the end of a file have no trailing
'\n' (a writer in the middle of a line, a buffered writer that flushed
mid-line, a file without a final newline), `getline` stops at EOF and
sets `eofbit`, and the next `assertStreamGood` threw `CANNOT_READ_ALL_DATA`
("Stream is in bad state") before the offset was stored. Every read of
the file then failed the same way, outside the parser, so
`handle_error_mode = 'stream'` could not catch it.

Now an unterminated last line is not emitted: the reader is reset to the
start of that line, the offset is stored there, and the file is marked
done for this read (otherwise `pollBatch` re-reads the same tail until
`poll_timeout_ms`). The line is read from its start once it is completed:
directory tables get a MODIFIED event from the watcher, single-file
tables re-read the file on every poll. `clear()` is needed when `getline`
extracted nothing (the file shrank after it was opened); `seekg` alone
only resets `eofbit`.

The "stream reach to end" check becomes `>=`: a line completed while it
was being read ends past the size recorded at open, so the file was
never marked done and every read of it spun for about three
`poll_timeout_ms` (measured 15.5 s vs 0.5 s with `poll_timeout_ms = 5000`
and a 256 MiB line).

A file whose last line never gets a newline now keeps that line unread
instead of failing every read of the file.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The directory watch of a FileLog table is installed on the watcher thread
after `CREATE` returns. An append made before that is never reported, so
both files would stay unchanged and the bounded loop would end without
their completed lines. Create a new file per iteration until a `SELECT`
reads one: its `ADDED` event proves the watch is armed before the
completions are written. Those sentinel rows are filtered out of the
completion loop.

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; 2 findings in the first pass, 0 in the delta recheck after the fix round) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ Test directory arm can append before the asynchronous directory watch is armed (05317_file_log_partial_last_line.sh) AGREE, fixed @ d55c11a the test waits for the watch with a new-file handshake; with a forced 2 s arming delay the old test failed 3/3, the new one passes 3/3
2 ⚠️ No committed test reddens if >= is reverted to == (FileLogConsumer.cpp) DISAGREE only wall time differs (same rows; 15.5 s vs 0.4-0.6 s with poll_timeout_ms = 5000), and the newline must land during the getline of the tail, so a test would be a timing race
3 💡 reader.clear() is not exercised by the test noted it matters only when getline extracted 0 bytes (file shrank under the reader), shown manually
4 💡 A held unterminated last line is skipped without a log line noted the behavior is stated in the engine docs; no wrong result

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

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

@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. printf '{"a":1}\n{"a":2' > f.jsonl plus a direct SELECT from a FileLog(..., 'JSONEachRow') table on it fails every time with Stream is in bad state (CANNOT_READ_ALL_DATA) on master and on the official 26.8.10.6 and 26.3.33.24 images.
b Root cause explained? FileLogConsumer::readNewRecords reads records with std::getline; a last line without \n stops at EOF with eofbit set and the next assertStreamGood throws before the offset is stored, outside the parser. A line completed during the read ended past the size recorded at open, so the read spun until poll_timeout_ms.
c Fix matches root cause? Yes. In the engine's only line reader, an unterminated last line is not emitted, the reader goes back to its start, the offset is stored there and the file is done for this read. An incomplete line is not malformed, so it is not routed to handle_error_mode.
d Test intent preserved / new tests added? New test 05317_file_log_partial_last_line: a single-file table (checks the re-read line's _offset) and a directory table with two incomplete files in one stream, which waits until the directory watch is armed and then, bounded, for the completed lines.
e Both directions demonstrated? Yes. Master: FAIL with CANNOT_READ_ALL_DATA. Fix: OK, 50/50 randomized, also with -j 10. Removing only the seekg gives Cannot parse input; removing only the "done" mark makes a held-line read take 10004 ms instead of 2 ms. With the watch armed 2 s late, the test without the handshake failed 3/3 and passes 3/3 with it.
f Fix is general across code paths? readNewRecords is the only getline in src/Storages/FileLog, shared by direct SELECT and the materialized-view path (the issue's MV repro now ingests all lines). Kafka, RabbitMQ and NATS are message based.
g Fix generalizes across inputs (params/datatypes/wrappers)? Splitting happens before any format runs, so it is format independent (JSONEachRow in the test, LineAsString manually). A file ending in \n is unchanged; a 0-byte tail after a shrink is held without a throw.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or metadata change; stored offsets keep their meaning. Behavior change requested by the issue: a last line that never gets a newline stays unread.
i Invariants and contracts preserved? The stored offset is always a line start and never decreases; a file's status and offset are written only by the stream that owns it; a held line is never emitted.

Session id: cron:clickhouse-impl-slot-6:20261002-024237

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [317b348]

Summary: ✅


AI Review

Summary

This PR changes FileLog to treat an unterminated trailing line as incomplete input instead of throwing CANNOT_READ_ALL_DATA, rewinds the offset to the start of that line so it can be re-read once completed, preserves the truncate-during-read error path, and adds focused stateless coverage for the single-file, directory-watcher, and truncate cases. After reviewing the current code, the PR diff, the linked issue, and the existing review threads, I did not find a remaining correctness, compatibility, or safety issue in the current version.

Final Verdict
  • Status: ✅ Approve

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

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 317b34862 with master b13e8f865 (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.

Compile time of recompiled translation units

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

Job report

`reader.eof()` after `getline` also happens when the file is truncated in
place after `openFilesAndSetPos` recorded `last_open_end`. Deferring the tail
in that case saved the truncated offset and returned no error; once the same
inode grew past that offset again, the next read started there and silently
skipped the first rows of the rewritten file (measured: 100-row file
truncated during a throttled direct SELECT, 29 rows returned without error,
then rows 1001..1023 of the regrown file never read).

Only a read that reached at least `last_open_end` is an incomplete last line.
If EOF came earlier, the bytes seen at open are gone, so the read fails with
`CANNOT_READ_ALL_DATA` as it does on master. The new test arm truncates the
file after the first row of a throttled read and expects that error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
reader.clear();
reader.seekg(offset);
StorageFileLog::assertStreamGood(reader);
file_ctx.status = StorageFileLog::FileStatus::NO_CHANGE;

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.

Is it a right status for the case when we have already read some records from the file but this happened on the last record?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. Here NO_CHANGE means "nothing left to read until the file changes", not "nothing was read": master sets it the same way after a read that consumed records and reached last_open_end (L145-148). The status is only used to skip the file in the next readNewRecords calls of the same pollBatch and in openFilesAndSetPos.

The records read before the partial line stay in new_records, and last_writen_position becomes tellg() (L140-143), which is the start of the partial line, so those records are committed and the line is re-read from its start. The file goes back to UPDATED on its next DW_ITEM_MODIFIED (or on every read for a single-file table). Keeping UPDATED would only make pollBatch re-read the same incomplete line on its next iterations.

05317 covers this case: {"a":1}\n{"a":2 returns 1, then 2 at _offset 8 once the line is completed.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Dear @antaljanosbenjamin, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit 63c5634 Nov 2, 2026
163 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 Nov 2, 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.

4 participants