Repository navigation
Incremental refresh from any engine that reports the cursor of a streaming read - #132145
alexey-milovidov wants to merge 9 commits into
Conversation
…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]>
|
Workflow [PR], commit [376dde1] Summary: ❌
AI ReviewSummaryThe PR introduces Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Complete and synchronize the cursor for every bounded-read subscription before checkpoint persistence, and cover parallel early completion, including transactional target commits. |
| /// 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()) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
[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, 0There 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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
[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.
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes386 object files changed (+161.26 KiB total), 0 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 units1526 translation units recompiled, 7796 s compile time in total, 1526 of them have a recent master baseline. |
…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]>
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]>
…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]>
…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]>
|
🕵 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. |
|
This is #132281, and my open PR #132543 fixes it. The internal I ran both fuzzer queries (this one and the It is not a regression from #119183: 26.10.3.7 (tagged 2026-10-25, without #119183) already had it. There, |
The infrastructure for an incremental refresh of a refreshable materialized view (
APPEND INCREMENTAL) from tables other thanMergeTree, 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 supportSTREAM, which was true just forMergeTreetables; a source of another engine that supportsSTREAMbut does not report the cursor would be read from the beginning on every refresh, appending the same rows again. So:IStorage::reportsStreamingCursor(true forMergeTreeandReplicatedMergeTree): an incremental refresh accepts only such a source. The engine PRs below enable it together with the reporting.StreamingCursor::mergeand child holders (createChild), which place the cursor of a part of a composite read (a table ofMerge, a shard ofDistributed) 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.Mergetable 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 thelimit/offsetsettings) are rejected in the query of an incremental refresh: a read stopped early does not report a cursor that matches the appended rows.DISTINCTby constants, aLIMIT BYwithout keys) still gets the cursor after all the rows of the read, so the next refresh does not append the same rows again.breakof the*_overflow_modesettings is rejected in the query of an incremental refresh: a partial result would advance the cursor past the rows that were never appended.profilein theSETTINGSclause of the query is resolved to the settings of the profile.StorageProxyforwards the capability, so a source in a database withlazy_load_tablesthat is not loaded yet is accepted.Context.hthatStreamingCursorexists 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
MergeTreesources), which is in the merge queue; its only own commit replaces that restriction with the capability.The engine PRs, based on this one:
Merge: Streaming queries with cursors for Merge tables #131815Distributed(a newStreamingCursorpacket of the native protocol for the shards): Streaming queries with cursors for Distributed tables #131816Kafka: Streaming queries with cursors for Kafka tables #131818FileLog: Streaming queries with cursors for FileLog tables #131819NATS: Streaming queries with cursors for NATS JetStream tables #131820RabbitMQ: Streaming queries with cursors for RabbitMQ stream queues #131821Memory: Streaming queries from Memory tables #131860Null(stores nothing, so it stays refused): Streaming queries from Null tables: an ephemeral multi-producer multi-consumer queue #131859Related: #42990
Related: #131769
Related: #131814
Related: #131814 (comment)
Changelog category (leave one):
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/132145]