Skip to content

Incremental RMV presist cursor in Iceberg snapshot - #114823

Merged
SmitaRKulkarni merged 11 commits into
masterfrom
Add_iceberg_incremental_rmv_cursor
Sep 15, 2026
Merged

SmitaRKulkarni merged 11 commits into
masterfrom
Add_iceberg_incremental_rmv_cursor

Conversation

@SmitaRKulkarni

@SmitaRKulkarni SmitaRKulkarni commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Support exactly-once incremental refresh of refreshable materialized views into Iceberg targets by committing the refresh cursor atomically inside the Iceberg snapshot summary.

depends on #114152

cc @alesapin @Michicosun


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

Version info

  • Merged into: 26.9.1.1509 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [618c349]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05182_join_order_conflict_detector_cast_null_propagation FAIL cidb
Stress test (amd_asan_ubsan) FAIL
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) FAIL cidb, issue

AI Review

Summary

This PR moves the incremental refreshable-MV cursor for transactional Iceberg targets into the Iceberg snapshot summary so restart recovery no longer depends on Keeper. The direct single-replica path is mostly wired up, but the current patch still has three correctness holes that can duplicate or replay data, plus one broad performance regression on every incremental view, so it is not ready to merge.

Findings

❌ Blockers

  • [src/Storages/MaterializedView/RefreshTask.cpp:1333-1337] The new exact-once path only recognizes a direct StorageObjectStorage target. TO can legally point at a wrapper such as StorageAlias, and AliasSink::onStart() copies the outer streaming_cursor into the nested insert context, so the inner Iceberg write still commits clickhouse.refresh-cursor into the snapshot. But RefreshTask stays on the non-transactional branch here, keeps resuming from/persisting only the local or Keeper cursor, and an Atomic deployment loses that cursor on restart. The next refresh then rereads from the beginning and re-appends rows even though the target snapshot already contains the durable cursor. Suggested fix: resolve wrappers before checking isTransactionalRefreshTarget() / loadRefreshCursor(), or expose that capability virtually on IStorage instead of relying on dynamic_cast<StorageObjectStorage *>.
  • [src/Storages/StorageMaterializedView.cpp:322,794; src/Storages/MaterializedView/RefreshTask.cpp:1331-1337; src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1349-1550] SETTINGS all_replicas = 1 explicitly disables cross-replica coordination, but transactional Iceberg now stores a single shared cursor in the table snapshot. Two replicas can therefore start from the same cursor, read the same source range, and race the catalog commit. When one replica loses the compare-and-swap, IcebergWrites retries by rereading metadata and committing the data files it already produced; it does not rerun the SELECT from the winner's new cursor. That permanently appends the same range twice on a shared target. Suggested fix: reject APPEND INCREMENTAL SETTINGS all_replicas = 1 for shared transactional Iceberg targets at DDL time, or add real cross-replica coordination for this mode.
  • [dismissed by author -- https://github.com/Incremental RMV presist cursor in Iceberg snapshot #114823#discussion_r3997809098] [src/Storages/MaterializedView/RefreshTask.cpp:1336; src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1237-1238] cursor_persisted_by_target is set before the code knows whether the Iceberg write actually committed a snapshot. finalizeBuffers() returns immediately when the refresh produced no data files, so a filtered incremental refresh can still advance the source STREAM cursor, skip both the Iceberg snapshot write and the Keeper fallback, and then lose that advanced cursor completely. I still consider this real because the current zero-row path never reaches initializeMetadata(), so the next refresh rereads the same source range forever. Suggested fix: persist the advanced cursor to Keeper when no snapshot was written, or emit an explicit empty snapshot that carries the cursor.

⚠️ Majors

  • [src/Storages/StorageMaterializedView.cpp:781-794; src/Interpreters/InterpreterInsertQuery.cpp:554-606] max_insert_threads = 1 is now forced for every APPEND INCREMENTAL view, not just the transactional Iceberg targets that need a single writer to couple data and cursor in one snapshot. For ordinary incremental views this has no correctness benefit, and on trivial INSERT ... SELECT refreshes it also collapses the read side to one thread via applyTrivialInsertSelectOptimization. Suggested fix: gate the setting on an actual transactional refresh target, or enforce the single-writer restriction inside the Iceberg sink only.
Tests
  • ⚠️ The new coverage only exercises direct single-replica targets that actually append rows. After the blocker fixes, please add focused regressions for TO through StorageAlias, for a zero-row incremental round, and for the all_replicas = 1 transactional-Iceberg combination (either a rejection test or a correctness test if the mode is supported).
Final Verdict

Status: ❌ Block

  • Minimum required actions: make transactional-target detection work through target wrappers, close the zero-row cursor-loss hole, and reject or coordinate all_replicas = 1 on shared transactional Iceberg targets. The unconditional single-threading regression should also be narrowed before merge.

LLVM Coverage Report

Measured on commit 618c349.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 110/118 (93.22%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 618c34944 with master e05544e98 (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

18 object files changed (+71.84 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/DataLakeRefreshCursorStore.cpp.o new 53.91 KiB +53.91 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

123 translation units recompiled, 1151 s compile time in total, 122 of them have a recent master baseline.

Job report

@SmitaRKulkarni SmitaRKulkarni changed the title [WIP] Incremental RMV presist cursor in Iceberg snapshot Incremental RMV presist cursor in Iceberg snapshot Aug 21, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... label Sep 4, 2026
/// - a transactional target table (e.g. Iceberg on a REST/filesystem catalog): the write path commits
/// the cursor atomically with the data files in one catalog compare-and-swap -> exactly-once, and
/// the refresh keeps the cursor out of Keeper entirely and reads it back from the target here.
class RefreshCursorStore

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not sure about this interface, it looks like it is possible to support RMT since we commit parts there atomically into the keeper, but that's just an illusion, since this interface heavily relies on the fact that the storage sink will not submit partially consumed data, without this it is not possible to correctly understand the right border of the cursor since reading is being made in unordered mode.

@SmitaRKulkarni SmitaRKulkarni Sep 12, 2026 •

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.

making max_insert_threads = 1. I think the right approach would be to wait for all inserts & write in Iceberg but it would be a big refactor (maybe in another pr).
Please let me know if you have any suggestions

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.

The smallest safe shape I see is to keep the interface Iceberg-only in this PR and make the optimization conditional on an actual metadata snapshot being committed. max_insert_threads = 1 removes the multi-sink case, but zero-output rounds still produce no Iceberg snapshot, so they need either an explicit empty-snapshot cursor commit or a fallback to the Keeper cursor for that round.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

As far as I know, Iceberg writes finalizes only at the end of the pipeline - that is why it is working right now even without max_insert_threads=1. My point was that let's not introduce a generic interface for that, since it may force someone to implement an invalid solution for another table.

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.

okay, got it. removed RefreshCursorStore

refresh_context->setSetting("parallel_replicas_for_non_replicated_merge_tree", Field(UInt64{0}));
refresh_context->setSetting("allow_insert_into_iceberg", Field(UInt64{1}));
/// A transactional target commits the whole round in one snapshot with the cursor, so it must be a single writer.
refresh_context->setSetting("max_insert_threads", Field(UInt64{1}));

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.

This only serializes sink creation inside one refresh on one replica. For APPEND INCREMENTAL SETTINGS all_replicas = 1 against a shared transactional Iceberg target (for example a REST catalog table, or a no-catalog table on shared object storage), multiple replicas can still start from the same table-level cursor, read the same source range, and race the metadata commit.

If replica A commits snapshot S1 with cursor C1 and replica B loses the compare-and-swap, B's retry loop does not rerun the SELECT from C1 or rebuild its data files. It just regenerates metadata around the rows it already read from C0, so the duplicate range is appended permanently once B succeeds on top of S1.

This needs a DDL-time rejection or real cross-replica coordination for shared transactional targets; max_insert_threads = 1 is not sufficient.

refresh_context->setSetting("parallel_replicas_for_non_replicated_merge_tree", Field(UInt64{0}));
refresh_context->setSetting("allow_insert_into_iceberg", Field(UInt64{1}));
/// A transactional target commits the whole round in one snapshot with the cursor, so it must be a single writer.
refresh_context->setSetting("max_insert_threads", Field(UInt64{1}));

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.

This forces max_insert_threads = 1 for every APPEND INCREMENTAL view, not just the transactional Iceberg targets that need a single writer to couple data and cursor in one snapshot. A regular incremental view writing to MergeTree still persists its cursor in Keeper only after the whole pipeline succeeds, so it can safely keep parallel insert threads.

As written, this silently serializes all existing incremental refreshes and can turn large INSERT SELECT rounds into single-threaded writes with no correctness benefit. Can we gate this on StorageObjectStorage::isTransactionalRefreshTarget() (or push it down into the Iceberg write path) instead of applying it unconditionally?

@Michicosun Michicosun self-assigned this Sep 14, 2026

@Michicosun Michicosun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Everything else LGTM

/// truth on resume; otherwise resume from the cursor in the Keeper coordination znode.
stream_cursor = execution.znode.cursor;
StoragePtr target_table = view->getTargetTable();
if (auto * object_storage = dynamic_cast<StorageObjectStorage *>(target_table.get());

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.

StorageMaterializedView::getTargetTable() can still return a wrapper such as StorageAlias, so this dynamic_cast<StorageObjectStorage *> misses TO alias_to_iceberg even though the nested insert eventually writes into the same transactional Iceberg table.

AliasSink::onStart() copies the outer context with Context::createCopy(getContext()), and ContextData copies streaming_cursor, so the inner Iceberg write still embeds clickhouse.refresh-cursor in the snapshot. But RefreshTask stays on the non-transactional path here, keeps resuming from/persisting only the local or Keeper cursor, and in the common Atomic case that cursor disappears on restart. The next refresh then rereads from the beginning and re-appends rows even though the Iceberg snapshot already has the correct cursor.

Please resolve wrappers before checking isTransactionalRefreshTarget() / loadRefreshCursor() (or make that capability virtual on IStorage) so alias targets participate in the same exact-once path as direct Iceberg tables.

@clickhouse-gh clickhouse-gh Bot added comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. and removed comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... labels Sep 15, 2026
@SmitaRKulkarni
SmitaRKulkarni added this pull request to the merge queue Sep 15, 2026
Merged via the queue into master with commit 6b8954c Sep 15, 2026
173 of 176 checks passed
@SmitaRKulkarni
SmitaRKulkarni deleted the Add_iceberg_incremental_rmv_cursor branch September 15, 2026 07:44
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants