Repository navigation
Streaming queries with cursors for NATS JetStream tables - #131820
alexey-milovidov wants to merge 13 commits into
Conversation
A streaming read of a `NATS` table with `nats_stream` 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. It starts after the stream
sequence in the cursor `{stream: sequence of the last read message}`; without the
cursor, the stream is read from the beginning. `STREAM BOUNDED` finishes once it
has read the messages pending at its start. The core NATS keeps no messages, so a
table without `nats_stream` does not support `STREAM`. An idle stream returns an
empty chunk after each poll, so that it does not hold a thread of the pipeline.
`WATERMARK` is not supported.
Related: #42990
Related: #131769
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [1761a68] Summary: ❌
AI ReviewSummaryAdds cursor-based streaming reads of Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Prevent soft read limits from committing an end-of-snapshot |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes395 object files changed (+352.72 KiB total), 1 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 units1527 translation units recompiled, 7863 s compile time in total, 1526 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]>
A bounded streaming read of a `NATS` table with `nats_stream` reports the stream sequence it read up to through the holder of an incremental refresh, so such a table can be the source of an incremental refresh. Related: #131814 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
… end for `STREAM BOUNDED` - `STREAM BOUNDED` captures the last sequence of the stream at its start and does not read the messages published later; previously it finished only when `NumPending` of a delivered message reached zero, so it could run forever while publishing continued. - Collecting a block takes at most `nats_poll_timeout_ms`: a steady stream of messages slower than `nats_max_block_size` per poll interval is returned as it arrives (e.g. `SELECT ... STREAM LIMIT 1` no longer waits for a full block). - The read uses an ephemeral pull consumer without acknowledgements instead of an ordered push consumer with unlimited pending limits, and fetches at most the rest of the block (no more than 1024 messages) at a time, so a query that stops reading does not accumulate messages in memory. A gap in the consumer sequence throws an exception instead of silently losing messages. The consumer is deleted at the end of the read, and the server deletes it after an hour of inactivity if that did not happen. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fresh A `LIMIT` (or the `limit` / `offset` settings) can close the source before the bounded streaming read finishes, and then the read does not report the cursor it advanced to: the refresh succeeds with the previous cursor, and every next refresh appends the same rows again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e_mv_limit` The rows of the target table were collected with `groupArray` over a sorted subquery, which does not keep the order with several threads: the test returned `[1,2,0]` instead of `[0,1,2]`. Use `arraySort`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131820&sha=906b9d467a4027ef3a633aa23acf8df2b8c56fc7&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 #131820 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…sor when the query stops reading early A query of an incremental refresh can stop reading its source before the bounded read finishes, not only with `LIMIT`: `LIMIT BY` and `DISTINCT` with constant keys and `LIMIT UNTIL` do it as well. The read then did not report its cursor, so the refresh succeeded with the previous cursor and the next one appended the same rows again. Instead of rejecting more kinds of queries, the sources now keep the invariant themselves: when the output of `MergeTreeCommitOrderSource` or `NATSStreamSource` is finished by the query during a bounded read, the source reports the end of the snapshot of the read as the cursor, the same as if the rest of it was read. The result of the query is the result over the whole snapshot, so nothing else has to be read from it. `LIMIT` and `OFFSET` remain rejected, now because the rows after the limit would be skipped by every refresh. Test: `05843_incremental_refreshable_mv_early_stop`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…urning rows `NATSStreamSource` reported the end of an early-stopped bounded read from `prepare`. If the query finished the output while `generate` was fetching, `prepare` ran only after the fetch, and a transactional target of an incremental refresh (`Iceberg`) could commit the old cursor meanwhile. The cursor after a successful bounded read is the last sequence of the stream at its start, so report it in `start`, before any row is returned. A read that is cancelled by a limit with the overflow mode `break` replaces it with the sequence of the last returned message, in the thread that checked the limit and before the last block is pushed, so the next refresh neither repeats nor skips messages. `IcebergStorageSink::initializeMetadata` now takes the mutex of the holder while it serializes the cursor, as `StreamingCursor::merge` does. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…able With `nats_max_block_size = 0` the fetch loop of `NATSStreamSource` never ran, so a streaming read returned empty chunks forever without fetching a message. `StorageNATS::readStream` now throws `BAD_ARGUMENTS`. `test_nats_stream_cursor` covers it, together with the cursor of an incremental refresh whose query stops reading early (`DISTINCT` of a constant) or is cut by `read_overflow_mode = 'break'`, over a table with one message per block. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| if (!stream_settings.subscribe_for_updates && current_round.has_value() && !isCancelled()) | ||
| { | ||
| read_state.finishReadRound(current_round->partitions, current_round->safe_block_numbers); | ||
| surfaceFinalCursor(); |
There was a problem hiding this comment.
[Blocker] Keep soft read limits from checkpointing unread MergeTree rows
!isCancelled() checks this wrapper, but a read limit with read_overflow_mode = 'break' cancels only the nested MergeTreeSource: ExecutionThreadContext calls processor.cancel when its progress callback returns false. That reader then finishes normally, while MergeTreeCommitOrderSource remains uncancelled. Both this path and the ordinary finishRound call ReadState::finishReadRound, which advances every changed partition to safe_block_number + 1, including unread rows.
For example, take the large source and cursor settings from 05843_incremental_refreshable_mv_early_stop and define an incremental refresh as:
AS SELECT k FROM src
SETTINGS max_block_size = 1, max_threads = 1,
max_rows_to_read = 2, read_overflow_mode = 'break'The definition passes validation. The first refresh can append only a small prefix, then persist the end-of-snapshot cursor; subsequent refreshes skip the rest permanently. The new NATSStreamSource rollback does not cover these nested readers, and ReplicatedMergeTree shares this streaming source.
Please propagate incomplete read status and prevent a successful checkpoint of the whole snapshot, or reject soft read limits for incremental refreshes. Add a stateless regression for this case that verifies unread rows are not silently checkpointed. This finding follows the current cancellation and cursor paths; it has not been executed locally.
Support streaming queries for
NATStables that read a JetStream stream (nats_stream). A streaming read reads the subjects of the table with its own ephemeral pull consumer without acknowledgements, so it does not affect the durable consumer of the table; it fetches no more than the rest of the output block at a time, so a stalled query does not accumulate messages in memory. It starts after the stream sequence in the cursor{stream: sequence of the last read message}; without the cursor, the stream is read from the beginning.STREAM BOUNDEDfinishes at the last sequence of the stream at its start, even if publishing continues. Collecting a block takes at mostnats_poll_timeout_ms. The core NATS keeps no messages, so a table withoutnats_streamdoes not supportSTREAM(ILLEGAL_STREAM). An idle stream returns an empty chunk after each poll.WATERMARKis not supported.Tests:
test_nats_stream_cursorandtest_nats_stream_concurrent_publishingin the existingtest_storage_nats/test_nats_jet_stream.py.The branch includes the commits of #131814 and #132145 (the infrastructure for an incremental refresh from tables other than
MergeTree).Incremental refresh: the bounded read reports
{stream: sequence}through the holder, so such a table can be the source of an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL). Tested bytest_nats_stream_cursor. When the query stops reading before the bounded read finishes (e.g.LIMIT BYorDISTINCTwith constant keys,LIMIT UNTIL), the read reports the end of its snapshot as the cursor, so the next refresh does not append the same rows again (05843_incremental_refreshable_mv_early_stop). ALIMITin the definition of an incremental refresh is rejected, because the rows after it would be skipped by every refresh (05770_incremental_refreshable_mv_limit).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 forNATStables with JetStream.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131820]