Skip to content

Refreshable MV dependencies overhaul - #104440

Merged
nikitamikhaylov merged 12 commits into
masterfrom
rmvd
May 26, 2026
Merged

nikitamikhaylov merged 12 commits into
masterfrom
rmvd

Conversation

@al13n321

@al13n321 al13n321 commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

  • Refreshable materialized view now supports REFRESH DEPENDS ON to trigger refreshes on another RMV's refreshes instead of time-based schedule. (REFRESH EVERY ... DEPENDS ON already existed, but couldn't be used reliably for this use case.) See CREATE MATERIALIZED VIEW documentation.

From documentation:

Using DEPENDS ON for consistent propagation latency {#using-depends-on-for-consistent-propagation-latency}

If both views use REFRESH EVERY with the same period, the dependency applies in each timeslot.

E.g. suppose views X and Y both use REFRESH EVERY 1 HOUR, and Y reads from X's output table. Without dependencies, Y would usually see X's data from previous hour's refresh. With DEPENDS ON X, Y's 11:00 refresh will start only after the X's 11:00 refresh completes.

           10:00            11:00            12:00
           │                │                │
  X:        [run]┐           [run]┐           [run]┐
                 │                │                │
  Y:             └►[run]          └►[run]          └►[run]

Both dependency and dependent may independently skip timeslots if refreshes run for longer than the refresh period. There's no guarantee that the dependent refreshes exactly once for each dependency refresh.

           10:00          11:00          12:00          13:00
           │              │              │              |
  X:        [run]┐         [run]┐         [run]┐         [run]┐
                 │              └────┐    (Y skips 12:00)     └───┐
  Y:             └►[10:00 ru------un]└►[11:00 ru---------------un]└►[13:00 run]

Using DEPENDS ON for batched stream processing {#using-depends-on-for-batched-stream-processing}

If REFRESH EVERY is not used, the dependent view X refreshes if all its dependencies refreshed at least once since X's last refresh. REFRESH AFTER T adds a delay: the dependent will start refresh T time after the dependency completes a refresh.

Circular dependencies are allowed and useful. Consider this graph of refreshable materialized views:

  1. X takes a batch of rows from some stream and puts them in a table.
  2. Then Y and Z both read from that table, do different aggregation, and append results to other tables.
  3. After the batch is fully processed, X takes the next batch, and the cycle repeats.
            source
               │
               ▼
          ┌─────────┐
     ┌───►│    X    │◄───┐
     │    └──┬───┬──┘    │
  DEPENDS    │   │    DEPENDS
    ON       ▼   ▼      ON
     │      ┌─┐ ┌─┐      │
     └──────┤Y│ │Z├──────┘
            └─┘ └─┘

Complete example:

CREATE TABLE current_batch (t UInt64, v Int64) ENGINE ReplicatedMergeTree ORDER BY t;
CREATE TABLE batch_log (max_t UInt64, n Int64, v_sum Int64, processed_at DateTime64) ENGINE ReplicatedMergeTree ORDER BY max_t;
CREATE TABLE stats (h UInt64, n UInt64) ENGINE ReplicatedSummingMergeTree ORDER BY h;

-- (system.numbers stands in for a data source with monotonically increasing timestamps or sequence numbers)
CREATE MATERIALIZED VIEW current_batch_v REFRESH EVERY 10 SECOND DEPENDS ON batch_log_v, stats_v TO current_batch AS SELECT number as t, number * 10 as v FROM system.numbers WHERE number > (SELECT max(max_t) FROM batch_log) LIMIT 100;

CREATE MATERIALIZED VIEW batch_log_v REFRESH DEPENDS ON current_batch_v APPEND TO batch_log AS SELECT max(t) as max_t, count() as n, sum(v) as v_sum, now64() as processed_at FROM current_batch;

CREATE MATERIALIZED VIEW stats_v REFRESH DEPENDS ON current_batch_v APPEND TO stats AS SELECT cityHash64(v) % 20 as h, count() as n FROM current_batch GROUP BY h;

-- Must trigger initial refresh manually.
SYSTEM REFRESH VIEW current_batch_v;

Longer chains work as well.

This only works well when refresh coordination is enabled, i.e. the views are in Replicated or Shared database. Without coordination, server restart breaks the cycle, requiring a manual SYSTEM REFRESH VIEW after each restart rather than once after creating the views.

Version info

  • Merged into: 26.6.1.170

@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd8d761]

Summary: ✅


AI Review

Summary

This PR overhauls refreshable materialized view dependency handling (DEPENDS ON for REFRESH AFTER, shorthand REFRESH DEPENDS ON, dependency-state persistence in Keeper, and expanded tests/docs). The core direction is good, but one replicated-path reliability risk remains in waitForLatestTargetTable, and there is one user-visible description mismatch in system.view_refreshes metadata.

Findings

⚠️ Majors

  • [src/Storages/MaterializedView/RefreshTask.cpp:571] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104440#discussion_r3212313978] waitForLatestTargetTable still hard-fails after a fixed 10-attempt exponential backoff window (~6.5s). On lagged replicated catalogs this can spuriously fail SYSTEM WAIT VIEW and dependency-triggered refreshes even though the expected table would appear shortly after.
    Suggested fix: replace the fixed-attempt cap with a timeout-based wait (or configurable timeout), and keep retrying until timeout/drop/cancel rather than treating lag beyond ~6.5s as a hard logical failure.

💡 Nits

  • [src/Storages/System/StorageSystemViewRefreshes.cpp:38] The next_refresh_time description claims NULL for MissingDependencies, but current behavior (including 02932_refreshable_materialized_views_3.reference) shows MissingDependencies can still have a concrete next_refresh_time for REFRESH EVERY ... DEPENDS ON ....
    Suggested fix: relax wording to say NULL only when the next time is unknown, without tying it unconditionally to MissingDependencies.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Address the bounded ~6.5s dependency visibility wait in waitForLatestTargetTable to avoid spurious failures under replica/catalog lag.
  2. Fix next_refresh_time column description wording to match observable behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 9, 2026

UInt64 backoff_ms = 100;
const UInt64 max_backoff_ms = 1000;
const int max_attempts = 10;

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 adds a hard cap of 10 retries with exponential backoff (~6.3s total) before throwing TABLE_UUID_MISMATCH.

That can make SYSTEM WAIT VIEW and dependency-triggered refreshes fail spuriously on slow replicas (replication lag or metadata propagation can exceed this window even though the table eventually appears). Previously this wait was open-ended and only failed on an actual refresh error/drop.

Please avoid a fixed short timeout here (or gate it behind a setting with a much safer default) so we do not convert transient lag into false refresh failures.

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 fixed retry window is still here (max_attempts = 10 with exponential backoff up to 1s, i.e. ~6.5s total).

I still think this is too short for replicated catalogs under lag: SYSTEM WAIT VIEW and dependency sync can fail with TABLE_UUID_MISMATCH even when the correct table appears shortly after. This converts transient replica lag into user-visible refresh failures.

Please avoid a hard short timeout here (or make it configurable with a safer default).

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 is still unresolved in the current code.

waitForLatestTargetTable still has a fixed max_attempts = 10 with exponential sleeps up to 1 second, then throws TABLE_UUID_MISMATCH.

That keeps the wait window around ~6.5 seconds, which is too short for realistic replication/catalog lag. This path is now used not only by SYSTEM WAIT VIEW, but also by dependency-triggered refresh via syncForDependentRefresh, so transient lag can still be converted into user-visible refresh exceptions.

Please remove the hard short timeout (or make it configurable with a safer default) so transient lag does not fail otherwise recoverable refresh flows.

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 is still live in the current code.

waitForLatestTargetTable still hard-fails after max_attempts = 10 (~6.5s total with exponential backoff). On replicated catalogs, table/metadata propagation can exceed this window under lag or recovery, so SYSTEM WAIT VIEW and dependency pre-sync can raise TABLE_UUID_MISMATCH even when the correct table appears shortly after.

Please avoid a fixed short timeout here (or make it configurable with a safer default and keep waiting by default).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Seems fine, I'd assume >6.5s is rare, and it's ok for WAIT VIEW to error out instead of stalling for a long time.

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.

Still seeing this as unresolved in the current code. waitForLatestTargetTable still has max_attempts = 10 with exponential backoff up to 1s (src/Storages/MaterializedView/RefreshTask.cpp, around lines 569-610), so it throws TABLE_UUID_MISMATCH after roughly 6.5s.

That turns transient metadata/replication lag into user-visible failures in two paths now using this helper: SYSTEM WAIT VIEW and dependency pre-sync (syncForDependentRefresh for non-APPEND). On replicated catalogs, table visibility can legitimately exceed this window during replica restart/recovery or Keeper reconnect.

Please avoid a hard short timeout here (or make it configurable with a conservative default), so these paths wait for convergence instead of failing on temporary lag.

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.

waitForLatestTargetTable still hard-fails after max_attempts = 10 (about 6.5s total with the current backoff) and throws TABLE_UUID_MISMATCH.

This path is now used by both SYSTEM WAIT VIEW and dependency pre-sync via syncForDependentRefresh, so transient replication/catalog lag can still become user-visible refresh exceptions even when the expected table appears shortly after.

Please avoid a fixed short timeout here (or make it configurable with a conservative default and keep waiting by default).

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.

Still seeing this as unresolved in the current head.

waitForLatestTargetTable still hard-fails after max_attempts = 10 (~6.5s total) and throws TABLE_UUID_MISMATCH (src/Storages/MaterializedView/RefreshTask.cpp, around lines 569-609).

That fixed short window turns transient replication/catalog lag into user-visible failures in both paths that now use this helper: SYSTEM WAIT VIEW and dependency pre-sync for non-APPEND views (syncForDependentRefresh). Lag above a few seconds is realistic during replica restart/recovery or Keeper reconnect, so this can fail flows that would otherwise converge.

Please remove the hard short cap (or make it configurable with a conservative default that keeps waiting by default).

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.

Still seeing this as unresolved in the current head.

waitForLatestTargetTable keeps a fixed max_attempts = 10 with exponential backoff (src/Storages/MaterializedView/RefreshTask.cpp, around lines 569-610), so it throws TABLE_UUID_MISMATCH after about 6.5s.

That is too short for realistic replicated metadata/table propagation under lag/recovery, and this helper is used in both SYSTEM WAIT VIEW and dependency pre-sync (syncForDependentRefresh for non-APPEND). So transient lag is still converted into user-visible failures even when convergence would happen shortly after.

Please avoid a hard short cap here (or make it configurable with a conservative default that waits by default).

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 still looks unresolved in current HEAD.

waitForLatestTargetTable keeps a fixed max_attempts = 10 with backoff capped at 1s, so this path throws TABLE_UUID_MISMATCH after roughly 6.5s.

That bounded wait is now on both user-visible paths:

  • SYSTEM WAIT VIEW (wait -> waitForLatestTargetTable)
  • dependency pre-sync for non-APPEND views (syncForDependentRefresh -> waitForLatestTargetTable)

On replicated catalogs, metadata/table visibility can legitimately exceed that window during replica restart/recovery or Keeper reconnect. In those cases this converts transient lag into refresh exceptions even though the expected table appears shortly after.

Please avoid a fixed short cap here (or make it configurable with a conservative default that keeps waiting by default), so dependency-triggered refresh and SYSTEM WAIT VIEW do not fail on temporary lag.

@al13n321
al13n321 marked this pull request as ready for review May 14, 2026 03:09
@al13n321

Copy link
Copy Markdown
Contributor Author

CI has 16 different test failures unrelated to this PR.

@al13n321

Copy link
Copy Markdown
Contributor Author

The one in FunctionsStressTest was already fixed in #104858

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

alexey-milovidov and others added 2 commits May 24, 2026 01:19
`aspell-dict.txt` was deleted in master along with the `aspell` and
`codespell` style checks. Removing the file here so the PR can merge
cleanly without a modify/delete conflict.
"Time when the latest refresh attempt finished (if known) or started (if unknown or still running). NULL if no refresh attempts happened since server startup or table creation."},
{"last_refresh_replica", std::make_shared<DataTypeString>(), "If coordination is enabled, name of the replica that made the current (if running) or previous (if not running) refresh attempt."},
{"next_refresh_time", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeDateTime>()), "Time at which the next refresh is scheduled to start, if status = Scheduled."},
{"next_refresh_time", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeDateTime>()), "Time at which the next refresh is scheduled to start. NULL if the next refresh time is not currently known, e.g. when waiting for dependencies (status `WaitingForDependencies` or `MissingDependencies`)."},

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 new description says next_refresh_time is NULL for MissingDependencies, but current behavior (and 02932_refreshable_materialized_views_3.reference) shows MissingDependencies can still have a concrete next_refresh_time (for REFRESH EVERY ... DEPENDS ON ...). Could we relax the wording so it doesn't promise NULL for all MissingDependencies cases?

@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 94.68% (534/564) | lost baseline coverage: 16 line(s) · Uncovered code

Full report · Diff report

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue May 26, 2026
Merged via the queue into master with commit b06071a May 26, 2026
166 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the rmvd branch May 26, 2026 22:53
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @al13n321 @nikitamikhaylov — a quick suggestion to help reviewers.

Description (currently empty):
A brief description explaining the new shorthand syntax, the deprecated settings, and the behavioral changes would help reviewers understand the scope of this overhaul.

Ignore this if intentional.

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

Labels

pr-improvement Pull request with some product improvements 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.

5 participants