Repository navigation
Streaming queries from Memory tables - #131860
alexey-milovidov wants to merge 29 commits into
Conversation
A streaming query (`SELECT ... FROM memory_table STREAM`) returns the blocks that the table has at the start of the query, and then every block inserted later, in the order of the blocks of the table. It follows the numbers of the blocks within a generation of the data, wakes up on every change of the data, and waits for new blocks on an event descriptor, without holding a thread of the pipeline. `STREAM BOUNDED` returns the blocks the table has at the start of the query. The query fails if the data is replaced while it runs (`TRUNCATE`, a mutation, a restore), and with `TOO_SLOW` if the blocks it has not read yet are removed by `max_rows_to_keep` or `max_bytes_to_keep`. `CURSOR` and `WATERMARK` are not supported. Related: #42990 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th a mutation `TRUNCATE` waits for the running streaming queries to finish, as for any other `SELECT`, so it cannot replace the data while a stream runs; document it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…from Memory Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of STREAM from Memory The output of a client that exits while nothing reads its FIFO is lost. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [50b6a61] AI ReviewSummaryAdds bounded and unbounded streaming reads from Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Fix complete cursor reporting on early termination, order it before transactional commit for both source implementations, and persist progress when a refresh produces no rows. Include focused regression coverage for these paths. |
…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 streaming read of a `Memory` table accepts a cursor
`{epoch, generation, block_number}`, and a bounded read reports it through the
holder of an incremental refresh, so a `Memory` table can be the source of an
incremental refresh. The epoch is a random number of the server process, as the
generations of the data are numbered anew in every process. A cursor of another
process or of a generation that started empty (`TRUNCATE`) means that all the
blocks are new; a generation that a mutation rewrote cannot be resumed after a
position in a previous one, so the refresh fails.
Related: #131814 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ncremental refresh validation A `Memory` table supports incremental refresh now. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes the `modernize-use-nodiscard` error of `clang-tidy` in the `arm_tidy` build: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131860&sha=latest&name_0=PR Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ike an ordinary read - Apply the row-level security filter and `PREWHERE` that the planner gives to the storage, as filter steps after the streaming source, the row-level filter first. - Read the columns with `readColumnsFromMemoryBlock` (exported from `ReadFromMemoryStorageStep`), which decompresses the columns of a table with `compress = 1` and fills the columns absent from the blocks inserted before `ALTER TABLE ... ADD COLUMN`. - Wake the source up in `onUpdatePorts` and finish in `prepare` when the output is closed, so that an unbounded stream with `LIMIT` finishes without waiting for another insert. - Remove the expired subscriptions in `MemoryTableSubscribers::subscribe` too, so that they do not accumulate in a table that is read but not written. Test: `05836_streaming_queries_memory_table_reading`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…memory_table` With a single insert thread (e.g. a random `max_threads = 1`), `INSERT ... SELECT` adds all its blocks to the `Memory` table at once, and the table does not remove the blocks it has just got, so the stream never fell behind and the test waited for `TOO_SLOW` until the timeout. Insert the rows with separate queries. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bounded streaming read reports its cursor once it reaches the end of the stream. A `LIMIT` stops the read earlier and may drop rows of an already read chunk, so the next refresh would resume from a cursor that does not match the appended rows and append the same rows again. Reject `LIMIT`/`OFFSET` (and the `limit`/`offset` settings) in the query of an `APPEND INCREMENTAL` view, both at definition and before each refresh, for every source engine including `MergeTree`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The holder of the streaming cursor starts from the cursor of the previous refresh, so that a part of a composite source that is not read keeps its position. But merging into it made the cursor append-only: the partitions that `ReadState::updatePartitionSet` removes (dropped by TTL or `DROP PARTITION`) survived every refresh, and the persisted cursor grew with every partition ever observed. Now the first cursor reported under a path (the root for a plain table, the key path of a child holder) replaces the subtree of the previous refresh at that path, and further reports under the same path (the parallel streams of one read) are merged into it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eMemory` `MemoryTableWakeup` has its own `reset` method, so calling it through the `std::shared_ptr` as `wakeup->reset` is reported by clang-tidy as ambiguous with `std::shared_ptr::reset`, and `Build (arm_tidy, 2/4)` fails. Dereference the pointer explicitly, as in the other places of the code base. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131860&sha=d724d8d016ca90d56f0503a22d1e1f8450148cb6&name_0=PR&name_1=Build%20%28arm_tidy%2C%202%2F4%29 PR: #131860 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…e overflow mode `break` A query of an incremental refresh can stop the bounded read before its end: - A `DISTINCT` by constants or a `LIMIT BY` without keys closes the source once it has its result. `MergeTreeCommitOrderSource::prepare` went to `handleShutdown` and never reached `surfaceFinalCursor`, so the refresh kept the previous cursor and appended the same rows again on the next refresh. Now `handleShutdown` of a bounded read finishes the running round and reports the cursor after all its rows: the rest of the rows cannot change the result of the query, so they are consumed without being read. - With the overflow mode `break` (e.g. `max_rows_to_read` with `read_overflow_mode = 'break'`) the query finishes successfully with a partial result, while the cursor is advanced past the rows that were not read, losing them. `validateIncrementalDefinition` now rejects the value `break` of every `*_overflow_mode` setting, taking the `SETTINGS` clause of the query into account (it is not applied to the context when the view is created, which also applies to the existing check of `limit` and `offset`). #132145 (comment) #132145 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
…memory-tables Bring in the fixes of #132145 (this branch already contains its first commit): the rejection of `LIMIT`, `OFFSET` and the overflow mode `break` in an incremental refresh, the cursor of an early stopped read, and the replacement of the reported part of the seeded refresh cursor. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A source of an incremental refresh in a database with `lazy_load_tables = 1` is a `StorageTableProxy` until it is loaded. The proxy did not forward `reportsStreamingCursor`, so the refresh of a supported source failed with `NOT_IMPLEMENTED` (`05816_streaming_queries_lazy_load_source`). Co-Authored-By: Claude Fable 5.2 <[email protected]>
…table - The read is a `SourceStepWithFilter` (`ReadFromMemoryStream`) instead of `ReadFromPreparedSource`, so `hasUnboundedSource` sees its stream settings and an unbounded stream is planned as a streaming query: aggregation, `ORDER BY`, `INTERSECT`, the query cache, etc. are rejected with `ILLEGAL_STREAM` instead of waiting for the end of the stream. - The row-level security filter and `PREWHERE` are transforms inside the pipe of the step instead of `FilterStep`s, so the optimizations of the query plan cannot merge the policy with an expression of the user, and such an expression is never evaluated on the rows the policy hides. - The source looks at the data when it starts to read instead of when the query is planned, so it gets the rows of a materialized CTE (or of a `GLOBAL` subquery), whose table is filled during the execution of the query. - A bounded read that the query stopped early (e.g. a `DISTINCT` by constants) reports the cursor after all its blocks, the same as `MergeTreeCommitOrderSource`, so an incremental refresh does not get these blocks again. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| /// it fails, and the reported cursor is discarded along with it. | ||
| /// If the round did not start, the read returned nothing, and the cursor stays in place. | ||
| const bool is_bounded_subscription = !stream_settings.subscribe_for_updates; | ||
| if (is_bounded_subscription && current_round.has_value() && !final_cursor_surfaced) |
There was a problem hiding this comment.
[Blocker] Report the positions of parallel sources stopped before round startup.
For an incremental SELECT DISTINCT toUInt64(1) AS k FROM src over a partitioned MergeTree source, one streaming source can produce the result while another source is still waiting for its first subscription update or building pending_round. Closing the latter's output reaches this branch with no current_round, so it finishes without reporting its assigned partitions. Those rows cannot change the current DISTINCT result, but they must still be consumed by this refresh.
The first other source's report replaces the previous root cursor in StreamingCursor::merge, so the unreported partition positions disappear. A subsequent refresh can reread the unchanged partitions and append another 1, even with a MergeTree target. Please account for sources stopped before their round starts, as well as active rounds, and add a regression with partitions assigned to different streams. Both added early-stop tests use max_threads = 1, which excludes this case.
There was a problem hiding this comment.
🕵 This code (MergeTreeCommitOrderSource::handleShutdown) is not a change of this PR: it comes from #132145, which this branch includes, and the same finding is open there (the thread on validateIncrementalDefinition about sources stopped before startRound). It has to be fixed in that PR, so that the two branches do not diverge; this branch gets the fix by merging it (the current head of that branch is merged here in e49765c). Not fixed yet - leaving this thread open until the fix lands there.
| if (is_bounded_subscription && current_round.has_value() && !final_cursor_surfaced) | ||
| { | ||
| read_state.finishReadRound(current_round->partitions, current_round->safe_block_numbers); | ||
| surfaceFinalCursor(); |
There was a problem hiding this comment.
[Blocker] Finish publishing the cursor before the transactional target commits.
This publishes the early-stop cursor only when the source processes its closed output. That is not ordered before downstream completion: ISimpleTransform::prepare closes its input and finishes its output together, and ExecutingGraph::updateNode only calls onUpdatePorts if the upstream processor is already executing. For this source, that callback merely disables the subscription; the cursor is reported later in handleShutdown.
With parallel streaming sources, an early-stop query such as a constant DISTINCT can therefore finish the downstream pipeline while source shutdown is still in progress. IcebergStorageSink::initializeMetadata serializes streaming_cursor->tree at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1662, before the executor joins all source work. It can commit a stale/partial cursor with the new row, causing replay on the next refresh. If reporting overlaps serialization, the reader also races with StreamingCursor::merge, including its assignment to tree.
Order all cursor reports before transactional snapshot commit; locking serialization alone does not ensure every report has arrived. Please cover early completion with a transactional target and multiple source streams. The added tests use a MergeTree target, whose cursor is collected after executor completion, so they miss this ordering.
There was a problem hiding this comment.
🕵 Same as the thread above: the early-stop report of the cursor in MergeTreeCommitOrderSource::handleShutdown belongs to #132145, which this branch includes. The ordering of the cursor reports before the commit of a transactional target (IcebergStorageSink::initializeMetadata) has to be solved there, and this branch will get it by a merge. Not fixed yet - leaving this thread open. Note that MemoryStreamingSource of this PR mirrors that early-stop path (it reports the cursor from prepare when its output is closed), so whatever ordering mechanism is introduced in that PR has to be applied to it as well after the merge; on a normal completion it reports from tryGenerate before it finishes its output.
…ncremental refresh The check of the `*_overflow_mode` settings (and of `limit`/`offset`) applied the raw changes of the `SETTINGS` clause to a copy of the settings, so `SETTINGS read_overflow_mode = 'throw', profile = '...'` with a profile that sets the mode `break` passed the check, while the refresh ran with `break` and lost the rows of the source that were not read. Apply the clause to a copy of the context with `Context::applySettingsChanges`, in the same way as the refresh does, so that the profile is resolved. #132145 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
A source in a database with `lazy_load_tables` is a `StorageTableProxy` until something reads it. `StorageProxy` forwarded `supportsStreaming` but not `reportsStreamingCursor`, so the first incremental refresh after the database was attached refused a `MergeTree` source as an engine that does not report the cursor. Add a test for this and for a `profile` in the `SETTINGS` clause of the query of an incremental refresh. #132145 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ts-cursor' into HEAD
…ursor The block number of the cursor is an input of the query (and can come from the stored metadata of a refresh), so it can be the maximum of `Int64`. The increment `last_block_number + 1` was done in `Int64` before the check of the upper bound, which is undefined behavior. It is now done in unsigned arithmetic, and such a cursor is rejected with `BAD_ARGUMENTS`. Test: `05876_streaming_queries_memory_table_cursor_boundary`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A duplicate include of `QueryPipeline/QueryPipelineBuilder.h` and a missing `[[nodiscard]]` on `ReadFromMemoryStream::getName`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131860&sha=6451aeef1524155e4f2f10c2b7fc307bbea5bd58&name_0=PR&name_1=Build%20%28arm_tidy%2C%202%2F4%29 #131860 Co-Authored-By: Claude Fable 5.2 <[email protected]>
| cursor->setValue("epoch", static_cast<Int64>(processEpoch())); | ||
| cursor->setValue("generation", static_cast<Int64>(generation)); | ||
| cursor->setValue("block_number", static_cast<Int64>(next_block_number) - 1); | ||
| streaming_cursor->merge(cursor); |
There was a problem hiding this comment.
[Blocker] Persist the cursor when an Iceberg refresh produces no rows.
This report reaches the holder, but IcebergStorageSink::finalizeBuffers returns without committing metadata when writer_per_partition_key is empty (IcebergWrites.cpp:1701-1702). RefreshTask also skips Keeper cursor persistence for a transactional target, so a successful refresh that filters out every row loses its progress.
For a Memory source with max_rows_to_keep = 1, an IcebergLocal target, and AS SELECT v FROM src WHERE v > 0, insert and refresh separately with values 1, then 0, then 2. The first refresh persists block 0. The second consumes block 1 and succeeds with no output, but leaves the persisted cursor at block 0. The third resumes at block 1 after retention has advanced to block 2, and throws TOO_SLOW instead of appending 2. Every previous refresh fully consumed the source, yet the view is now unable to progress.
Commit the advanced cursor even for a refresh with no output rows, and add this three-refresh regression with an Iceberg target.
Support streaming queries from
Memorytables:SELECT ... FROM memory_table STREAMreturns the blocks that the table has at the start of the query, and then every block inserted later, in the order of the blocks of the table.STREAM BOUNDEDreturns the blocks the table has at the start of the query.The source follows the numbers of the blocks within a generation of the data (
BlocksWithCounts::generationandfirst_block_number, which already exist for the query condition cache). The table wakes up its streaming queries on every change of the data (setData); the source subscribes before it looks at the data, so it does not miss a change, and waits for new blocks on an event descriptor (Status::Async), without holding a thread of the pipeline.The query fails rather than return wrong data: if the data is replaced while it runs (by
TRUNCATE, a mutation or a restore, which start a new generation), it fails withABORTED, and if the blocks it has not read yet are removed bymax_rows_to_keepormax_bytes_to_keep, it fails withTOO_SLOW.WATERMARKis not supported.Test:
05773_streaming_queries_memory_table(bounded, unbounded with existing and new blocks, two subscribers, two concurrent producers,TRUNCATE, falling behindmax_rows_to_keep,CURSORrejected).Incremental refresh: a streaming read accepts the cursor
{epoch, generation, block_number}, and the bounded read reports it through the holder, so aMemorytable can be the source of an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL). The epoch is a random number of the server process, as the generations of the data are numbered anew in every process. A cursor of another process or of a generation that started empty (TRUNCATE) means that all the blocks are new; a generation rewritten by a mutation cannot be resumed after a position in a previous one, so the refresh fails. Tested by05773_streaming_queries_memory_table.The read is a step of its own (
ReadFromMemoryStream, aSourceStepWithFilter), so the planner plans an unbounded stream as a streaming query and rejects aggregation,ORDER BY, etc. withILLEGAL_STREAM. The row policy andPREWHEREare applied inside the pipe of the step, the policy first and in a transform of its own. The source looks at the data when it starts to read, so it gets the rows of a materialized CTE. Tested by05836_streaming_queries_memory_table_readingand05844_streaming_queries_memory_table_planning.This branch includes the changes of #132145 (the rejection of
LIMITand of the overflow modebreakin an incremental refresh, the retirement of the reported part of the cursor).Related: #42990
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) are supported forMemorytables: they return the existing blocks and then every block inserted later.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131860]