Repository navigation
Streaming queries with cursors for Distributed tables - #131816
alexey-milovidov wants to merge 17 commits into
Conversation
A streaming read of a `Distributed` table (and of the `remote` and `cluster` table
functions) sends the query with `STREAM` to every shard; the cursor is
`{shard number: <cursor of the table on the shard>}`, and a shard without an
entry is read from the beginning. The cursor of a `ReplicatedMergeTree` table
does not depend on the replica, so the read can be resumed on any replica.
`SortChunksBySequenceNumber` pushed a chunk only when every unfinished input had
one, so a remote read of an infinite stream returned nothing until enough chunks
arrived to fill all the parallel unmarshalling streams. It pushes the chunk with
the next sequence number as soon as it arrives now.
`WATERMARK` is not supported.
Related: #42990
Related: #131769
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [dd707ab] Summary: ❌
AI ReviewSummaryAdds experimental Findings❌ Blockers
💡 Nits
Tests
Missing context / blind spots
Performance & SafetyCursor transport was traced through Final VerdictStatus: ❌ Block Prevent successful incremental refreshes with incomplete cursors and add the focused early-termination regression. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes426 object files changed (+275.98 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1608 translation units recompiled, 8145 s compile time in total, 1608 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]>
…-distributed-tables
For an incremental refresh from a `Distributed` table, the initiator sets the internal setting `report_streaming_cursor` for the shards. A shard then creates the holder of the cursor for the query and sends the cursor its bounded streaming read advanced to in the new `StreamingCursor` server packet (protocol version 54497) before `EndOfStream`. The initiator keeps the cursors under the shard numbers, and fails if a shard does not send one. A local shard, including the local fallback of a lazy remote shard, reports through a child holder under the shard number. A streaming read for an incremental refresh of a table that does not report the cursor is refused by the analyzer, e.g. on a shard. `MultiplexedConnections` and `HedgedConnections` pass the new packet through; the native protocol spec describes it. Related: #131814 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cursor of a `MergeTree` table has e.g. `block_offset` -1 for a block with no row read yet, and the query for a shard of a `Distributed` table formats the cursor of the shard into its text, so it must be parsed back. The incremental refresh from a `Distributed` table failed with a syntax error on the shards. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…tables Master took protocol version 54497 for `CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`, so `STREAMING_CURSOR` moves to 54498.
… STREAM off serialized shard plans `setStreamCursorForShard` matched every table expression of the underlying table (or every table function), so an independent `t STREAM ... CURSOR` in a JOIN lost its cursor and replayed excluded rows. Match the replaced distributed table expression by its alias, unique among the table expressions of the query, and require exactly one match. The merge of master made all shards share one query tree (`Plan a distributed query once for all remote shards`), so the in-place rewrite of the cursor for one shard leaked into the others. Clone the tree for a streaming read before rewriting it. A serialized query plan (`serialize_query_plan = 1`, `ReadFromTableStep`, `ReadFromTableFunctionStep`) does not keep `StreamSettings`, so a shard made an ordinary snapshot read. Disable `serialize_query_plan` for the shards of a query that has a STREAM read. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131816&sha=321813a37af0900e22ef794a977cc88031492008&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted) #131816 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… STREAM source
`distributedWriteBetweenDistributedTables` forwards the whole cursor of the `Distributed` table
(`{shard: <cursor>}`) to every shard, where the underlying table cannot parse it. Execute such an
`INSERT SELECT` the regular way, where `ClusterProxy::executeQuery` passes each shard its own cursor.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ry read, including the shards The check that the source of an incremental refresh is a plain `MergeTree` with `enable_block_number_column` and `enable_block_offset_column` ran only on the outer source of the view, so it did not reach the tables on the shards of a `Distributed` source, whose cursor then skipped rows after a merge. Move it to `IStorage::checkStreamingCursorForIncrementalRefresh`, implemented by `MergeTreeData`, and call it also in the analyzer for every STREAM read of an incremental refresh. `StorageProxy` forwards it, together with `supportsStreaming` and `reportsStreamingCursor`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A JOIN with another streaming read of the underlying table, `serialize_query_plan = 1`, `INSERT SELECT` with every value of `parallel_distributed_insert_select`, and an incremental refresh rejected on the shards of a table without persisted block numbers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…longer used Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/StorageProxy.h
…formed cursors A STREAM read from a `Distributed` table nested in a subquery, a CTE, or a branch of `UNION` failed with a `LOGICAL_ERROR` exception: `buildQueryTreeForShard` numbers the aliases of the table expressions again (`createUniqueAliasesIfNecessary`), so the table expression that replaced the distributed one in the query for the shards has another alias than the distributed table expression, and `setStreamCursorForShard` did not find it. `StorageDistributed::read` now finds the replaced table expression by its place in the join tree and passes its alias to `ClusterProxy::executeQuery`, which looks for it in the whole query tree. An entry of the cursor that is not a cursor of a shard (a key that is not a shard number, or a number instead of the cursor of the table on the shard) was ignored and the shard was read from the beginning. It is now rejected with `INVALID_CURSOR_LOOKUP`. A shard without an entry is still read from the beginning. Also mark `HasStreamReadVisitor::needChildVisit` as `[[nodiscard]]` (clang-tidy, `modernize-use-nodiscard`): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131816&sha=af8fc971359a52c38fb4b4faeeeb42b07f575a3c&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #131816 Co-Authored-By: Claude Fable 5.2 <[email protected]>
The version on master is now 26.12, and the `settings_changes_history` check of the Style check requires a setting added now to be recorded under the current version: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131816&sha=57a98e138c498c70d8cc8988b2b93af08e697498&name_0=PR&name_1=Style%20check #131816 Co-Authored-By: Claude Fable 5.2 <[email protected]>
| std::lock_guard lock(cursor->mutex); | ||
| tree = cursor->tree; | ||
| } | ||
|
|
||
| writeVarUInt(Protocol::Server::StreamingCursor, *out); | ||
| writeFieldBinary(Field(cursorTreeToMap(tree)), *out); |
There was a problem hiding this comment.
[Blocker] Require completion of the bounded read before accepting its cursor
This sends the initially empty cursor even when the source finished because its output was closed, without reaching MergeTreeCommitOrderSource::surfaceFinalCursor. Merely receiving this packet then satisfies the new check in RemoteQueryExecutor::processPacket.
For example, for a one-shard Distributed table d over a large source with persisted block columns, this definition is accepted:
CREATE MATERIALIZED VIEW mv
REFRESH EVERY 10 YEAR APPEND INCREMENTAL TO tgt EMPTY
AS SELECT a FROM d LIMIT 1
SETTINGS prefer_localhost_replica = 0, max_threads = 1, max_block_size = 1;With more source rows than the pipeline can buffer, LimitTransform closes the bounded source before it completes its round. The shard still sends this empty packet and EndOfStream, so the refresh succeeds without advancing the saved cursor. A second refresh with no inserts reads the same snapshot and appends another row. The local-shard path also leaves the cursor unchanged on early termination.
Please either reject queries that can terminate an incremental source early or drain every bounded source to completion before successfully persisting its cursor. Add a stateless case that refreshes twice without new inserts, with a small block size and both values of prefer_localhost_replica. This finding is based on the control-flow trace; no server binary is available in this review job.
Support streaming queries for
Distributedtables and theremote/clustertable functions. The query is sent withSTREAMto every shard; the cursor is{shard number: <cursor of the table on the shard>}, and a shard without an entry is read from the beginning. The cursor of aReplicatedMergeTreetable does not depend on the replica, so a read can be resumed on any replica of a shard.SortChunksBySequenceNumber(after the parallel unmarshalling of a remote read) pushed a chunk only when every unfinished input had one, so a remote read of an infinite stream returned nothing until enough chunks arrived to fill all the parallel unmarshalling streams. It now pushes the chunk with the next sequence number as soon as it arrives, and keeps the previous rule as the fallback.The first version of this change failed many
Distributedtests in Fast test withUNKNOWN_DATABASE: it compared the database name of every table expression, throughStorageID::getDatabaseName, also for queries withoutSTREAM. The rewrite of the cursor now runs only for a streaming read and compares the names without throwing.A query with a STREAM read is sent to the shards as text even with
serialize_query_plan = 1, because the serialized plan does not keep the settings of STREAM, and anINSERT SELECTfrom a streamingDistributedsource does not useparallel_distributed_insert_select, so that every shard gets its own cursor.WATERMARKis not supported. The read can be nested in a subquery, a CTE, or a branch ofUNION: the table expression that replaced the distributed one is found in the query for the shards by its place in the join tree, because the aliases are numbered again there. An entry of the cursor that is not a cursor of a shard is rejected withINVALID_CURSOR_LOOKUP. Test:05770_streaming_queries_distributed_cursors(both values ofprefer_localhost_replica,remote, an unbounded stream from two shards, 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 initiator sets the internal setting
report_streaming_cursorfor the shards; a shard creates the holder of the cursor and sends the cursor of its bounded read in a newStreamingCursorserver packet (type 19, protocol version 54498) beforeEndOfStream. The initiator keeps the cursors under the shard numbers and fails if a shard does not send one (e.g. an older server). A local shard, including the local fallback of a lazy remote shard, reports through a child holder under the shard number. The analyzer refuses a streaming read for an incremental refresh of a table that does not report the cursor, or whose cursor is not stable across merges (e.g. aMergeTreewithout persisted block numbers), also on a shard.MultiplexedConnectionsandHedgedConnectionspass the packet through, and the native protocol spec (docs/resources/develop-contribute/native-protocol/protocol.mdx) describes it. Tested by05770_streaming_queries_distributed_cursorswith both values ofprefer_localhost_replica.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 forDistributedtables and theremoteandclustertable functions.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131816]