Skip to content

Streaming queries with cursors for NATS JetStream tables - #131820

Open
alexey-milovidov wants to merge 13 commits into
masterfrom
stream-nats-tables
Open

alexey-milovidov wants to merge 13 commits into
masterfrom
stream-nats-tables

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Support streaming queries for NATS tables 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 BOUNDED finishes at the last sequence of the stream at its start, even if publishing continues. Collecting a block takes at most nats_poll_timeout_ms. The core NATS keeps no messages, so a table without nats_stream does not support STREAM (ILLEGAL_STREAM). An idle stream returns an empty chunk after each poll. WATERMARK is not supported.

Tests: test_nats_stream_cursor and test_nats_stream_concurrent_publishing in the existing test_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 by test_nats_stream_cursor. When the query stops reading before the bounded read finishes (e.g. LIMIT BY or DISTINCT with 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). A LIMIT in 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::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 NATS tables with JetStream.

🤖 Generated with Claude Code


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

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

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1761a68]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05182_compress_per_substream_in_compact_parts FAIL cidb
04908_group_by_top_k_max_k_cap NOT_FAILED cidb
05234_promql_result_timestamp_scale NOT_FAILED cidb
04836_time_series_v10_selector_whole_metric_pk_range NOT_FAILED cidb
05320_promql_duplicate_series_one_to_one_matching NOT_FAILED cidb
05293_promql_constant_scalar_arithmetic NOT_FAILED cidb
04891_timeseries_lowcardinality_id NOT_FAILED cidb
05234_promql_streaming_aggregation_memory NOT_FAILED cidb
05211_promql_present_over_time_absent_over_time NOT_FAILED cidb
05332_promql_set_operator_empty_on NOT_FAILED cidb
18 more test cases not shown
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds cursor-based streaming reads of NATS JetStream tables and enables them as incremental refresh sources. The earlier inline findings are addressed in the current code. One remaining correctness issue affects the modified MergeTree cursor-completion logic: a successful refresh stopped by a soft read limit can checkpoint rows it never appended.

Missing context / blind spots
  • ⚠️ Reviewed PR head 1761a68330bd31ebbb5089d47cbd5ba57d6a794d; the relevant checked-out files match its diff. The finding below is based on source tracing, without a local server run because this review job has no ClickHouse binary.
  • ⚠️ The current Praktika workflow is still running. The new stateless regressions passed in Fast test; targeted integration jobs, including the NATS coverage, are pending. Completed integration results would close that validation gap.
Findings

❌ Blockers

  • MergeTreeCommitOrderSource.cpp:127–130: A soft read limit can permanently skip unread source rows. With a large MergeTree source and max_block_size = 1, max_threads = 1, max_rows_to_read = 2, read_overflow_mode = 'break', the progress callback cancels the nested MergeTreeSource, which finishes without an exception. The enclosing MergeTreeCommitOrderSource remains uncancelled, treats its subpipeline as exhausted, and calls ReadState::finishReadRound through finishRound, advancing the cursor to safe_block_number + 1 despite reading only a prefix. The added shutdown check also tests only the enclosing processor. The refresh can succeed and persist that cursor, so later refreshes permanently skip the unread suffix. ReplicatedMergeTree shares this path. Propagate incomplete-read status and prevent a successful whole-snapshot checkpoint, or reject soft read limits for incremental refreshes. The corresponding NATS rollback does not cover nested MergeTree readers.
Tests
  • ⚠️ Add a stateless regression using the source fixture from 05843_incremental_refreshable_mv_early_stop with the soft read limit above. Verify that a partial refresh either fails without committing its cursor or resumes without losing unread rows. The existing early-stop tests cover query operators; the new soft-limit test covers only NATS.
Final Verdict

Status: ❌ Block

Prevent soft read limits from committing an end-of-snapshot MergeTree cursor for a partially read snapshot, and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 15, 2026
Comment thread src/Storages/NATS/NATSStreamSource.cpp Resolved
Comment thread src/Storages/NATS/NATSStreamSource.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1761a6833 with master 2b066904b (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

395 object files changed (+352.72 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/NATS/NATSStreamSource.cpp.o new 226.64 KiB +226.64 KiB

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

1527 translation units recompiled, 7863 s compile time in total, 1526 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
Comment thread src/Storages/NATS/NATSStreamSource.cpp Resolved
alexey-milovidov and others added 3 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]>
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]>
Comment thread src/Storages/NATS/StorageNATS.h Resolved
alexey-milovidov and others added 6 commits November 19, 2026 17:43
… 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]>
Comment thread src/Storages/NATS/NATSStreamSource.cpp Resolved
alexey-milovidov and others added 3 commits November 24, 2026 23:31
…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]>
Comment on lines +127 to +130
if (!stream_settings.subscribe_for_updates && current_round.has_value() && !isCancelled())
{
read_state.finishReadRound(current_round->partitions, current_round->safe_block_numbers);
surfaceFinalCursor();

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant