Skip to content

Streaming queries with cursors for Distributed tables - #131816

Open
alexey-milovidov wants to merge 17 commits into
masterfrom
stream-distributed-tables
Open

alexey-milovidov wants to merge 17 commits into
masterfrom
stream-distributed-tables

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Support streaming queries for Distributed tables and the remote/cluster table functions. The query is sent 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 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 Distributed tests in Fast test with UNKNOWN_DATABASE: it compared the database name of every table expression, through StorageID::getDatabaseName, also for queries without STREAM. 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 an INSERT SELECT from a streaming Distributed source does not use parallel_distributed_insert_select, so that every shard gets its own cursor. WATERMARK is not supported. The read can be nested in a subquery, a CTE, or a branch of UNION: 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 with INVALID_CURSOR_LOOKUP. Test: 05770_streaming_queries_distributed_cursors (both values of prefer_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_cursor for the shards; a shard creates the holder of the cursor and sends the cursor of its bounded read in a new StreamingCursor server packet (type 19, protocol version 54498) before EndOfStream. 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. a MergeTree without persisted block numbers), also on a shard. MultiplexedConnections and HedgedConnections pass the packet through, and the native protocol spec (docs/resources/develop-contribute/native-protocol/protocol.mdx) describes it. Tested by 05770_streaming_queries_distributed_cursors with both values of prefer_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::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 Distributed tables and the remote and cluster table functions.

🤖 Generated with Claude Code


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

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

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dd707ab]

Summary: ❌

job_name test_name status info comment
Unit tests (arm_debug) FAIL
ParserStreamSettings.CursorRejectsMalformedInput FAIL cidb
AllTests FAIL cidb
Unit tests (asan_ubsan) FAIL
ParserStreamSettings.CursorRejectsMalformedInput FAIL cidb
AllTests FAIL cidb
Unit tests (tsan) FAIL
ParserStreamSettings.CursorRejectsMalformedInput FAIL cidb
AllTests FAIL cidb
Unit tests (msan) FAIL
ParserStreamSettings.CursorRejectsMalformedInput FAIL cidb
AllTests FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (wasm64) DROPPED
Build (arm_fuzzers) DROPPED
Integration tests (arm_binary, distributed plan, targeted) DROPPED

AI Review

Summary

Adds experimental STREAM reads with per-shard cursors for Distributed, remote, and cluster, including cursor transport for incremental refreshes. The six prior findings are addressed in the current code. One correctness blocker remains: early termination can make a refresh succeed without advancing its cursor, so subsequent refreshes append rows again without new source data.

Findings

❌ Blockers

  • src/Server/TCPHandler.cpp:2184: A StreamingCursor packet is sent even if the bounded source never reported completion. An accepted APPEND INCREMENTAL query with LIMIT 1, max_block_size = 1, and enough source rows closes the source before MergeTreeCommitOrderSource::surfaceFinalCursor. The remote path sends an empty cursor that passes RemoteQueryExecutor's receipt check; the local path also retains the previous cursor. The refresh succeeds, and another refresh without inserts appends from the same snapshot again. Reject early-terminating incremental queries or ensure all bounded sources complete and report their cursors before committing success. The related drain path in RemoteQueryExecutor::finishUnlocked also bypasses the normal end-of-stream receipt check, so validation needs to cover both normal completion and early closure.

💡 Nits

  • src/Parsers/ParserCreateQuery.cpp:3452: The structured materialized-view documentation still says APPEND INCREMENTAL requires a single plain MergeTree source. Update the source registration to describe Distributed support and the prerequisites on its leaf tables; regenerate the reference page through the documentation workflow.
Tests
  • ⚠️ Add a focused stateless regression using a large source, LIMIT 1, and a small block size. Run two refreshes without intervening inserts for both values of prefer_localhost_replica; either reject the definition or verify that the second refresh appends nothing. The same completion requirement applies to other operators that can stop reading early, such as DISTINCT with a limit hint.
Missing context / blind spots
  • ⚠️ The blocker is established by static control-flow tracing; this review job has no server binary and local test execution is prohibited. The new 05770_streaming_queries_distributed_cursors test passes in Fast test. Targeted sanitizer jobs are pending and the existing test does not exercise early termination.
Performance & Safety

Cursor transport was traced through Connection decoding, MultiplexedConnections and HedgedConnections forwarding/draining, RemoteQueryExecutor merging, local child holders, and persistence by RefreshTask and the Iceberg refresh writer. The remaining gap is that a received packet or a successful pipeline does not prove that every source supplied a final cursor.

Final Verdict

Status: ❌ Block

Prevent successful incremental refreshes with incomplete cursors and add the focused early-termination regression.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 15, 2026
Comment thread src/Storages/StorageDistributed.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dd707aba1 with master 515c1baee (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

426 object files changed (+275.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ClusterProxy/executeQuery.cpp.o 627.22 KiB 667.62 KiB +40.40 KiB (+6.44%)
src/CMakeFiles/dbms.dir/Storages/StorageMaterializedView.cpp.o 860.65 KiB 837.23 KiB -23.42 KiB (-2.72%)
src/CMakeFiles/dbms.dir/Server/TCPHandler.cpp.o 1019.91 KiB 1.01 MiB +18.43 KiB (+1.81%)
src/CMakeFiles/dbms.dir/QueryPipeline/RemoteQueryExecutor.cpp.o 667.06 KiB 685.20 KiB +18.13 KiB (+2.72%)

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

1608 translation units recompiled, 8145 s compile time in total, 1608 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 5 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]>
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]>
@mintlify

mintlify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 25, 2026, 4:00 AM

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 7 commits November 19, 2026 15:55
…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]>
@clickhouse-gh clickhouse-gh Bot added comp-streaming-queries Streaming queries: queries that keep reading a table as data arrives - cursors, subscriptions to ... and removed comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). labels Nov 20, 2026
alexey-milovidov and others added 2 commits November 22, 2026 13:15
# 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]>
Comment thread src/Server/TCPHandler.cpp
Comment on lines +2180 to +2185
std::lock_guard lock(cursor->mutex);
tree = cursor->tree;
}

writeVarUInt(Protocol::Server::StreamingCursor, *out);
writeFieldBinary(Field(cursorTreeToMap(tree)), *out);

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

This branch was successfully deployed

1 active deployment
staging - docs — dd707aba Deployed Nov 25, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-streaming-queries Streaming queries: queries that keep reading a table as data arrives - cursors, subscriptions to ... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant