Repository navigation
Streaming queries with cursors for Merge, Distributed, Kafka, FileLog, NATS and RabbitMQ - #131769
alexey-milovidov wants to merge 7 commits into
Conversation
- `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]>
…tedMergeTree` Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [cb9431a] Summary: ❌
|
Michicosun
left a comment
There was a problem hiding this comment.
It is better to split the PR by storage and not mix everything together.
| /// 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; | ||
| }; |
There was a problem hiding this comment.
You should not use this interface; it was added only for irmv. General streaming queries should not rely on it.
There was a problem hiding this comment.
Translation: "irmv" -> "Refreshable Materialized View with APPEND"
There was a problem hiding this comment.
Does the code explain "why" ("it was added only for irmv. General streaming queries should not rely on it")?
There was a problem hiding this comment.
Because there were no query snapshots at that moment, I will remove this interface once snapshots are implemented.
| /// 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>()); |
There was a problem hiding this comment.
Looks like an invariant break.
| /// 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; | ||
| } |
There was a problem hiding this comment.
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.
| /// 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); |
There was a problem hiding this comment.
not needed, use CursorTreeNode::setSubtree
| /// 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); | ||
| } | ||
|
|
There was a problem hiding this comment.
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} |
There was a problem hiding this comment.
Do not add virtual columns that represent the cursor. I want to rework it in mt; it is a bad approach.
| /// 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); | ||
| } | ||
|
|
| #include <Storages/StorageFile.h> | ||
| #include <Storages/StorageFactory.h> | ||
| #include <Storages/StorageMerge.h> | ||
| #include <Storages/StorageMaterializedView.h> |
There was a problem hiding this comment.
Abstraction leak: do not include or deisolate the internal materialized-views logic.
|
Split by storage, as requested in the review:
How the review comments are addressed:
The Fast test failures of this PR ( Closing this PR in favor of the ones above. |
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]>
…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]>
Streaming queries (
SELECT ... FROM t STREAM [BOUNDED] [CURSOR {...}]) were supported only forMergeTreeandReplicatedMergeTreetables. This PR addsSTREAMand cursors forMerge,Distributed(andremote),Kafka,FileLog,NATSandRabbitMQtables.Related: #42990
The cursor of each engine:
Merge: every table is read withSTREAM, 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.Narrowingconcatenates 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 aReplicatedMergeTreetable 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(bothKafkaandKafka2): 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 needstream_like_engine_allow_direct_select.BOUNDEDends 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.NATSwithnats_stream(JetStream): an ephemeral ordered consumer starts after the sequence in{stream: sequence}. A new_sequencevirtual column holds the stream sequence. Core NATS keeps no messages, so it does not supportSTREAM.RabbitMQwith stream queues (x-queue-type=stream): a separate connection consumes withx-stream-offset, using the cursor{queue: offset}. New_queueand_offsetvirtual columns. RabbitMQ does not report the end of a stream queue, soBOUNDEDends afterstream_poll_timeout_mswithout messages. Classic queues do not supportSTREAM.A bounded read reports its final cursor under the key path of the child:
Context::getStreamingCursorandStreamingCursor::createChild. As a result,Merge,Kafka,FileLog,NATSandRabbitMQtables 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 aMergetable that is not read in some refresh keeps its position. ADistributedtable 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.b': 1}inCURSORis now one key with a dot, not a path. No test or code relied on the old meaning.SortChunksBySequenceNumberpushes 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.Mergetable).WATERMARKis rejected withNOT_IMPLEMENTEDfor all the new engines.Tests:
05768(Merge, with incremental refresh),05769(Distributed, both values ofprefer_localhost_replica, unbounded),05770(ReplicatedMergeTreeresume on another replica),05771(FileLog).test_kafka_stream_cursor(bothKafkaengines, with incremental refresh),test_nats_stream_cursor,test_rabbitmq_stream_cursor.streaming_queries,FileLogand incremental-refresh tests.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 forMerge,Distributed,Kafka,FileLog,NATS(JetStream) andRabbitMQ(stream queues) tables. Such tables, exceptDistributed, can be the sources of incremental refreshable materialized views.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131769]