Skip to content

Streaming queries from Null tables: an ephemeral multi-producer multi-consumer queue - #131859

Open
alexey-milovidov wants to merge 15 commits into
masterfrom
stream-null-tables
Open

alexey-milovidov wants to merge 15 commits into
masterfrom
stream-null-tables

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Support streaming queries from Null tables: SELECT ... FROM null_table STREAM receives every block inserted into the table while the query runs. Any number of queries can insert into the table and subscribe to it at the same time, so a Null table works as an ephemeral queue with many producers and many consumers. The blocks inserted before the start of a subscription, or while there are no subscribers, are lost, and the materialized views of the table work as before.

The sink of the table pushes each inserted block (sharing its columns) to the subscriptions; with no subscribers, it does nothing, as before. The source of a subscription waits for blocks on an event descriptor (Status::Async), so an idle subscriber does not hold a thread of the pipeline. A subscriber never slows down the inserts: if it falls behind by more than 1024 blocks, its queued blocks are dropped and its query fails with TOO_SLOW. The table stores nothing, so CURSOR is rejected, and STREAM BOUNDED returns nothing. WATERMARK is not supported.

Test: 05773_streaming_queries_null_table (two subscribers with different columns and filters, two concurrent producers, the materialized view still gets the data, a lagging subscriber fails with TOO_SLOW, CURSOR rejected, BOUNDED empty).

Also, an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL) no longer succeeds when the read of its source is incomplete: LIMIT, LIMIT BY and DISTINCT are rejected in the definition, a refresh fails if the query closes the source before the end of its bounded read (otherwise the next refreshes would append the same rows again), and a limit on the amount of data to read throws even with read_overflow_mode = 'break' (otherwise the unread rows would be skipped). Tests: 05837_incremental_refreshable_mv_limit, 05875_incremental_refreshable_mv_incomplete_read.

Related: #42990

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A streaming query (SELECT ... FROM t STREAM) from a Null table receives every block inserted into it, so a Null table works as an ephemeral queue with many producers and many consumers.

🤖 Generated with Claude Code


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

alexey-milovidov and others added 3 commits November 15, 2026 16:03
A streaming query (`SELECT ... FROM null_table STREAM`) receives every block
inserted into the table while it runs, so the table works as an ephemeral queue
with many producers and many consumers. The sink of the table pushes the blocks
to the subscriptions, and the source of a subscription waits for them on an
event descriptor, without holding a thread of the pipeline. A subscriber does not
slow down the inserts: if it falls behind by more than 1024 blocks, its query
fails with `TOO_SLOW`. The table stores nothing, so `CURSOR` is rejected and
`STREAM BOUNDED` returns nothing. `WATERMARK` is not supported.

Related: #42990

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…test of STREAM from Null

The thousands of one-row blocks went to the `MergeTree` table of the view as
parts, and the delay of inserts for too many parts made the test time out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the test of STREAM from Null

The output of a client that exits while nothing reads its FIFO is lost.

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 [1624fba]


AI Review

Summary

Adds experimental streaming reads from Null tables and strengthens cursor handling for APPEND INCREMENTAL refreshes. One cursor-safety blocker remains: a timeout after source completion can discard downstream output while the refresh still succeeds and saves the advanced cursor.

Findings

❌ Blockers

  • ReadRoundContext.cpp:52, RefreshTask.cpp:1644: Executor timeouts can still commit a cursor past discarded output. The new override changes storage limits, while QueryStatus independently retains timeout_overflow_mode = 'break'. PipelineExecutor treats a timeout in this mode as partial success. If a blocking aggregate has consumed the source before a downstream expression or write exceeds the deadline, the source has already reported its cursor and hasUnfinishedReads is false. The refresh consequently records success and saves that cursor even if the aggregate result never reached the target; subsequent refreshes skip those source rows. Make the effective executor timeout throw, or check the deadline with OverflowMode::THROW before accepting refresh success. Continued on the existing partial-read-limit thread; the other prior findings are addressed.
Tests
  • ⚠️ Add a regression for a timeout after source completion, for example SELECT sum(k) + sleep(2) AS k FROM s SETTINGS max_threads = 1, max_execution_time = 1, timeout_overflow_mode = 'break'. The refresh must fail without accepting the advanced cursor. The current fast-test report passes 05773, 05836, 05837, and 05875, but the latter covers read-size overflow and early aggregation termination, not this executor path.
Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job. The remaining finding follows the current source, executor, and refresh control flow; the proposed timeout regression has not been executed here.
Final Verdict

Status: ❌ Block

Prevent timeout-driven partial success from saving the incremental cursor and add the downstream-timeout regression.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 15, 2026
Comment thread src/Storages/StorageNull.cpp Resolved
Comment thread src/Storages/NullTableSubscribers.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a979d1657 with master ffc535ce4 (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

394 object files changed (+230.65 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/NullTableSubscribers.cpp.o new 76.64 KiB +76.64 KiB
src/CMakeFiles/dbms.dir/Storages/StorageNull.cpp.o 438.72 KiB 481.49 KiB +42.77 KiB (+9.75%)

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

1523 translation units recompiled, 7731 s compile time in total, 1522 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... label Nov 15, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 16, 2026 16:40
alexey-milovidov and others added 2 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]>
alexey-milovidov and others added 5 commits November 19, 2026 15:31
…t is closed

When an outer `LIMIT` was satisfied by another branch of the pipeline, a source
of a streaming query from a `Null` table that waited in the async poller was
never woken up, and the query waited for the next insert. Wake it up from
`onUpdatePorts` and finish on a closed output before returning `Status::Async`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cribe

Ended subscriptions were removed only on insert, so starting and cancelling
streaming readers of a table without inserts (even `EXPLAIN PIPELINE`) grew
the list without a bound.

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]>
@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-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... labels Nov 20, 2026
if (const auto settings_ast = select.settings())
{
for (const auto & change : settings_ast->as<const ASTSetQuery &>().changes)
if ((change.name == "limit" || change.name == "offset") && !change.value.isNull() && change.value != Field(0))

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] Reject partial read limits before committing the snapshot cursor

The settings validation here still allows max_rows_to_read = 10, read_overflow_mode = 'break'. When that limit stops the inner read, ReadState::finishReadRound treats the truncated read as a completed snapshot and sets its position to safe_block_number + 1. The refresh succeeds and persists that cursor, permanently skipping the unread source rows.

Reproduced with the fast-test binary for this head:

CREATE TABLE s (k UInt64) ENGINE = MergeTree ORDER BY k
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1,
         index_granularity = 1;
CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO s SELECT number FROM numbers(100);
CREATE MATERIALIZED VIEW m
    REFRESH EVERY 10 YEAR APPEND INCREMENTAL TO t EMPTY
    AS SELECT k FROM s
    SETTINGS max_block_size = 1, max_threads = 1,
             max_rows_to_read = 10, read_overflow_mode = 'break';
SYSTEM REFRESH VIEW m;
SYSTEM WAIT VIEW m;
SELECT groupArray(k) FROM (SELECT k FROM t ORDER BY k); -- [0,1,2,3,4,5,6,7,8,9]
SYSTEM REFRESH VIEW m;
SYSTEM WAIT VIEW m;
INSERT INTO s VALUES (100);
SYSTEM REFRESH VIEW m;
SYSTEM WAIT VIEW m;
SELECT groupArray(k) FROM (SELECT k FROM t ORDER BY k); -- [0,1,2,3,4,5,6,7,8,9,100]

Rows 10–99 are never appended. This also reproduces with default granularity and 100,000 source rows: only the first 8,192 rows are appended before the cursor skips the remainder.

Please reject or override non-throwing read limits in the effective refresh settings, including settings inherited from profiles and the byte/leaf equivalents, or track the consumed position without treating a truncated scan as a completed snapshot. Add a regression proving unread rows cannot be skipped by a successful refresh.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in 1624fba. A read round whose cursor is going to be persisted (a bounded read with a StreamingCursor holder in the context) now gets its storage limits with the throw overflow mode, see makeStreamingSelectQueryInfo: this covers read_overflow_mode, read_overflow_mode_leaf and timeout_overflow_mode, for rows and bytes. It is applied to the effective limits of the query, so it does not matter whether they come from the SETTINGS of the query or from a profile.

The reproducer now fails the refresh with TOO_MANY_ROWS and the cursor is not advanced, so no rows are skipped. Regression test: 05875_incremental_refreshable_mv_incomplete_read.

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] The timeout case still permits partial success at this head. src/Storages/MergeTree/Streaming/ReadingPlan/ReadRoundContext.cpp:52 changes the storage limits, but QueryStatus separately captures timeout_overflow_mode from the refresh context (src/Interpreters/ProcessList.cpp:628–629). That value is still break. PipelineExecutor cancels the whole pipeline when its deadline expires (src/Processors/Executors/Runtime/V1/PipelineExecutor.cpp:460–463) and deliberately returns without an exception for this mode (:350–365).

If the source has already finished and downstream processing is still running, surfaceFinalCursor has already advanced the cursor and balanced both read counters. Consequently, the check at src/Storages/MaterializedView/RefreshTask.cpp:1644 passes even though cancellation discarded output before the target received it. The refresh succeeds and persists the advanced cursor, permanently skipping that output.

A focused regression case is a blocking aggregate followed by a delay:

CREATE TABLE s (k UInt64) ENGINE = MergeTree ORDER BY k
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO s VALUES (42);
CREATE MATERIALIZED VIEW m
    REFRESH EVERY 10 YEAR SETTINGS refresh_retries = 0
    APPEND INCREMENTAL TO t EMPTY
    AS SELECT sum(k) + sleep(2) AS k FROM s
    SETTINGS max_threads = 1, max_execution_time = 1,
             timeout_overflow_mode = 'break';
SYSTEM REFRESH VIEW m;
SYSTEM WAIT VIEW m;

This case is derived from the current code; I could not execute it because this review job has no ClickHouse binary. The aggregate requires the source to finish before the delayed expression runs; the executor then stops before that expression's result is pushed to the sink. Please make the executor's effective timeout throw for an incremental refresh, or explicitly check the deadline with OverflowMode::THROW before accepting success, and cover a timeout after source completion. Changing only the read-round limits cannot close this path.

alexey-milovidov and others added 3 commits November 25, 2026 04:19
…e is incomplete

An incremental refresh (`APPEND INCREMENTAL`) persists the cursor that the bounded read of the source reports
when it finishes. Two ways to make it wrong remained:

- The query closes the source before the end of the bounded read (`LIMIT ... UNTIL`, `LIMIT BY` and `DISTINCT`
  with constant keys, `group_by_overflow_mode = 'break'`, etc.). The read did not report the cursor, the refresh
  succeeded with the previous one, and every next refresh appended the same rows again. Now
  `validateIncrementalDefinition` also rejects `LIMIT ... UNTIL`, `LIMIT BY` and `DISTINCT`, and, for everything
  else, `MergeTreeCommitOrderSource` counts itself in `StreamingCursor` from its first read round until it reports
  the cursor, and `RefreshTask` fails the refresh if a read has not reported it (`hasUnfinishedReads`).

- A limit on the amount of data to read with the `break` overflow mode (`max_rows_to_read` with
  `read_overflow_mode = 'break'`, also the leaf and the timeout ones) truncated a read round, which
  `ReadState::finishReadRound` took for a completed one, so the cursor skipped the unread rows forever. Now the
  limits of a read round that reports the cursor always throw.

Also make the result of `05837_incremental_refreshable_mv_limit` independent of the order of rows in the target
table (it failed with `[1,2,0]` instead of `[0,1,2]` in CI):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131859&sha=a979d16577e8f6394108cd4cce0814e2e5cd9f8b&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#131859

Co-Authored-By: Claude Fable 5.2 <[email protected]>

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