Skip to content

Incremental refresh from any engine that reports the cursor of a streaming read - #132145

Open
alexey-milovidov wants to merge 9 commits into
masterfrom
stream-incremental-refresh-reports-cursor
Open

alexey-milovidov wants to merge 9 commits into
masterfrom
stream-incremental-refresh-reports-cursor

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The infrastructure for an incremental refresh of a refreshable materialized view (APPEND INCREMENTAL) from tables other than MergeTree, which is one of the goals of #42990: infinite and consistent consumption of a stream, inserting into another table.

The refresh resumes from the cursor that the bounded streaming read of the previous refresh reports through Context::getStreamingCursor. The source was required only to support STREAM, which was true just for MergeTree tables; a source of another engine that supports STREAM but does not report the cursor would be read from the beginning on every refresh, appending the same rows again. So:

  • A new capability IStorage::reportsStreamingCursor (true for MergeTree and ReplicatedMergeTree): an incremental refresh accepts only such a source. The engine PRs below enable it together with the reporting.
  • StreamingCursor::merge and child holders (createChild), 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), so that a part of the cursor reported by a read replaces the same part of the cursor of the previous refresh.
  • The holder starts from the cursor of the previous refresh, so a part of the source that is not read this time (a table of a Merge table that stops matching for a while) keeps its position instead of being read again from the beginning. The first cursor reported under a path replaces the previous subtree there, so entries that the read no longer has (dropped partitions) are retired instead of accumulating.
  • LIMIT/OFFSET (and the limit/offset settings) are rejected in the query of an incremental refresh: a read stopped early does not report a cursor that matches the appended rows.
  • A query that stops the bounded read once the rest of the rows cannot change its result (a DISTINCT by constants, a LIMIT BY without keys) still gets the cursor after all the rows of the read, so the next refresh does not append the same rows again.
  • The value break of the *_overflow_mode settings is rejected in the query of an incremental refresh: a partial result would advance the cursor past the rows that were never appended.
  • These checks see the settings that the refresh runs with: a profile in the SETTINGS clause of the query is resolved to the settings of the profile.
  • StorageProxy forwards the capability, so a source in a database with lazy_load_tables that is not loaded yet is accepted.
  • A comment in Context.h that StreamingCursor exists only for the incremental refresh, and other streaming queries must not rely on it.

This PR is based on #131814 (an incremental refresh accepts only MergeTree sources), which is in the merge queue; its only own commit replaces that restriction with the capability.

The engine PRs, based on this one:

Related: #42990
Related: #131769
Related: #131814
Related: #131814 (comment)

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


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

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

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [376dde1]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR introduces IStorage::reportsStreamingCursor, composable cursor holders, and validation against refresh queries that could checkpoint partial results. The early-completion fix still permits an incomplete checkpoint when parallel subscriptions stop before starting their rounds, allowing subsequent successful refreshes to replay source rows.

Findings

❌ Blockers

  • MergeTreeCommitOrderSource.cpp:130: A successful bounded read must checkpoint every subscription consistently. ReadFromMergeTree::groupPartitionsByStreams creates sources for disjoint partition assignments. If a constant DISTINCT or keyless LIMIT BY closes the read while another source has not entered startRound, that source reports nothing, even after its pending work returns. Meanwhile, another source's first report clears the entire previous cursor in StreamingCursor::mergeAt. The persisted cursor therefore omits the stopped source's partitions and can lose their previous positions; a later refresh can replay them without new source writes. Complete the checkpoint for all subscriptions, including those stopped before round startup. This remains part of the existing early-completion finding; its fixing claim is incomplete for this parallel interleaving.
Tests
  • ⚠️ The new early-stop tests pass in Fast test, but force max_threads = 1. Add a focused stateless regression with partitions assigned to different subscriptions, delayed startup of one subscription, and repeated refreshes without source writes. Verify that previously saved partition positions survive too.
  • ⚠️ Verify early completion with an Iceberg target and multiple execution threads. IcebergStorageSink::initializeMetadata serializes the shared cursor during sink finalization, before the executor joins all upstream work. A downstream early-stop transform can finish while an upstream worker still delays shutdown propagation. The test must establish that the committed snapshot contains the completed cursor before another refresh resumes from it; the current early-stop tests use MergeTree targets only.
Missing context / blind spots
  • ⚠️ The parallel interleavings above were traced through the current source and executor code, not reproduced locally: this CI review environment has no ClickHouse binary, and nested test runs are prohibited. The focused regressions described above would close this gap. The partition-retirement test is excluded from Fast test; its broader CI result was not available during review.
Final Verdict

Status: ❌ Block

Complete and synchronize the cursor for every bounded-read subscription before checkpoint persistence, and cover parallel early completion, including transactional target commits.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 16, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... label Nov 16, 2026
/// The refresh resumes from the cursor that the read reports through `Context::getStreamingCursor`. A source
/// that supports STREAM but does not report the cursor would be read from the beginning on every refresh,
/// appending the same rows again.
if (!source->reportsStreamingCursor())

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 cursor reporting for the actual refresh query, including early completion

A MergeTree source passes this check even when the query stops it before it can report its cursor. With the PR's fast-test binary, an APPEND INCREMENTAL view defined as SELECT k FROM src LIMIT 1 SETTINGS max_block_size = 1, max_threads = 1, exact_rows_before_limit = 0 over 1,000 source rows appends [0] on its first refresh and leaves [0,0] in the target after the second refresh, with no intervening inserts and no reported exception.

LimitTransform closes its input, so MergeTreeCommitOrderSource::prepare takes handleShutdown instead of reaching surfaceFinalCursor. The refresh still succeeds and saves the empty/previous cursor. Thus the repeated-append failure this capability is meant to prevent remains reachable through an accepted source. This completion gap already exists in the underlying reader; the new engine capability alone does not enforce the contract.

Reject refresh queries that can terminate the source early, or ensure the bounded source is fully consumed and reports its cursor before accepting the refresh as successful. Add a stateless regression with two refreshes and no new source rows.

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 97cccb9: the query of an APPEND INCREMENTAL view now rejects LIMIT/OFFSET (and the limit/offset settings) for every source engine, including MergeTree, both at definition and before each refresh, since a read stopped early cannot report a cursor that matches the appended rows. LIMIT BY stays allowed because it does not stop the read. Covered by 05770_incremental_refreshable_mv_limit.

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 early-completion issue still reproduces on eaa3198c9f5e: src/Storages/StorageMaterializedView.cpp:187 checks ordinary LIMIT fields, but accepted LIMIT BY and DISTINCT queries can also close the source before it reports its cursor.

Using the PR's Fast test binary, a MergeTree source containing k = 0..99999 with both persisted block columns enabled, and an empty MergeTree target:

CREATE MATERIALIZED VIEW mv REFRESH EVERY 10 YEAR APPEND INCREMENTAL TO tgt EMPTY
AS SELECT k FROM src LIMIT 1 BY tuple()
SETTINGS max_block_size = 1, max_threads = 1, exact_rows_before_limit = 0;
SYSTEM REFRESH VIEW mv;
SYSTEM WAIT VIEW mv;
SELECT count(), sum(k) FROM tgt; -- 1, 0
SYSTEM REFRESH VIEW mv;
SYSTEM WAIT VIEW mv;
SELECT count(), sum(k) FROM tgt; -- 2, 0

There are no source writes between refreshes and both refreshes succeed. SELECT DISTINCT toUInt64(1) AS k FROM src with the same settings likewise appends 1 twice; SELECT DISTINCT k FROM src SETTINGS max_rows_in_distinct = 1, distinct_overflow_mode = 'break', max_block_size = 1, max_threads = 1 grows from 8192 to 16384 target rows.

LimitByTransform at line 276 and DistinctTransform at line 184 call stopReading; MergeTreeCommitOrderSource::prepare then takes handleShutdown, bypassing surfaceFinalCursor. The source needs to drain successfully before the refresh commits, or these early-terminating forms must also be rejected. The regression needs a source spanning multiple chunks; 1000 rows did not expose these cases in this binary.

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 a4ee690. MergeTreeCommitOrderSource::handleShutdown of a bounded read now finishes the running round and reports the cursor after all its rows when the query closes the source early. A DISTINCT by constants or a LIMIT BY without keys stops the read only when the rest of the rows cannot change the result, so these rows are consumed without being read and the next refresh does not get them again. If the query fails or is cancelled instead, the refresh fails and the cursor is discarded with it. The distinct_overflow_mode = 'break' form returns a partial result, so it is rejected (see the other thread). Covered by 05843_incremental_refreshable_mv_early_stop with a source of 100000 rows and repeated refreshes without source writes; the repros from this thread now leave one row in the target.

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 fix in a4ee690edb26 still leaves the original early-completion failure reachable with parallel subscriptions. At src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSource.cpp:130, a source stopped before startRound reports nothing, including when its work is still constructing pending_round. When that work returns, prepare goes straight to handleShutdown, so the pending round never contributes a cursor.

ReadFromMergeTree::groupPartitionsByStreams creates multiple such sources with disjoint partition assignments and a shared cursor holder. An allowed interleaving is that one source supplies the row for DISTINCT by a constant or LIMIT 1 BY tuple(), and the downstream transform closes the other sources before all their rounds start. The reporting source clears the entire seeded cursor at src/Interpreters/Context.cpp:5341, while an unstarted source publishes nothing. Consequently its partitions are absent from the saved cursor, including their previously persisted positions. The next refresh can read those partitions again without any intervening source writes.

Please make cursor completion cover every subscription of the bounded table read, including subscriptions stopped before their round starts, before persisting the checkpoint. The new early-stop regressions all force max_threads = 1; add a focused case with partitions assigned to different subscriptions and a delayed round start, then refresh again without inserting anything.

alexey-milovidov and others added 3 commits November 19, 2026 16:55
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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 376dde100 with master c93b9302b (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

386 object files changed (+161.26 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Context.cpp.o 3.67 MiB 3.72 MiB +49.85 KiB (+1.33%)

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

1526 translation units recompiled, 7796 s compile time in total, 1526 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits November 22, 2026 06:13
…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]>
alexey-milovidov added a commit that referenced this pull request Nov 22, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Nov 25, 2026
Merge `stream-incremental-refresh-reports-cursor` (#132145),
whose commits this branch includes: it rejects `LIMIT`, `OFFSET` and the overflow mode `break`
in the query of an incremental refresh, and a read replaces its part of the cursor of the previous refresh.

The conflict in `StreamingCursor` is resolved by keeping both `mergeAt` and `replaceAt`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 25, 2026
…ation and an early stop

- A file without a read position (no complete record was read yet, or the file was truncated)
  was not in the cursor of an incremental refresh, so the next refresh did not know the file
  after it was renamed to a name that does not match the path of the table, and its records
  were lost. Such a file is now in the cursor with its inode only.

- A file truncated and written again past the read position was taken for a file that was
  appended to, and the records before the position were lost. The read now keeps the evidence
  of the contents it has read (the first bytes of the file and the last record read), the
  cursor of an incremental refresh has its `fingerprint`, and the unbounded stream checks it
  at every poll. A file whose contents do not match is read from the beginning.

- A query that stops the read early (a `DISTINCT` by constants, a `LIMIT BY` without keys)
  finished the refresh without the cursor, so every refresh appended the same rows again.
  The bounded read of an incremental refresh now skips the remaining records without parsing
  and reports the cursor, as `MergeTreeCommitOrderSource` does. `LIMIT`, `OFFSET` and the
  overflow mode `break` are rejected by the validation merged from
  #132145.

Test: `05844_streaming_queries_file_log_refresh_positions`.

#131819 (comment)
#131819 (comment)
#131819 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov and others added 2 commits November 25, 2026 00:44
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI on a4ee690 had two failures unrelated to this PR:

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132145&sha=a4ee690edb26d1355058a60bf2a4688da5b42967&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

This is #132281, and my open PR #132543 fixes it.

The internal accurateOrNull cast of Tuple(Array(UInt128)) to Nullable(Tuple(Array(UInt64))) returns Nullable(Tuple(Array(Nullable(UInt64)))): the Nullable leaks into the array element. castOrDefault.cpp:231 then copies that column into the declared type, which trips the typeid assertion in debug and sanitizer builds. Release builds return a wrong value instead: on play (26.12.1.396) the SELECT from this report returns ([263974373728016]) instead of ([1]). The Unexpected return type from accurateCastOrNull STIDs in stress tests (3262-3c86, 3262-3a0d, 3262-3938, 3344-4ec5) are the same leak.

I ran both fuzzer queries (this one and the Enum8 one from the AST fuzzer run you linked) on a debug build of master 127ab3c: both abort on the same assertion at castOrDefault.cpp:231. With the diff of #132543 applied they return ([1]) and Code: 70 ... Cannot convert NULL to a non-nullable type, a normal exception.

It is not a regression from #119183: 26.10.3.7 (tagged 2026-10-25, without #119183) already had it. There, accurateCastOrDefault(tuple(materialize([toUInt16(1), toUInt16(2), toUInt16(300)])), 'Nullable(Tuple(Array(UInt8)))') returned ([144,230,155]), and the Unexpected return type fuzzer query threw LOGICAL_ERROR. So there is nothing to revert.

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-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants