Skip to content

Streaming queries with cursors for Merge, Distributed, Kafka, FileLog, NATS and RabbitMQ - #131769

Closed
alexey-milovidov wants to merge 7 commits into
masterfrom
stream-cursors-more-engines
Closed

alexey-milovidov wants to merge 7 commits into
masterfrom
stream-cursors-more-engines

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Streaming queries (SELECT ... FROM t STREAM [BOUNDED] [CURSOR {...}]) were supported only for MergeTree and ReplicatedMergeTree tables. This PR adds STREAM and cursors for Merge, Distributed (and remote), Kafka, FileLog, NATS and RabbitMQ tables.

Related: #42990

The cursor of each engine:

  • Merge: every table is read with STREAM, and its cursor is {database: {table: <cursor of the table>}}. Narrowing, read-in-order and the parallel-replicas expansion are disabled for a streaming read. Narrowing concatenates streams, and a streaming child never finishes.
  • Distributed / remote: the query for each shard gets the subtree {shard_num: ...} of the cursor. The cursor of a ReplicatedMergeTree table refers to the block numbers allocated in Keeper, so it does not depend on the replica, and a stream can be resumed on any replica. A test covers this.
  • Kafka (both Kafka and Kafka2): a streaming read assigns all partitions to its own consumer, starting after the offsets in the cursor {topic: {partition: offset of the last message}}. It never joins the consumer group and never commits. It does not take messages away from the materialized views and does not need stream_like_engine_allow_direct_select. BOUNDED ends at the high watermarks of its start.
  • FileLog: the files are read with separate readers, and the read positions stored by the table are not moved. The cursor is {file name: offset of the last record}. The final cursor of a bounded read is {file name: {'offset': ..., 'inode': ...}}, so a rotated file is read again from the beginning.
  • NATS with nats_stream (JetStream): an ephemeral ordered consumer starts after the sequence in {stream: sequence}. A new _sequence virtual column holds the stream sequence. Core NATS keeps no messages, so it does not support STREAM.
  • RabbitMQ with stream queues (x-queue-type=stream): a separate connection consumes with x-stream-offset, using the cursor {queue: offset}. New _queue and _offset virtual columns. RabbitMQ does not report the end of a stream queue, so BOUNDED ends after stream_poll_timeout_ms without messages. Classic queues do not support STREAM.

A bounded read reports its final cursor under the key path of the child: Context::getStreamingCursor and StreamingCursor::createChild. As a result, Merge, Kafka, FileLog, NATS and RabbitMQ tables can be the sources of incremental refreshable materialized views (APPEND INCREMENTAL). An incremental refresh now starts its final cursor from the previous one, so a table of a Merge table that is not read in some refresh keeps its position. A Distributed table is rejected as such a source: the shards do not send the cursor of a bounded read back. That would need a new packet in the native protocol, so it is left for a follow-up.

Other changes:

  • A cursor key may contain dots (file names, topics, subjects), using backslash escaping in the dotted form. A flat key written as {'a.b': 1} in CURSOR is now one key with a dot, not a path. No test or code relied on the old meaning.
  • SortChunksBySequenceNumber pushes the chunk with the next sequence number as soon as it arrives. Before, a remote read of an infinite stream returned nothing until every parallel unmarshalling stream had a chunk.
  • An idle stream source of a queue engine returns an empty chunk after each poll, so that it does not hold a pipeline thread (e.g. for the other tables of a Merge table).
  • WATERMARK is rejected with NOT_IMPLEMENTED for all the new engines.

Tests:

  • Stateless: 05768 (Merge, with incremental refresh), 05769 (Distributed, both values of prefer_localhost_replica, unbounded), 05770 (ReplicatedMergeTree resume on another replica), 05771 (FileLog).
  • Integration, added to the existing modules: test_kafka_stream_cursor (both Kafka engines, with incremental refresh), test_nats_stream_cursor, test_rabbitmq_stream_cursor.
  • All of them pass locally (aarch64, RelWithDebInfo), as do the existing streaming_queries, FileLog and incremental-refresh tests.

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 Merge, Distributed, Kafka, FileLog, NATS (JetStream) and RabbitMQ (stream queues) tables. Such tables, except Distributed, can be the sources of incremental refreshable materialized views.

🤖 Generated with Claude Code


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

alexey-milovidov and others added 7 commits November 15, 2026 00:37
- `Merge`: each table is read with STREAM, its cursor is the subtree
  `{database: {table: ...}}` of the cursor of the query.
- `Distributed` (and `remote`): the query for each shard gets the subtree
  `{shard_num: ...}` of the cursor.
- `Kafka`: a streaming read assigns all partitions to its own consumer,
  starting after the offsets in the cursor `{topic: {partition: offset}}`,
  never joins the consumer group and never commits.
- A bounded read reports its final cursor under the key path of the child.
- Keys of a cursor may contain dots (escaped in the dotted form).

Related: #42990

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `FileLog`: a streaming read uses its own readers and never moves the read
  positions of the table; its cursor is `{file name: offset of the last record}`.
- `NATS` with `nats_stream`: an ephemeral ordered consumer starts after the
  sequence in the cursor `{stream: sequence}`; the new `_sequence` virtual
  column holds the stream sequence of a message.
- Draft tests for `Merge`, `Distributed`, `ReplicatedMergeTree` and `FileLog`.

Related: #42990

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tests for Kafka and NATS

A streaming read of a table with stream queues (`x-queue-type = stream`) uses
its own connection and consumes with `x-stream-offset` after the offsets in the
cursor `{queue: offset}`. New `_queue` and `_offset` virtual columns.

Related: #42990

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- An idle stream of a queue engine or `FileLog` returns an empty chunk after a
  poll instead of holding the thread (it starved the other tables of `Merge`).
- A bounded `Kafka` stream ends at the high watermarks of its start; a bounded
  `NATS` stream compares the delivered count of the consumer, not the stream
  sequence (it never finished after expired messages or other subjects).
- The `FileLog` final cursor holds the inode, so a rotated file is read anew;
  an offset not at a record start is rejected; a truncated file is read anew.
- An incremental refresh starts the final cursor from the previous one, so a
  table of a `Merge` table that is not read this time keeps its position.
- A `RabbitMQ` message without `x-stream-offset` is an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…halling stream

`SortChunksBySequenceNumber` pushed a chunk only when every unfinished input had
one, so a remote read of an infinite stream (`STREAM` from a `Distributed`
table) returned nothing until enough chunks arrived to fill all the parallel
unmarshalling streams. Push the chunk with the next sequence number as soon as it
arrives.

Also fix the cursors in the test of `ReplicatedMergeTree` (block numbers start
at 0), add the references of the tests of `Merge` and `FileLog`, and add an
integration test for `RabbitMQ` stream queues.

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 [cb9431a]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
02983_const_sharding_key FAIL cidb
01231_distributed_aggregation_memory_efficient_mix_levels FAIL cidb
04303_58766_distributed_product_mode_local_default_database FAIL cidb
01615_random_one_shard_insertion FAIL cidb
05054_timeseries_under_distributed FAIL cidb
04320_skip_unavailable_shards_mode_distributed_engine FAIL cidb
05032_skip_unavailable_shards_nested_healthy_sibling FAIL cidb
04369_trivial_view_pushdown_skip_unused_shards FAIL cidb
01232_extremes FAIL cidb
02346_additional_filters_distr FAIL cidb
4 more test cases not shown
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
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_asan_ubsan) DROPPED

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

@Michicosun Michicosun left a comment

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.

It is better to split the PR by storage and not mix everything together.

Comment on lines +354 to 370
/// Holder of the cursor that a bounded streaming read (`STREAM BOUNDED`) advanced to.
/// A read of a composite table (`Merge`, `Distributed`) gives each of its children a child holder,
/// which places the child cursor under its own key path (e.g. database and table) in the parent.
struct StreamingCursor
{
std::mutex mutex;
CursorTreeNodePtr tree;

/// Merge the cursor of a finished read into this holder (or into the parent under `path`).
void merge(const CursorTreeNodePtr & cursor);

static std::shared_ptr<StreamingCursor> createChild(std::shared_ptr<StreamingCursor> parent, std::vector<String> path);

private:
std::shared_ptr<StreamingCursor> parent;
std::vector<String> path;
};

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.

You should not use this interface; it was added only for irmv. General streaming queries should not rely on it.

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.

Translation: "irmv" -> "Refreshable Materialized View with APPEND"

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.

Does the code explain "why" ("it was added only for irmv. General streaming queries should not rely on it")?

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.

Because there were no query snapshots at that moment, I will remove this interface once snapshots are implemented.

Comment on lines +235 to +244
/// An entry of `from` replaces an entry of another kind in `into`, e.g. an offset of a file
/// written by a user is replaced by an offset with an inode reported by a read.
if (std::holds_alternative<Int64>(value))
{
chassert(!into->hasSubtree(key));
into->setValue(key, std::get<Int64>(value));
}
else
{
chassert(!into->hasValue(key));
if (into->hasValue(key))
into->setSubtree(key, std::make_shared<CursorTreeNode>());

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.

Looks like an invariant break.

Comment on lines +29 to +44
/// Splits a dotted path into unescaped keys, see `escapeCursorKey`.
VectorWithMemoryTracking<String> splitCursorPath(const String & dotted_path)
{
VectorWithMemoryTracking<String> path(1);
for (size_t i = 0; i < dotted_path.size(); ++i)
{
const char c = dotted_path[i];
if (c == '\\' && i + 1 < dotted_path.size())
path.back() += dotted_path[++i];
else if (c == '.')
path.emplace_back();
else
path.back() += c;
}
return path;
}

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.

Logic related to escaping and de-escaping should not be handled here; it is the responsibility of a table to correctly prepare a cursor tree.

Comment on lines +56 to +58
/// The subtree of `cursor` at `path`, or nullptr if `cursor` is nullptr or has no such subtree.
/// Throws if `path` leads to a value instead of a subtree.
CursorTreeNodePtr getCursorSubtree(const CursorTreeNodePtr & cursor, const Strings & path);

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.

not needed, use CursorTreeNode::setSubtree

Comment on lines +86 to +92
/// Replace the cursor of the STREAM modifier, e.g. by its subtree for a child of a composite table
void setStreamCursor(CursorTreeNodePtr cursor)
{
chassert(stream_settings.has_value());
stream_settings->cursor = std::move(cursor);
}

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.

This is wrong. Table expression modifiers should not have methods for changing the internals of stream settings. It has only access to the full stream settings.

A streaming query (`SELECT ... FROM nats_table STREAM`, an experimental feature enabled by `enable_streaming_queries`) is supported for a table that reads a JetStream stream (`nats_stream`). It reads the subjects of the table with its own ephemeral ordered consumer, which does not acknowledge the messages of the durable consumer of the table. The cursor is a map from the stream name to the stream sequence of the last read message, and can be reconstructed from the `_sequence` virtual column:

```sql
SELECT _sequence, * FROM nats_table STREAM CURSOR {'events_stream': 41}

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.

Do not add virtual columns that represent the cursor. I want to rework it in mt; it is a bad approach.

Comment on lines +342 to +348
/// The last ones, see `RabbitMQSource`. They are filled only by a streaming query, see `RabbitMQStreamSource`.
if (has_stream_queues)
{
desc.addEphemeral("_queue", std::make_shared<DataTypeString>(), "", VirtualsMaterializationPlace::Reader);
desc.addEphemeral("_offset", std::make_shared<DataTypeInt64>(), "", VirtualsMaterializationPlace::Reader);
}

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.

Here also.

#include <Storages/StorageFile.h>
#include <Storages/StorageFactory.h>
#include <Storages/StorageMerge.h>
#include <Storages/StorageMaterializedView.h>

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.

Abstraction leak: do not include or deisolate the internal materialized-views logic.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Split by storage, as requested in the review:

How the review comments are addressed:

  • Context::getStreamingCursor and StreamingCursor: no longer used by the new engines (no createChild and no reporting of the final cursor). Since only MergeTree reports the cursor, Accept only MergeTree sources for an incremental refresh #131814 rejects other sources of an incremental refresh, which would otherwise re-read the whole source on every refresh, and documents in Context.h that the holder exists only for the incremental refresh.
  • The mergeCursors change (invariant break): reverted.
  • Escaping in CursorTree: reverted, the parser is unchanged. The tables whose keys may contain dots (Kafka topics, FileLog file names, RabbitMQ queue names) read the collapsed paths of the cursor tree themselves.
  • getCursorSubtree: removed; hasSubtree/getSubtree are used directly.
  • TableExpressionModifiers::setStreamCursor: removed; the per-child and per-shard modifiers are constructed from a copy of the full stream settings.
  • Virtual columns for the cursor (_sequence for NATS, _queue/_offset for RabbitMQ): removed.
  • The include of the materialized-view logic in StorageMerge: removed; the check is in StorageMaterializedView only.

The Fast test failures of this PR (UNKNOWN_DATABASE in Distributed queries) were a real bug: the per-shard cursor rewrite called StorageID::getDatabaseName for every table expression, also without STREAM. It runs only for streaming reads and compares the names without throwing in #131816. The arm_tidy failures (duplicate includes) are fixed in #131820 and #131821.

Closing this PR in favor of the ones above.

alexey-milovidov added a commit to davimi/ClickHouse that referenced this pull request Nov 17, 2026
An incremental refresh (`APPEND INCREMENTAL`) resumes from the cursor that the
read reports through `Context::getStreamingCursor`, and only a `MergeTree` read
reports it. When other engines support `STREAM`, a source of such an engine
would be read from the beginning on every refresh, appending the same rows again.
Reject it, and explain in `Context.h` that `StreamingCursor` exists only for the
incremental refresh.

Related: ClickHouse#42990
Related: ClickHouse#131769

Co-Authored-By: Claude Opus 5.5 <[email protected]>
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 19, 2026
…plica

The cursor of a `ReplicatedMergeTree` table refers to the block numbers allocated
in Keeper, so a stream can be resumed on another replica with the cursor obtained
on one replica. Block numbers of a replicated table start at 0.

Related: ClickHouse#42990
Related: ClickHouse#131769

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants