Repository navigation
Streaming queries with cursors for Kafka tables - #131818
alexey-milovidov wants to merge 13 commits into
Conversation
A streaming read of a `Kafka` table (both `Kafka` and the Keeper-based `Kafka2`)
assigns all partitions of the topics to its own consumer, starting after the
offsets in the cursor `{topic: {partition: offset of the last read message}}`;
a partition without an entry is read from the beginning. It does not join the
consumer group, does not use the offsets stored for the group and never stores
offsets, so it does not take the messages away from the materialized views of
the table and does not need `stream_like_engine_allow_direct_select`. A topic
name may contain dots: the table takes the partition as the last part of the
path of an offset in the cursor.
`STREAM BOUNDED` finishes at the high watermarks as of the start of the read.
An idle stream returns an empty chunk after each poll, so that it does not hold
a thread of the pipeline. `WATERMARK` is not supported.
Related: #42990
Related: #131769
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [b0ec058] AI ReviewSummaryAdds independent, cursor-based Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Fix the terminal-input transition and use the data type's default for malformed-message recovery, with focused regression coverage. |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Storages/Kafka/KafkaStreamSource.cpp.o |
new | 345.95 KiB | +345.95 KiB |
src/CMakeFiles/dbms.dir/Storages/Kafka/StorageKafka2.cpp.o |
990.25 KiB | 1007.02 KiB | +16.77 KiB (+1.69%) |
src/CMakeFiles/dbms.dir/Storages/Kafka/StorageKafka.cpp.o |
594.73 KiB | 611.08 KiB | +16.35 KiB (+2.75%) |
716 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
1523 translation units recompiled, 7872 s compile time in total, 1522 of them have a recent master baseline.
…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 `Kafka` table reports the offsets it read up to through the holder of an incremental refresh, so a `Kafka` table can be the source of an incremental refresh, which resumes every refresh from them without a consumer group. Related: #131814 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The cursor splits its keys by dots, so a topic name is now a single key with `.` written as `%2E` (and `%` as `%25`), as for `FileLog`. Topics like `events` and `events.0` no longer collide in the cursor of an incremental refresh; an unescaped dotted name is rejected with a hint. - `auto.offset.reset` is `error` for the stream consumer: a cursor outside of a partition is an exception instead of a silent reread from the beginning. A bounded read checks it against the watermarks before reading. - An offset of `9223372036854775807` in the cursor is rejected instead of overflowing when computing the next offset. - A bounded read skips a message at or after the high watermark captured at the start before parsing it (the offsets before it can be transaction markers, so the end of partition event may come later). - Every configured topic must be present in the metadata, without an error: a topic that does not exist or cannot be described is an exception instead of a silently partial (or empty) result. - An unbounded read checks the topics for new partitions every 5 seconds and assigns them, keeping the positions of the other partitions. - An idle source does not occupy a thread of the pipeline: the consumer queue writes to a pipe when it gets an event (`rd_kafka_queue_io_event_enable`), and the source returns `Async` on it, with `poll_timeout_ms` as the timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The refresh resumes from the cursor that the read reports after reaching the end of its snapshot. A `LIMIT` closes the source before that, so the cursor stayed unchanged and every following refresh appended the same rows again (for `Kafka` as well as for `MergeTree`, whose `MergeTreeCommitOrderSource` skips its final report too when the output is closed). Reporting the last read position instead would skip the rows discarded by the limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_stream_cursor` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n incremental refresh `LIMIT BY` stops the read once every group that can appear has reached its limit (e.g. `LIMIT 1 BY tuple()`), so the source does not report its final cursor and the next refresh appends the same rows again. The same holds for the limits with the overflow mode `break` (`read_overflow_mode`, `result_overflow_mode`, `timeout_overflow_mode`). `validateIncrementalDefinition` now rejects them, taking the `SETTINGS` clause of the query into account. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Both `Kafka` engines support subcolumns, so a query can request e.g. an element of a `Tuple`, while the format parses the whole columns. The source matched the parsed block with its header by name, which fails with `THERE_IS_NO_COLUMN` for a subcolumn. It now extracts the requested columns with `getColumnFromBlock`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The source of an incremental refresh (`APPEND INCREMENTAL`) reports the cursor it advanced to only when it reaches the end of its snapshot. A query that does not need the whole source for its result closes the source before that: `SELECT DISTINCT 1 AS k FROM src` (`DistinctTransform` stops reading once it has got all its rows), `GROUP BY` with `group_by_overflow_mode = 'break'`, `distinct_overflow_mode = 'break'`. The refresh succeeded, but the cursor stayed unchanged, so the next refresh appended the same rows again. These cases cannot be listed exhaustively in `validateIncrementalDefinition`, so the invariant is enforced in the pipeline instead: `ReadToEndTransform` is put right after the streaming sources (`MergeTreeCommitOrderSource` and `KafkaStreamSource` of both `Kafka` engines) when the context has the holder of the cursor. When its output is closed, it keeps reading and discarding its input until the source finishes and reports the cursor. The limits that stop the source itself are still rejected, and the leaf ones are rejected as well: `read_overflow_mode_leaf` and `timeout_overflow_mode_leaf` with the mode `break`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| input.setNeeded(); | ||
| if (input.hasData()) | ||
| input.pull(/*set_not_needed=*/ false); | ||
|
|
||
| return Status::NeedData; |
There was a problem hiding this comment.
[Blocker] Recheck the input after discarding its final buffered chunk
An input whose producer has finished can still have a buffered chunk: InputPort::isFinished returns false until that chunk is pulled. If the output is already closed and the input has both IS_FINISHED and HAS_DATA, this branch consumes the last chunk and then returns NeedData even though the input is now finished. ExecutingGraph::updateNode leaves this processor idle and ignores updates to the already-finished producer, so there need not be another notification to run this processor. Execution then fails with the Pipeline stuck exception.
This state is reachable with the bounded MergeTree source: MergeTreeCommitOrderSource::handleRunningPipeline checks whether its internal input finished before checking whether its output can accept more data, so handleBoundedReconfiguration can finish the source while its last output chunk is still buffered. An incremental refresh that closes downstream early can therefore fail after appending rows and replay them on retry.
Recheck input.isFinished after the pull and return Finished when it drained the final chunk. Please cover a closed output with a final buffered chunk from an already-finished producer.
| for (size_t i = 0; i < result_columns.size(); ++i) | ||
| { | ||
| result_columns[i]->rollback(*checkpoints[i]); | ||
| result_columns[i]->insertDefault(); |
There was a problem hiding this comment.
[Blocker] Insert the data type's default when recovering a malformed message
For a JSONEachRow table containing e Enum8('a' = 1, 'b' = 2) with kafka_handle_error_mode = 'stream', a malformed message such as not json reaches this branch. The underlying integer column's insertDefault inserts 0, which is outside this enum; its data type's default is 1. Consequently, SELECT e, _error FROM t STREAM BOUNDED fails with UNKNOWN_ELEMENT_OF_ENUM during text serialization instead of returning the error row, and an incremental refresh can pass the invalid enum value into its destination. Both Kafka engines use this source.
Use non_virtual_header.getByPosition(i).type->insertDefaultInto(*result_columns[i]) after rollback, as the existing KafkaSource and StorageKafka2::pollConsumer paths do. Please cover this through STREAM for both engines; test_kafka_engine_put_errors_to_stream_enum_type_default currently covers only the background-consumption path.
Support streaming queries for
Kafkatables (bothKafkaand the Keeper-basedKafka2). A streaming read assigns all partitions of the topics to its own consumer, starting after the offsets in the cursor{topic: {partition: offset of the last read message}}; a partition without an entry is read from the beginning. It does not join the consumer group, does not use the offsets stored for the group and never stores offsets, so it does not take the messages away from the materialized views of the table and does not needstream_like_engine_allow_direct_select. The cursor tree splits its keys by dots, so a dot in a topic name is written as%2E(and%as%25), as forFileLog. An offset outside of a partition is an error (auto.offset.reset=error), every configured topic must be present in the metadata, and an unbounded stream checks the topics for new partitions every 5 seconds.STREAM BOUNDEDfinishes at the high watermarks as of the start of the read (or at the end-of-partition event). An idle stream waits for the consumer queue asynchronously (the queue writes to a pipe when it gets an event), so that it does not hold a thread of the pipeline (e.g. for the other tables of aMergetable).WATERMARKis not supported.Test:
test_kafka_stream_cursorin the existingtest_storage_kafka/test_batch_fast.py(both engines; bounded, nothing consumed for the group, cursor with a dotted topic name, a subcolumn of aTuple, out-of-range and invalid cursors, unbounded, a partition added while an unbounded stream runs).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 the offsets it read up to (
{topic: {partition: offset}}) through the holder, so aKafkatable can be the source of an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL), which resumes every refresh from them without a consumer group. Tested bytest_kafka_stream_cursor(three rounds, both engines). An incremental refresh rejectsLIMIT/OFFSET/LIMIT BYand the limits with the overflow modebreak(read_overflow_mode,result_overflow_mode,timeout_overflow_mode), which would stop the read before it reports the cursor (05770_incremental_refreshable_mv_rejects_limit). A query that closes the source in another way (DISTINCTthat has got all its rows,GROUP BYorDISTINCTwith the overflow modebreak) still reads the source to the end:ReadToEndTransformafter the streaming sources ofMergeTreeandKafkatables discards the rest, so the cursor always advances (05875_incremental_refreshable_mv_reads_source_to_end).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::getStreamingCursoronly for an incremental refresh, which is what it exists for.Related: #42990
Related: #131769
Related: #131814
Related: #132145
Changelog category (leave one):
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 forKafkatables. They read the topics with their own consumer and do not take the messages away from the materialized views.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131818]