Skip to content

Streaming queries with cursors for Kafka tables - #131818

Open
alexey-milovidov wants to merge 13 commits into
masterfrom
stream-kafka-tables
Open

alexey-milovidov wants to merge 13 commits into
masterfrom
stream-kafka-tables

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Support streaming queries for Kafka tables (both Kafka and the Keeper-based Kafka2). 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 need stream_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 for FileLog. 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 BOUNDED finishes 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 a Merge table). WATERMARK is not supported.

Test: test_kafka_stream_cursor in the existing test_storage_kafka/test_batch_fast.py (both engines; bounded, nothing consumed for the group, cursor with a dotted topic name, a subcolumn of a Tuple, 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 a Kafka table 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 by test_kafka_stream_cursor (three rounds, both engines). An incremental refresh rejects LIMIT / OFFSET / LIMIT BY and the limits with the overflow mode break (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 (DISTINCT that has got all its rows, GROUP BY or DISTINCT with the overflow mode break) still reads the source to the end: ReadToEndTransform after the streaming sources of MergeTree and Kafka tables 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::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 Kafka tables. 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]

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

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b0ec058]


AI Review

Summary

Adds independent, cursor-based Kafka streaming reads and incremental refresh support for both Kafka engines, with source draining for early-terminating refresh plans. Two correctness blockers remain: draining a final buffered chunk can leave the pipeline stuck, and malformed-message recovery can produce invalid Enum values.

Findings

❌ Blockers

  • src/Processors/Transforms/ReadToEndTransform.cpp:24–28: When the output is closed and a finished producer still has one buffered chunk, the initial input.isFinished check returns false. Pulling that chunk finishes the input, but the transform returns NeedData. The graph leaves it idle, and the finished producer cannot wake it again, causing a Pipeline stuck exception. A bounded MergeTreeCommitOrderSource can finish while its final output remains buffered because it checks internal completion before output capacity. A refresh can fail after appending rows and replay them on retry. Recheck input completion after discarding the chunk and return Finished when appropriate.
  • src/Storages/Kafka/KafkaStreamSource.cpp:378: With kafka_handle_error_mode = 'stream', a malformed message inserts the column's default rather than the data type's default. For Enum8('a' = 1, 'b' = 2), this produces invalid value 0; selecting the error row then throws UNKNOWN_ELEMENT_OF_ENUM, and a refresh can write the invalid value to its destination. Use the header type's insertDefaultInto, as the existing consumption paths do. Both Kafka engines are affected.
Tests
  • ⚠️ Add focused coverage for draining a final buffered chunk after its producer has finished and its downstream has closed. The new stateless test passes but does not establish this ordering.
  • ⚠️ Exercise a malformed JSONEachRow message with a nonzero-default Enum through STREAM for both Kafka engines. The existing enum regression exercises background consumption only.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary is available, so these findings are based on source traces. At review time, Kafka integration jobs are pending. The fast-test report confirms that 05770_incremental_refreshable_mv_rejects_limit and 05875_incremental_refreshable_mv_reads_source_to_end passed. CI report.
Final Verdict

Status: ❌ Block

Fix the terminal-input transition and use the data type's default for malformed-message recovery, with focused regression coverage.

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

Comparing 3fa853c27 with master ffc535ce4 (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 ⚠️

394 object files changed (+496.31 KiB total), 1 added.

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.

Job report

@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 `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]>
alexey-milovidov and others added 4 commits November 19, 2026 16:49
- 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]>
@clickhouse-gh clickhouse-gh Bot added comp-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... and removed comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Nov 20, 2026
alexey-milovidov and others added 5 commits November 22, 2026 13:16
…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]>
Comment on lines +24 to +28
input.setNeeded();
if (input.hasData())
input.pull(/*set_not_needed=*/ false);

return Status::NeedData;

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] 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();

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

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-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant