Skip to content

Streaming queries with cursors for FileLog tables - #131819

Open
alexey-milovidov wants to merge 17 commits into
masterfrom
stream-file-log-tables
Open

alexey-milovidov wants to merge 17 commits into
masterfrom
stream-file-log-tables

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Support streaming queries for FileLog tables. A streaming read reads the files with its own readers and never moves the read positions stored in the metadata of the table, so it does not need stream_like_engine_allow_direct_select. The cursor is {file name: offset of the last read record}; a file without an entry is read from the beginning, and an offset outside a file or not at the start of a record is rejected. The cursor splits its keys by dots, so a dot in a file name is written as %2E (and % as %25), e.g. {'app%2Elog': 1024}. Only complete records (ending with a newline) are read. Files are identified by inode, and a file is read through a descriptor whose inode is verified after opening: a file renamed by log rotation keeps its position, also when its new name does not match the globs of the path (app.log renamed to app.log.1 for *.log), a file with several names (hard links) is read once, and a file that leaves the directory is closed after its remaining records are read.

An unbounded stream checks the files every poll_timeout_ms (also while there is a backlog; the files are read round robin) and reads a file replaced by another one with the same name (e.g. by log rotation) or truncated in place from the beginning. An idle stream returns an empty chunk after each poll, so that it does not hold a thread of the pipeline. STREAM BOUNDED reads the records that are complete within the sizes of the files at the start of the query. WATERMARK is not supported.

Test: 05771_streaming_queries_file_log_cursors (bounded with and without a cursor, the stream does not consume, invalid offset, unbounded with a new file and an incomplete record, incremental refresh rejected).

The branch includes the commits of #131814 and #132145 (the infrastructure for an incremental refresh from tables other than MergeTree).

Incremental refresh: the bounded read reports {file: {'offset': ..., 'inode': ..., 'end': ..., 'fingerprint': ...}} through the holder, so a FileLog table can be the source of an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL); a file renamed since the cursor was taken keeps its position, and a file replaced by another one with the same name or truncated is read from the beginning by the next refresh. The read replaces the cursor of the previous refresh (StreamingCursor::replace), so the cursor keeps neither the previous names of a renamed file nor the position in a file truncated to empty. The cursor has positions in the files of one server, so a refresh coordinated between the replicas of a Replicated database is rejected (IStorage::hasServerLocalStreamingCursor); all_replicas = 1 is allowed. A file without a read position (no complete record yet, or truncated) is in the cursor with its inode only, so it is still a file of the table after it is renamed. A file truncated and written again past the read position is detected by its contents (fingerprint: the first bytes of the file and the last record read; the unbounded stream checks them at every poll) and is read from the beginning; a file rewritten with the same first bytes and the same record at the same position cannot be told from a file that was appended to. A query that stops the read early (DISTINCT by constants, LIMIT BY without keys) still advances the cursor: the remaining records are skipped without parsing; LIMIT, OFFSET and the overflow mode break are rejected (#132145). Tested by 05771_streaming_queries_file_log_cursors (new data, a truncated file, an idle round), 05836_streaming_queries_file_log_rotated_files (a rotated file that does not match the glob, two renames across three refreshes, a file truncated to empty) 05837_streaming_queries_file_log_replicated_database and 05844_streaming_queries_file_log_refresh_positions (an incomplete record completed after rotation, truncation plus regrowth, an early stop).

This is a part of #131769, split by storage as requested in the review. Compared to it, the cursor format is handled by the table itself, no new virtual columns represent the cursor, and the read reports its final cursor through Context::getStreamingCursor only for an incremental refresh, which is what it exists for.

Related: #42990
Related: #131769
Related: #131814
Related: #132145

Changelog category (leave one):

  • Experimental Feature

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

Streaming queries (SELECT ... FROM t STREAM) with cursors are supported for FileLog tables. They do not move the read positions of the table.

🤖 Generated with Claude Code


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

A streaming read of a `FileLog` table reads the files with its own readers and
never moves the read positions stored in the metadata of the table, so it does
not need `stream_like_engine_allow_direct_select`. The cursor is
`{file name: offset of the last read record}`; a file without an entry is read
from the beginning, and an offset that is outside a file or not at the start of a
record is rejected. A file name may contain dots: the table takes the whole path
of an offset in the cursor as the file name. Only complete records (ending with a
newline) are read.

An unbounded stream checks the files every `poll_timeout_ms`, and reads a file
replaced by another one with the same name or truncated from the beginning; an
idle stream returns an empty chunk after each poll, so that it does not hold a
thread of the pipeline. `STREAM BOUNDED` reads the files up to their sizes at the
start of the query. `WATERMARK` is not supported.

Related: #42990
Related: #131769

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

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [51ef384]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

Adds independent FileLog streaming reads, resumable cursors, and incremental refresh support, including rotation and truncation handling. At head 51ef384fe58ad7d8b4ae1f09a2db78805b686c3d, two cursor correctness gaps remain after the previous fixes, and the new early-stop drain can delay cancellation for an entire file. Block pending the cursor fixes.

Findings

❌ Blockers

  • FileLogStreamSource.cpp:478: Unbounded truncation detection does not validate the consumed newline. Let P be 255 x bytes and a newline. After consuming P + "a\n", the position is 258 and the last record starts at 256. Rewrite the same inode as P + "ab\nc\n" between polls: its size, saved 256-byte head, and one-byte record hash all pass. Reading resumes at byte 258, inside the new ab record, losing that record or causing a parse exception. The old newline at byte 257 changed, so this is distinguishable from an append. Include the delimiter in the evidence or validate the resume boundary on polling. Replied to the author's fixed claim and reopened the existing thread.

  • MergeTreeCommitOrderSource.cpp:132: Successful early termination can omit a parallel source's cursor. One source can satisfy DISTINCT by a constant while another is still building its first round. Closing the merged input reaches the latter's shutdown with no current_round, so it reports nothing, including when it has a pending_round. The reporting source contains only its assigned partitions, and its first report clears the seeded root in StreamingCursor::mergeAt. The omitted partitions can therefore be read again on an idle refresh, appending another constant without new source data. Finalize the bounded snapshot for every participating source, including pending/unstarted rounds, before persisting the shared cursor. This follows from the source-state and scheduling paths; it was not reproduced with a binary. Replied to the author's fixed claim and reopened the existing thread.

⚠️ Majors

  • FileLogStreamSource.cpp:613: The early-stop drain ignores cancellation until the entire file has been scanned. With skip_remaining_records, the loop bypasses the block-size limit and has no inner cancellation check. Cancelling a refresh over a large log continues reading and hashing the remaining file, retaining the executor and delaying shutdown. Check cancellation in batches inside the loop and leave without publishing a successful cursor. Posted as a new inline finding.
Tests
  • ⚠️ Cover an unbounded rewrite that preserves the first 256 bytes and the old last-record bytes but replaces its terminating newline.
  • ⚠️ Cover early termination with partitions assigned to different MergeTree sources, including one whose round is still pending, followed by an idle refresh. The added early-stop tests use max_threads = 1.
  • ⚠️ Verify cancellation during the skipped-record drain of a large file.
  • ⚠️ Head CI does not provide stateless execution results for the latest fixes: those jobs are skipped, and the Praktika report reports a duplicate-include tidy failure. Run the focused regressions after CI is restored. No server binary is available in this review job; no local tests were run. The tidy failure is left to its dedicated CI check.
Final Verdict

Status: ❌ Block

Fix resume-boundary validation and finalize every parallel source's bounded cursor on successful early termination. Add the focused regressions and make the new drain cancellable.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit efebf51151bdc59198e73bbd28aead307a175e3d was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 16, 2026 16:41
alexey-milovidov and others added 3 commits November 16, 2026 20:32
…l refresh

Instead of accepting only `MergeTree` sources, an incremental refresh accepts a
source whose bounded streaming read reports the cursor it advanced to
(`IStorage::reportsStreamingCursor`, true for `MergeTree` and
`ReplicatedMergeTree`); other engines enable it together with the reporting.

`StreamingCursor` gets `merge` and child holders, which place the cursor of a
part of a composite read (a table of `Merge`, a shard of `Distributed`) under its
key path. The trees are merged in the persisted form (a key with a dot is split
into a path), and the holder starts from the cursor of the previous refresh, so a
part that is not read this time keeps its position.

Related: #42990
Related: #131814 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bounded streaming read of a `FileLog` table reports the offsets it read up to
through the holder of an incremental refresh, with the inode of every file
(`{file: {offset, inode}}`), so a `FileLog` table can be the source of an
incremental refresh. A file replaced by another one with the same name or
truncated since the cursor was taken is read from the beginning.

Related: #131814 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 19, 2026 15:56
- The cursor splits its keys by dots, so a file name is now a single key with
  `.` written as `%2E` and `%` as `%25`. Files with a common dotted prefix
  (`app.log`, `app.log.1`) and files ending with `.offset` or `.inode` are no
  longer ambiguous; an unescaped dotted name is rejected with a hint.
- Disable CSV/TSV/custom header detection for the per-record parser, as for
  the other reads of `FileLog`: a record equal to a column name was dropped.
- `STREAM BOUNDED` reads only records whose newline is within the size of the
  file at the start of the query.
- Files are identified by inode: a renamed file keeps its position (log
  rotation), a file with several names (hard links) is read once, and the
  cursor of an incremental refresh is matched by inode for a renamed file.
- A file that leaves the directory is closed after its remaining records are
  read, instead of holding the descriptor forever.
- The directory is checked every `poll_timeout_ms` even with a backlog, and
  every chunk starts after the file that filled the previous one.
- The refresh cursor keeps the position after the last read record (`end`),
  so a single-record file truncated in place to a shorter record is detected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bounded streaming read reports its cursor once it reaches the end of the stream.
A `LIMIT` stops the read earlier and may drop rows of an already read chunk, so the
next refresh would resume from a cursor that does not match the appended rows and
append the same rows again. Reject `LIMIT`/`OFFSET` (and the `limit`/`offset`
settings) in the query of an `APPEND INCREMENTAL` view, both at definition and before
each refresh, for every source engine including `MergeTree`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
Comment thread src/Storages/FileLog/StorageFileLog.h Resolved
alexey-milovidov and others added 5 commits November 19, 2026 17:40
The holder of the streaming cursor starts from the cursor of the previous refresh, so
that a part of a composite source that is not read keeps its position. But merging into
it made the cursor append-only: the partitions that `ReadState::updatePartitionSet`
removes (dropped by TTL or `DROP PARTITION`) survived every refresh, and the persisted
cursor grew with every partition ever observed.

Now the first cursor reported under a path (the root for a plain table, the key path of
a child holder) replaces the subtree of the previous refresh at that path, and further
reports under the same path (the parallel streams of one read) are merged into it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The state of a file is bound to an opened descriptor whose inode is checked
  with `fstat`, and the file is read through it. A name given to another file
  between the listing of the directory and the opening (log rotation) cannot
  make a state read another file: the directory is listed again.
- The cursor of an incremental refresh replaces the previous one
  (`StreamingCursor::replace`) instead of being merged into it. It does not
  keep the previous names of a renamed file, whose obsolete position was taken
  by inode after the next rename, nor the position in a file truncated to
  empty, which became valid again after new records were written.
- A file is taken for reading by a name that matches the path of the table,
  and is still read after it is renamed to a name that does not match
  (`app.log` -> `app.log.1` for `*.log`), as for the other reads of `FileLog`.
- An incremental refresh from a `FileLog` table cannot be coordinated between
  the replicas of a `Replicated` database, because the cursor has positions in
  the files of one server (`IStorage::hasServerLocalStreamingCursor`).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
if (bounded)
{
/// A pass without new records: everything up to the sizes at the start is read.
reportFinalCursor();

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.

[Blocker] Handle successful refreshes that stop before source exhaustion

Publishing the cursor only on an empty pass assumes that the consumer drains the source. An accepted APPEND INCREMENTAL ... AS SELECT k FROM file_log LIMIT 1 can finish successfully before reaching this call. With source records 1 through 100 and the table's max_block_size = 1, three refreshes on the exact PR-head binary produce [1], [1,1], and [1,1,1]: the holder retains its previous cursor and every refresh replays the first record.

Reject definitions that can terminate the read early until their cursor semantics are supported, or implement progress reporting that is safe for a successful partial read. The equivalent MergeTree view also reproduces this, so the shared incremental-definition validation needs coverage too.

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.

🕵 Fixed in 51ef384, in both ways. The branch now has the validation from #132145 (merged in 727bb31), which rejects LIMIT, OFFSET, the settings limit/offset and the overflow mode break in the query of an incremental refresh, with MergeTree coverage in 05770_incremental_refreshable_mv_limit and 05843_incremental_refreshable_mv_early_stop. For the queries that may still stop the read early (DISTINCT by constants, LIMIT BY without keys), FileLogStreamSource::prepare keeps the bounded read going after its output is closed: it skips the remaining records without parsing and reports the cursor, as MergeTreeCommitOrderSource::handleShutdown does. Covered by 05844_streaming_queries_file_log_refresh_positions (the LIMIT 1 definition is rejected; a DISTINCT by a constant over 100 records with max_block_size = 1 appends one row per round of new data).

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.

[Blocker] The parallel MergeTree case still has an unreported-cursor path in src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSource.cpp:132: shutdown reports only when current_round exists, ignoring both pending_round and a subscription whose first round has not started.

With partitions assigned to two sources, one source can emit the row that completes DISTINCT by a constant while the other is still building its first round. The final DistinctTransform closes the merged input, ResizeProcessor closes both sources, and the second source reaches handleShutdown with no current_round, so it publishes nothing. The first source's StreamingCursor::merge also clears the seeded root on its first report (src/Interpreters/Context.cpp:5343); its ReadState contains only its assigned partitions. Consequently the other source's partitions have no saved positions, and an unchanged source can append the same constant again on the next refresh. Even retaining their old positions would leave already-consumed snapshot rows for the next refresh.

Finalize the bounded snapshot for every source participating in a successful early stop, including pending/unstarted rounds, before committing the shared cursor. The new early-stop tests all use max_threads = 1; please cover partitions assigned to different sources and an idle refresh with multiple streams. This is a source-state/scheduling trace, not a binary reproduction.

Comment on lines +335 to +336
&& (entry->end ? *entry->end > static_cast<UInt64>(entry->offset) && *entry->end <= size
&& isRecordStart(fd, file_name, *entry->end)

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.

[Blocker] Detect truncation followed by regrowth past the saved position

A valid newline at end does not establish that the consumed contents are still present. Refresh a file containing 1\n, then truncate that same inode and write 2\n3\n before the next refresh. Its size is now greater than the saved end = 2, and byte 1 is still a newline, so this check accepts the old cursor and starts at 3. On the exact PR-head binary the target remains [1,3] through subsequent refreshes, silently losing 2. The unbounded stream also skips 2 when these writes happen between polls.

Persist and validate enough evidence of the consumed contents/file generation before reusing the position, resetting it when the contents have changed. Add a regression for truncation plus regrowth without an intervening refresh or poll that observes the smaller file.

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.

🕵 Fixed in 51ef384. The read keeps evidence of the contents it has consumed: the first bytes of the file (up to 256, up to the read position) and the hash of the last record read. The cursor of an incremental refresh has it as fingerprint, validated before the position is reused (and again when the cursor is reported, for a file rewritten during the refresh); the unbounded stream checks it at every poll. A mismatch resets the file to the beginning. 05844_streaming_queries_file_log_refresh_positions covers truncation plus regrowth without an intervening refresh or poll, for both the refresh (including new contents that start with the old first record) and the unbounded stream.

One limit is inherent and documented in FileLogStreamSource.h: a file rewritten with the same first bytes and the same record at the same position cannot be told from a file that was appended to. Hashing the whole consumed prefix would narrow it further at the cost of reading the whole file on every refresh, and still could not tell a rewrite with an identical prefix from an append.

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.

[Blocker] The unbounded case still misses a changed record boundary in src/Storages/FileLog/FileLogStreamSource.cpp:478: record_size excludes the terminating newline, and tryUpdateFiles does not check that state.position is still a record boundary.

For a concrete byte trace, let P be 255 x bytes followed by a newline. Read P + "a\n" completely, so head = P, last_offset = 256, and position = 258. Between polls, truncate the same inode and write P + "ab\nc\n". The size check passes, the first 256 bytes still match, and the one byte hashed at offset 256 is still a, so consumedContentsChanged returns false. The next read starts at byte 258, the newline inside the new ab record, and never reads ab from its start. This is distinguishable from an append: the old terminating newline at byte 257 has changed to b.

Include the delimiter in the consumed-record evidence, or validate the resume boundary during unbounded polling as the structured-cursor resume already does. Please cover this rewrite after the first 256 bytes in the unbounded regression.

alexey-milovidov and others added 4 commits November 22, 2026 07:41
…e overflow mode `break`

A query of an incremental refresh can stop the bounded read before its end:

- A `DISTINCT` by constants or a `LIMIT BY` without keys closes the source once it has its result.
  `MergeTreeCommitOrderSource::prepare` went to `handleShutdown` and never reached `surfaceFinalCursor`,
  so the refresh kept the previous cursor and appended the same rows again on the next refresh.
  Now `handleShutdown` of a bounded read finishes the running round and reports the cursor after all its rows:
  the rest of the rows cannot change the result of the query, so they are consumed without being read.

- With the overflow mode `break` (e.g. `max_rows_to_read` with `read_overflow_mode = 'break'`) the query finishes
  successfully with a partial result, while the cursor is advanced past the rows that were not read, losing them.
  `validateIncrementalDefinition` now rejects the value `break` of every `*_overflow_mode` setting, taking
  the `SETTINGS` clause of the query into account (it is not applied to the context when the view is created,
  which also applies to the existing check of `limit` and `offset`).

#132145 (comment)
#132145 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Merge `stream-incremental-refresh-reports-cursor` (#132145),
whose commits this branch includes: it rejects `LIMIT`, `OFFSET` and the overflow mode `break`
in the query of an incremental refresh, and a read replaces its part of the cursor of the previous refresh.

The conflict in `StreamingCursor` is resolved by keeping both `mergeAt` and `replaceAt`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ation and an early stop

- A file without a read position (no complete record was read yet, or the file was truncated)
  was not in the cursor of an incremental refresh, so the next refresh did not know the file
  after it was renamed to a name that does not match the path of the table, and its records
  were lost. Such a file is now in the cursor with its inode only.

- A file truncated and written again past the read position was taken for a file that was
  appended to, and the records before the position were lost. The read now keeps the evidence
  of the contents it has read (the first bytes of the file and the last record read), the
  cursor of an incremental refresh has its `fingerprint`, and the unbounded stream checks it
  at every poll. A file whose contents do not match is read from the beginning.

- A query that stops the read early (a `DISTINCT` by constants, a `LIMIT BY` without keys)
  finished the refresh without the cursor, so every refresh appended the same rows again.
  The bounded read of an incremental refresh now skips the remaining records without parsing
  and reports the cursor, as `MergeTreeCommitOrderSource` does. `LIMIT`, `OFFSET` and the
  overflow mode `break` are rejected by the validation merged from
  #132145.

Test: `05844_streaming_queries_file_log_refresh_positions`.

#131819 (comment)
#131819 (comment)
#131819 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>

bool reached_end = false;
bool has_last_record = false;
while (skip_remaining_records || total_rows < max_block_size)

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.

[Major] Keep the early-stop drain cancellable

Once skip_remaining_records is set, this loop scans the entire remaining file in one call, regardless of max_block_size. Its only isCancelled check is outside the loop, before entering the file. For an incremental refresh using DISTINCT by a constant over a large log, cancelling the query or stopping the refresh during this drain therefore continues reading and hashing the whole file before releasing the executor. A small block size no longer bounds that delay, and shutdown can wait for the full scan.

Check cancellation inside the record loop, preferably in batches, and stop the drain immediately without reporting a successful cursor when cancelled.

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

comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant